在Numpy的reshape函数中,给三个参数有什么意义,第一个是-1?
In reshape function of Numpy, what is the significance of giving three parameters, where the first one is -1?
arr = np.array([[1, 2, 3, 4, 5, 6]])
newarr = arr.reshape(-1,3,2)
newarr
以上是我做的代码。这是输出:
array([[[1, 2],
[3, 4],
[5, 6]]])
但我不明白-1 做了什么。 -1 单独应该使数组变平,即将多维数组转换为一维数组。当 -1 与 2,3 一起使用时,输出发生了什么?
正如 numpy.reshape docs 所说:
One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
也就是说,-1表示“请计算出这个形状的尺寸”。它将被计算以使元素的数量与原始数组中的相同。
在您的示例中,由于其余形状尺寸为 2 和 3,因此已经涵盖了所有 6 个元素。因此,推断的(第一个)形状维度必须为 1,结果数组的形状为 (1, 2, 3)。
另一个例子:
arr = np.arange(27) # 1-dim array of 27 elements
newarr = arr.reshape(-1,3,3)
在这种情况下,生成的 newarr.shape
将是 (3,3,3),因此您得到 27 个元素。
arr = np.array([[1, 2, 3, 4, 5, 6]])
newarr = arr.reshape(-1,3,2)
newarr
以上是我做的代码。这是输出:
array([[[1, 2],
[3, 4],
[5, 6]]])
但我不明白-1 做了什么。 -1 单独应该使数组变平,即将多维数组转换为一维数组。当 -1 与 2,3 一起使用时,输出发生了什么?
正如 numpy.reshape docs 所说:
One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.
也就是说,-1表示“请计算出这个形状的尺寸”。它将被计算以使元素的数量与原始数组中的相同。
在您的示例中,由于其余形状尺寸为 2 和 3,因此已经涵盖了所有 6 个元素。因此,推断的(第一个)形状维度必须为 1,结果数组的形状为 (1, 2, 3)。
另一个例子:
arr = np.arange(27) # 1-dim array of 27 elements
newarr = arr.reshape(-1,3,3)
在这种情况下,生成的 newarr.shape
将是 (3,3,3),因此您得到 27 个元素。