我正在尝试在 python 中实现二维卷积。我有一组尺寸的输入图像(m、64、64、3),其中 m 是图像的数量。我想对高度和宽度使用过滤器大小 f=8 和 stride=8,并使用相同的填充,以便保留输入宽度和高度 (64, 64)。
使用公式[n' = floor((n-f+2*pad)/stride + 1)]并输入 n'=64, n=64, stride=8, f=8,我得到pad=224,其中大得不合理。
比如我取了m,图片数量为1080,估计是内存出错,系统崩溃了。
但是当我使用 Keras 库和以下代码时,它运行良好。
X = keras.layers.Conv2D(filters=32, kernel_size=(8, 8), strides=(8, 8), padding='same')(X)
这是我在 python 中的 Conv2D 实现:
import numpy as np
# A.shape = (1080, 64, 64, 3)
# W.shape = (8, 8, 3, 32)
# b.shape = (32,)
def conv_fwd(A, W, b, pad=0, stride=1):
pad_A = np.pad(A, ((0, 0), (pad, pad), (pad, pad), (0, 0)), mode='constant')
(m, w, h, nc) = A.shape
(fw, fh, ncc, ncn) = W.shape
if nc != ncc:
raise Exception('Number of channels in kernel and input do not match')
wn = int((w-fw+2*pad)/stride + 1)
hn = int((h-fh+2*pad)/stride + 1)
A_n = np.zeros((m, wn, hn, ncn))
W = W.reshape(fw*fh*ncc, ncn)
for i in range(wn):
for j in range(hn):
A_n[:, i, j] = pad_A[:, i*stride:i*stride+fw, j*stride:j*stride+fh].reshape(m, fw*fh*nc).dot(W) + b
return A_n
所以我假设在 keras 中计算填充有不同的过程。我试图寻找源代码,但找不到它。它是如何工作的?