用numpy实现二维卷积
import numpy as np
# img = np.random.rand(2, 5, 5, 3)
img = np.ones([2, 5, 5, 4])
print("输入图像的尺寸", img.shape)
ker = np.ones([3, 3, 4, 6]) # 6 表示输出通道
def conv(img, ker, stride=1, padding=0):
size = list(img.shape)
pad_img = np.zeros([size[0], size[1] + 2 * padding, size[2] + 2 * padding, size[3]])
pad_img[:, padding:-padding, padding:-padding, :] = img
img = pad_img
out_size = (img.shape[1] - ker.shape[0]) // stride + 1
res = np.zeros([img.shape[0], out_size, out_size, ker.shape[3]])
for i in range(img.shape[0]): # minibatch的维度
for out_c in range(ker.shape[3]): # 卷积后的输出的通道数
for hi in range(0, out_size * stride, stride): # hi表示padding后原图的坐标 每一次都是移动stride大小
for wi in range(0, out_size * stride, stride):
region = img[i, hi:hi + ker.shape[0], wi:wi + ker.shape[0], :]
res[i, hi // stride, wi // stride, out_c] = np.sum(region * ker[:, :, :, out_c])
return res
stride = 2
padding = 1
fm = conv(img, ker, stride=stride, padding=padding)
print("stride = {} padding = {}".format(stride, padding))
print("输出的feature map 尺寸", fm.shape)
print(fm)