我在尝试实现卷积网络中无重叠且池化区域为2×2的MaxPooling层的fprop。为了实现这一点,我需要将输入矩阵分割成2×2大小的矩阵,以便提取最大值。然后,我创建一个掩码,以便在bprop
中后续使用。为了进行分割,我首先垂直然后水平分割输入矩阵,并分别使用vsplit
、hsplit
和amax
来找到最大值。然而,这总是会因为索引超出边界异常而崩溃,我不确定错误出在哪里。是否有更简单的方法将24 x 24的输入矩阵分割成144个2×2的矩阵,以便我能获取最大值。
我正在做以下操作来实现这一点:
for i in range(inputs.shape[0]): for j in range(inputs.shape[1]): for k in range(inputs.shape[2] // 2): for h in range(inputs.shape[3] // 2): outputs[i,j,k,h] = np.amax(np.hsplit(np.vsplit(inputs[i,j], inputs.shape[2] // 2)[k], inputs.shape[1] // 2)[h]) max_ind = np.argmax(np.hsplit(np.vsplit(inputs[i,j], inputs.shape[2] // 2)[k], inputs.shape[1] // 2)[h]) max_ind_y = max_ind // inputs.shape[2] if (max_ind_y == 0): max_ind_x = max_ind else: max_ind_x = max_ind % inputs.shape[3] self.mask[i,j,max_ind_y + 2 * k, max_ind_x + 2 * h] = outputs[i,j,k,h]
编辑:
这是reshape产生的输出:
而我想要的是
[0 1 4 5][2 3 6 7]
依此类推…
回答:
步骤#1:获取max_ind_x
,max_ind_y
我们需要获取每个块中最大元素的行列索引 –
m,n = inputs.shapea = inputs.reshape(m//2,2,n//2,2).swapaxes(1,2)row, col = np.unravel_index(a.reshape(a.shape[:-2] + (4,)).argmax(-1), (2,2))
步骤#2:使用输入中的argmax位置设置输出数组
然后,从你的代码来看,你似乎是试图创建一个输出数组,并在那些argmax
位置设置输入数组的值。因此,我们可以这样做 –
out = np.zeros_like(a)M,N = a.shape[:2]indx_tuple = np.arange(M)[:,None],np.arange(N), row, colout[indx_tuple] = a[indx_tuple]
最后,我们可以将输出恢复到2D形状,这将是对原始输入inputs
的一个很好的验证步骤 –
out2d = out.reshape(a.shape[:2]+(2,2)).swapaxes(1,2).reshape(m,n)
样本输入,输出 –
In [291]: np.random.seed(0) ...: inputs = np.random.randint(11,99,(6,4))In [292]: inputsOut[292]: array([[55, 58, 75, 78], [78, 20, 94, 32], [47, 98, 81, 23], [69, 76, 50, 98], [57, 92, 48, 36], [88, 83, 20, 31]])In [286]: out2dOut[286]: array([[ 0, 0, 0, 0], [78, 0, 94, 0], [ 0, 98, 0, 0], [ 0, 0, 0, 98], [ 0, 92, 48, 0], [ 0, 0, 0, 0]])