NumPy 1.7.0(当添加[(0, 1), (0, 1)]时)现在已经很老了(它于2013年发布),因此即使该问题要求一种不使用该功能的方法,我认为了解使用[(0, 1), (0, 1)]如何实现也是有用的。
实际上很简单:
>>> 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, 1), (0, 1)]作为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.]])
但是,我倾向于始终使用显式的,因为这样做很容易出错(当NumPys的期望与您的意图有所不同时):
>>> 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个元素,在每个轴后填充2个元素! 即使您打算用轴1中的1个元素和轴2中的2个元素填充。
我使用元组列表进行填充,请注意,这只是“我的约定”,您也可以使用元组列表或元组甚至数组元组的列表。 NumPy只是检查参数的长度(如果没有长度)和每个项目的长度(或者如果有长度)!