将矩阵分成2×2的子矩阵 – maxpooling fprop

我在尝试实现卷积网络中无重叠且池化区域为2×2的MaxPooling层的fprop。为了实现这一点,我需要将输入矩阵分割成2×2大小的矩阵,以便提取最大值。然后,我创建一个掩码,以便在bprop中后续使用。为了进行分割,我首先垂直然后水平分割输入矩阵,并分别使用vsplithsplitamax来找到最大值。然而,这总是会因为索引超出边界异常而崩溃,我不确定错误出在哪里。是否有更简单的方法将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产生的输出:

enter image description here

而我想要的是

[0 1  4 5][2 3  6 7]

依此类推…


回答:

步骤#1:获取max_ind_xmax_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]])

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注