# 互相关计算
def correlation_calc(view, kernel):
return np.sum(view * kernel)
def numpy_conv(inputs, kernel, strides, padding):
in_channels, H, W = inputs.shape
kernel_c, kernel_h, kernel_w = kernel.shape
assert kernel_c == in_channels
stride_h, stride_w = strides
padding_h = padding[0]
padding_w = padding[1]
# 构造padding后的输入
padding_data = np.zeros((in_channels, H + 2 * padding_h, W + 2 * padding_w))
padding_data[:, padding_h: H + padding_h, padding_w: W + padding_w] = inputs
# 构造输出
out_h = (H + 2 * padding_h - kernel_h) // stride_h + 1
out_w = (W + 2 * padding_w - kernel_w) // stride_w + 1
outputs = np.zeros((out_h, out_w))
# 滑动窗口
for i in range(out_h):
for j in range(out_w):
view = padding_data[:, i * stride_h: i * stride_h + kernel_h, j * stride_w: j * stride_w + kernel_w]
outputs[i][j] = correlation_calc(view, kernel)
return outputs
输出多通道计算
def multi_channels_conv(inputs, kernels, strides, padding):
outputs = []
for kernel in kernels:
outputs.append(numpy_conv(inputs, kernel, strides, padding))
return numpy.array(outputs)