Numpy1.7.0(添加^{}时)现在已经很旧了(2013年发布),所以即使问题是不使用而需要一种方法,我还是认为知道如何使用^{}来实现这个功能是很有用的。
其实很简单:>>> import numpy as np
>>> a = np.array([[ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.],
... [ 1., 1., 1., 1., 1.]])
>>> np.pad(a, [(0, 1), (0, 1)], mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
在本例中,我使用0是mode='constant'的默认值。但也可以通过显式地传递它来指定:>>> np.pad(a, [(0, 1), (0, 1)], mode='constant', constant_values=0)
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
就在第二个参数([(0, 1), (0, 1)])看起来很混乱的情况下:每个列表项(在本例中是元组)对应于一个维度,其中的项表示之前(第一个元素)和之后(第二个元素)的填充。所以:[(0, 1), (0, 1)]
^^^^^^------ padding for second dimension
^^^^^^-------------- padding for first dimension
^------------------ no padding at the beginning of the first axis
^--------------- pad with one "value" at the end of the first axis.
在这种情况下,第一和第二个轴的填充是相同的,因此也可以传入2元组:>>> np.pad(a, (0, 1), mode='constant')
array([[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0.]])
如果前后填充相同,甚至可以省略元组(但在本例中不适用):>>> np.pad(a, 1, mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 1., 1., 1., 1., 1., 0.],
[ 0., 0., 0., 0., 0., 0., 0.]])
或者,如果轴的前后填充相同但不同,也可以省略内部元组中的第二个参数:>>> np.pad(a, [(1, ), (2, )], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
不过,我倾向于总是使用明确的一个,因为它很容易犯错误(当你的意图与你的期望不同时):>>> np.pad(a, [1, 2], mode='constant')
array([[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 1., 1., 1., 1., 1., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0.]])
在这里,NumPy认为你想在所有的轴上加上一个元素在每个轴之前,两个元素在每个轴之后!即使您打算在轴1中填充1个元素,在轴2中填充2个元素。
我使用元组列表作为填充,注意这只是“我的约定”,您也可以使用元组列表或元组列表,甚至数组元组。NumPy只检查参数的长度(或者如果它没有长度)和每个项的长度(或者如果它有长度)!