有没有一种快速的方法来“亚展平”或展平 numpy 数组中的一些第一个维度?
例如,给定一个维度为 (50,100,25)
的 numpy 数组,结果维度将是 (5000,25)
your_array[50:100, 7, :]
将 3d 对象展平为 2d,仅使用第 7 个切片作为第 2 维。
array[0:50,7,:]
,它给出了大小 (50,25)
,丢弃了 99% 的数据。
看看 numpy.reshape 。
>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)
>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape
# (5000, 25)
# One shape dimension can be -1.
# In this case, the value is inferred from
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)
对亚历山大的回答稍作概括 - np.reshape 可以将 -1 作为参数,意思是“数组总大小除以所有其他列出的维度的乘积”:
例如展平除最后一个维度之外的所有维度:
>>> arr = numpy.zeros((50,100,25))
>>> new_arr = arr.reshape(-1, arr.shape[-1])
>>> new_arr.shape
# (5000, 25)
对彼得的回答稍作概括——如果您想超越三维数组,您可以在原始数组的形状上指定一个范围。
例如展平除最后两个维度之外的所有维度:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
编辑:对我之前的回答稍作概括——当然,您也可以在重塑的开头指定一个范围:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
另一种方法是使用 numpy.resize()
,如:
In [37]: shp = (50,100,25)
In [38]: arr = np.random.random_sample(shp)
In [45]: resized_arr = np.resize(arr, (np.prod(shp[:2]), shp[-1]))
In [46]: resized_arr.shape
Out[46]: (5000, 25)
# sanity check with other solutions
In [47]: resized = np.reshape(arr, (-1, shp[-1]))
In [48]: np.allclose(resized_arr, resized)
Out[48]: True
numpy.vstack
非常适合这种情况
import numpy as np
arr = np.ones((50,100,25))
np.vstack(arr).shape
> (5000, 25)
我更喜欢使用 stack
、vstack
或 hstack
而不是 reshape
,因为 reshape
只是扫描数据并且似乎将其强制转换为所需的形状。如果您要取列平均值,这可能会出现问题。
这是我的意思的说明。假设我们有以下数组
>>> arr.shape
(2, 3, 4)
>>> arr
array([[[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]],
[[7, 7, 7, 7],
[7, 7, 7, 7],
[7, 7, 7, 7]]])
我们应用这两种方法来获得一个形状数组 (3,8)
>>> arr.reshape((3,8)).shape
(3, 8)
>>> np.hstack(arr).shape
(3, 8)
但是,如果我们看看它们在每种情况下是如何被重塑的,hstack
将允许我们获取我们也可以从原始数组中计算出来的列总和。使用 reshape 这是不可能的。
>>> arr.reshape((3,8))
array([[1, 2, 3, 4, 1, 2, 3, 4],
[1, 2, 3, 4, 7, 7, 7, 7],
[7, 7, 7, 7, 7, 7, 7, 7]])
>>> np.hstack(arr)
array([[1, 2, 3, 4, 7, 7, 7, 7],
[1, 2, 3, 4, 7, 7, 7, 7],
[1, 2, 3, 4, 7, 7, 7, 7]])
不定期副业成功案例分享
arr.flatten(dimensions=(0, 1))
。arr.reshape((-1,2))
。arr.reshape(arr.shape[0] * arr.shape[1], arr.shape[2])