np.pad函数在卷积神经网络的使用方法

np.pad主要就是三个参数
array 需要填充的数组
pad_width 是填充的形状
mode 填充的方法
举个例子就清楚了

arr1=np.array([1,1,1])
np.pad(arr1,(3,4),'constant')   #constant的缺省值为0 

在这里插入图片描述前面填充3位,后面填充4位。
mode还有一些其他的模式
‘edge’:用数组的边缘值填充。
‘maximum’ ‘mean’ ‘median’ ‘minimum’ 最大值,均值,中位数,最小值
用的不多,这里不再详细介绍,主要讲一下用0填充

二维情况;

arr2=np.array([[1,1,1],
              [1,1,1],
              [1,1,1]])
print(arr2)
np.pad(arr2,((1,1),(1,1)),'constant')   # 行,列

在这里插入图片描述

arr2=np.array([[1,1,1],
              [1,1,1],
              [1,1,1]])
print(arr2)
np.pad(arr2,((2,3),(1,3)),'constant')     # 行,列

在这里插入图片描述三维情况

arr3=np.array([[[1,1,1],
               [1,1,1],
               [1,1,1]],
               
              [[2,2,2],
              [2,2,2],
              [2,2,2]],
               
              [[3,3,3],
              [3,3,3],
              [3,3,3]]])
print(arr3)
np.pad(arr3,((0,0),(1,1),(1,1)),'constant')   # Z ,Y,X

在这里插入图片描述

arr3=np.array([[[1,1,1],
               [1,1,1],
               [1,1,1]],
               
              [[2,2,2],
              [2,2,2],
              [2,2,2]],
               
              [[3,3,3],
              [3,3,3],
              [3,3,3]]])
print(arr3)
np.pad(arr3,((2,1),(1,1),(1,1)),'constant')

在这里插入图片描述
在卷积网络中常常写成函数

def zero_pad(X, pad):
    """
    Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, 
    as illustrated in Figure 1.
    
    Argument:
    X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images
    pad -- integer, amount of padding around each image on vertical and horizontal dimensions
    
    Returns:
    X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C)
    """
    
    ### START CODE HERE ### (≈ 1 line)
    X_pad = np.pad(X, ((0,0), (pad,pad), (pad,pad), (0,0)), "constant")
    ### END CODE HERE ###
    
    return X_pad
np.random.seed(1)
x = np.random.randn(4, 3, 3, 2)
x_pad = zero_pad(x, 2)
print ("x.shape =", x.shape)
print ("x_pad.shape =", x_pad.shape)
fig, axarr = plt.subplots(1, 2)
axarr[0].set_title('x')
axarr[0].imshow(x[0,:,:,0])
axarr[1].set_title('x_pad')
axarr[1].imshow(x_pad[0,:,:,0])

在这里插入图片描述注意:(batch,H,W,C)分别表示,
batch_size, height, weight, channal

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开始King

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值