问题背景
用numpy实现一个2d卷积,不允许调用其他库函数。
代码
import numpy as np
def conv2d(input_array, kernel):
batch_size, in_channel, height, width = input_array.shape
in_channel, out_channel, k_height, k_width = kernel.shape
output_height = height - k_height + 1
output_width = width - k_width + 1
output_array = np.empty((batch_size, out_channel, output_height, output_width))
for b in range(batch_size):
for oc in range(out_channel):
for h in range(output_height):
for w in range(output_width):
output_array[b, oc, h, w] = np.sum(
input_array[b, :, h:h+k_height, w:w+k_width] * kernel[:, oc, :, :]
)
return output_array
input_array = np.random.randn(1, 3, 256, 256)
kernel = np.random.randn(3, 3, 3, 3)
print(conv2d(input_array=input_array, kernel=kernel).shape)
print('OK')