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