可以使用 .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/