提供新形状要满足的标准是'新形状应该与原始形状兼容'
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) 重塑。结果新形状为 (12,) 并且与原始形状 (3,4) 兼容
z.reshape(-1)
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
现在尝试用 (-1, 1) 重塑。我们提供了 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]])
以上与numpyadvice/error message 一致,将reshape(-1,1) 用于单个功能;即单列
如果您的数据具有单一特征
,请使用 array.reshape(-1, 1) 重塑您的数据
新形状为 (-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]])
以上与numpyadvice/error message一致,单样使用reshape(1,-1);即单行
如果数据包含单个样本
,则使用 array.reshape(1, -1) 重塑您的数据
新形状 (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