numpy如何实现填充(使用常数值)?

3

我将尝试在Theano中实现numpy的pad函数,以constant模式为例。在numpy中如何实现这个函数?假设填充值仅为0。

给定一个数组

a = np.array([[1,2,3,4],[5,6,7,8]])
# pad values are just 0 as indicated by constant_values=0
np.pad(a, pad_width=[(1,2),(3,4)], mode='constant', constant_values=0)

将返回

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0],
       [0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

现在,如果我事先知道a的维度数量,我可以通过创建一个新数组来实现这一点,该数组的新维度填充填充值,并填写此数组中的相应元素。但是,如果我不知道输入数组的维度呢?虽然我仍然可以从输入数组推断出输出数组的维度,但如果不知道其中的维度数量,则无法对其进行索引。或者我错过了什么吗?
也就是说,如果我知道输入维度是3,那么我可以执行以下操作:
zeros_array[pad_width[0][0]:-pad_width[0][1], pad_width[1][0]:-pad_width[1][1], pad_width[2][0]:-pad_width[2][1]] = a

其中的 zeros 数组是使用输出维度创建的新数组。

但如果我事先不知道 ndim,我就无法这样做。


np.pad 的源代码在这里:https://github.com/numpy/numpy/blob/master/numpy/lib/arraypad.py - jmilloy
1个回答

2

我的本能是这样做:

def ...(arg, pad):
    out_shape = <arg.shape + padding>  # math on tuples/lists
    idx = [slice(x1, x2) for ...]   # again math on shape and padding
    res = np.zeros(out_shape, dtype=arg.dtype)
    res[idx] = arg     # may need tuple(idx)
    return res

换句话说,创建目标数组,并使用适当的索引元组复制输入。这将需要一些数学计算和迭代来构建所需的形状和切片,但如果繁琐的话应该是直截了当的。
然而,似乎np.pad在轴上进行迭代(如果我已经确定了正确的替代品:
   newmat = narray.copy()
   for axis, ((pad_before, pad_after), (before_val, after_val)) \
            in enumerate(zip(pad_width, kwargs['constant_values'])):
        newmat = _prepend_const(newmat, pad_before, before_val, axis)
        newmat = _append_const(newmat, pad_after, after_val, axis)

其中_prepend_const的含义是:

np.concatenate((np.zeros(padshape, dtype=arr.dtype), arr), axis=axis)

(而append方法也是类似的)。因此,它会为每个维度单独添加每个前缀和后缀。从概念上讲,这很简单,即使可能不是最快的。

In [601]: np.lib.arraypad._prepend_const(np.ones((3,5)),3,0,0)
Out[601]: 
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])

In [604]: arg=np.ones((3,5),int)
In [605]: for i in range(2):
     ...:     arg=np.lib.arraypad._prepend_const(arg,1,0,i)
     ...:     arg=np.lib.arraypad._append_const(arg,2,2,i)
     ...:     
In [606]: arg
Out[606]: 
array([[0, 0, 0, 0, 0, 0, 2, 2],
       [0, 1, 1, 1, 1, 1, 2, 2],
       [0, 1, 1, 1, 1, 1, 2, 2],
       [0, 1, 1, 1, 1, 1, 2, 2],
       [0, 2, 2, 2, 2, 2, 2, 2],
       [0, 2, 2, 2, 2, 2, 2, 2]])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接