【发布时间】:2019-09-28 20:08:40
【问题描述】:
我正在尝试使用 Numpy 在 Python 中实现卷积层。
输入是一个形状为 [N, H, W, C] 的 4 维数组,其中:
-
N: 批量大小 -
H: 图片高度 -
W: 图片宽度 -
C:频道数
卷积滤波器也是一个形状为[F, F, Cin, Cout]的4维数组,其中
-
F: 方形滤镜的高度和宽度 -
Cin:输入通道数(Cin = C) -
Cout: 输出通道数
假设沿所有轴的步幅为 1,并且没有填充,输出应该是形状为 [N, H - F + 1, W - F + 1, Cout] 的 4 维数组。
我的代码如下:
import numpy as np
def conv2d(image, filter):
# Height and width of output image
Hout = image.shape[1] - filter.shape[0] + 1
Wout = image.shape[2] - filter.shape[1] + 1
output = np.zeros([image.shape[0], Hout, Wout, filter.shape[3]])
for n in range(output.shape[0]):
for i in range(output.shape[1]):
for j in range(output.shape[2]):
for cout in range(output.shape[3]):
output[n,i,j,cout] = np.multiply(image[n, i:i+filter.shape[0], j:j+filter.shape[1], :], filter[:,:,:,cout]).sum()
return output
这很好用,但是使用了四个 for 循环并且非常慢。有没有更好的方法来使用 Numpy 实现一个卷积层,它接受 4 维输入和过滤,并返回一个 4 维输出?
【问题讨论】:
-
我在尝试重现这一点时遇到了困难。你能给一个样品过滤器吗?由此判断,
filter.shape[3],是 4 维的吗? -
过滤器是 4 维的。样本过滤器可以是
filter = np.random.randint(0, 2, [5, 5, 3, 16])。这将是一个 5 X 5 过滤器,它对三通道输入图像进行操作并生成具有 16 个通道的输出“图像”。 -
好的,我有时间去看看
标签: python arrays numpy conv-neural-network