python - -1 在 numpy reshape 中是什么意思?

标签 python numpy reshape numpy-ndarray

可以使用 .reshape(-1) 将 2D 数组重新整形为 1D 数组。 例如:

>>> a = numpy.array([[1, 2, 3, 4], [5, 6, 7, 8]])
>>> a.reshape(-1)
array([[1, 2, 3, 4, 5, 6, 7, 8]])

通常,array[-1] 表示最后一个元素。 但是这里的 -1 是什么意思呢?

最佳答案

提供新形状要满足的标准是'新形状应该与原始形状兼容'

numpy 允许我们将新的形状参数之一指定为 -1(例如:(2,-1) 或 (-1,3) 但不是 (-1, -1))。它只是意味着它是一个未知维度,我们希望 numpy 弄清楚它。 numpy 将通过查看'数组的长度和剩余维度' 并确保它满足上述条件来计算这一点

现在看例子。

z = np.array([[1, 2, 3, 4],
         [5, 6, 7, 8],
         [9, 10, 11, 12]])
z.shape
(3, 4)

现在尝试用 (-1) reshape 。结果新形状为 (12,) 并且与原始形状 (3,4) 兼容

z.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])

现在尝试用 (-1, 1) reshape 。我们提供 column 为 1 但 rows 为 unknown 。所以我们得到的结果新形状为 (12, 1)。再次与原始形状 (3,4) 兼容

z.reshape(-1,1)
array([[ 1],
   [ 2],
   [ 3],
   [ 4],
   [ 5],
   [ 6],
   [ 7],
   [ 8],
   [ 9],
   [10],
   [11],
   [12]])

以上与 numpy 建议/错误信息一致,将 reshape(-1,1) 用于单个特征;即单列

Reshape your data using array.reshape(-1, 1) if your data has a single feature

新形状为 (-1, 2)。行未知,第 2 列。我们得到的结果新形状为 (6, 2)

z.reshape(-1, 2)
array([[ 1,  2],
   [ 3,  4],
   [ 5,  6],
   [ 7,  8],
   [ 9, 10],
   [11, 12]])

现在尝试将列保持为未知。新形状为 (1,-1)。即,行为 1,列未知。我们得到结果新形状为 (1, 12)

z.reshape(1,-1)
array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12]])

以上与numpy建议/错误信息一致,对单个样本使用reshape(1,-1);即单行

Reshape your data using array.reshape(1, -1) if it contains a single sample

新形状 (2, -1)。第 2 行,列未知。我们得到结果新形状为 (2,6)

z.reshape(2, -1)
array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])

新形状为 (3, -1)。第 3 行,列未知。我们得到结果新形状为 (3,4)

z.reshape(3, -1)
array([[ 1,  2,  3,  4],
   [ 5,  6,  7,  8],
   [ 9, 10, 11, 12]])

最后,如果我们尝试将两个维度都提供为未知,即新形状为 (-1,-1)。会报错

z.reshape(-1, -1)
ValueError: can only specify one unknown dimension

关于python - -1 在 numpy reshape 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691084/

相关文章:

r - 同一图中的多个变量

python - 为什么这个小部件位于菜单栏的顶部?

python - 使用 Matplotlib 注释正态分布图中的四分位数

python - 将圆投影到正方形上?

python - 使用Rasterio保存窗口图像(另存为jpg)

python - 将高斯混合模型拟合到单个特征数据的正确方法是什么?

r - 如何在一列内有条件地计数(对于所有行)并循环遍历所有列以在 R 中创建列联表

python - 基于日期时间数据在 matplotlib 中使用 axvline 添加垂直线

python - 将 2 位字符串数字列表转换为 2 位整数列表

python - 为什么python在函数和类中使用不同的作用域机制?