np.pad()

在写作业的时候遇到的,np.pad()就像剥洋葱一样,一层一层的加。

比如说:

arr3D = np.array([[[1, 1, 2, 2, 3, 4],
                   [1, 1, 2, 2, 3, 4],
                   [1, 1, 2, 2, 3, 4]],

                  [[0, 1, 2, 3, 4, 5],
                   [0, 1, 2, 3, 4, 5],
                   [0, 1, 2, 3, 4, 5]],

                  [[1, 1, 2, 2, 3, 4],
                   [1, 1, 2, 2, 3, 4],
                   [1, 1, 2, 2, 3, 4]]])

这样一个array, 做下面这个操作:

np.pad(array, ((x1, y1), (x2, y2), (x3, y3)), 'constant')

(x1, y1)是对最外面这个中括号操作的,就是对这个中括号里面的元素, 按照尺寸,首尾分别添加 x1, y1 个零array(图示为我在终端的操作)。

>>> np.pad(arr3D, ((1, 1), (0, 0), (0, 0)), 'constant')
array([[[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]],

       [[1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4]],

       [[0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5]],

       [[1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4]],

       [[0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0]]])

那么同理可得(x2,y2)就是对第二个中括号首尾加上同规格的零array。

注意arr3D没有变哦。

>>> np.pad(arr3D, ((0,0),(1,1),(0,0)), 'constant')
array([[[0, 0, 0, 0, 0, 0],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 1, 2, 3, 4, 5],
        [0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [1, 1, 2, 2, 3, 4],
        [0, 0, 0, 0, 0, 0]]])

以此类推,(X3,y3)就是对第三组中括号,最小的那组,首尾添加x3,y3个同规格零元素,这里就是0。

>>> np.pad(arr3D, ((0,0),(0,0),(1,1)), 'constant')
array([[[0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0]],

       [[0, 0, 1, 2, 3, 4, 5, 0],
        [0, 0, 1, 2, 3, 4, 5, 0],
        [0, 0, 1, 2, 3, 4, 5, 0]],

       [[0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0]]])
>>> 

我们最后来测试一下维度:

>>> out = np.pad(arr3D, ((0,0),(1,1),(1,1)), 'constant')
>>> out
array([[[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 0, 1, 2, 3, 4, 5, 0],
        [0, 0, 1, 2, 3, 4, 5, 0],
        [0, 0, 1, 2, 3, 4, 5, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]],

       [[0, 0, 0, 0, 0, 0, 0, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 1, 1, 2, 2, 3, 4, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]]])
>>> out.shape
(3, 5, 8)

也就是说,array的维度也是从中括号由外往里进行的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值