关于 -1 意义的一般问题

General question about the significance of -1

我正在研究机器学习中的一个问题,我看到 [-1] 在代码的不同位置频繁出现,但我似乎无法理解它的重要性。

在此特定示例中,目标是稍微移动训练集中的所有图像。

代码如下:

from scipy.ndimage.interpolation import shift

def shift_image(image, dx, dy):
    image = image.reshape((28, 28))
    shifted_image = shift(image, [dy, dx], cval=0, mode="constant")
    return shifted_image.reshape([-1])

最后一行的-1有什么意义?

这一行:

shifted_image.reshape([-1])

只是简单地以一个列表作为参数调用reshape方法,而这个列表恰好包含一个元素,即数字-1。这具有重塑 numpy 数组的效果。来自文档:

One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions

在 numpy 数组中,reshape 允许您在尝试重塑数组时 "infer" 其中一个维度。

import numpy as np
a = np.arange(4).reshape(2,2)
#Output:
array([[0, 1],
       [2, 3]])
a.reshape([-1])
#Output:
array([0, 1, 2, 3])

如果您注意到,您还可以使用推理重写第一个重塑,如下所示:

b =np.arange(4).reshape(2,-1)
#Output:
array([[0, 1],
       [2, 3]])