【问题标题】:Divide matrix into square 2x2 submatrices - maxpooling fprop将矩阵划分为正方形 2x2 子矩阵 - maxpooling fprop
【发布时间】:2018-05-07 14:21:05
【问题描述】:

我正在尝试为 Conv Networks 中的 MaxPooling 层实现 fprop,没有重叠和池化区域 2x2。为此,我需要将输入矩阵拆分为大小为 2x2 的矩阵,以便提取最大值。然后我正在创建一个掩码,稍后我可以在bprop 中使用它。为了进行拆分,我首先垂直拆分输入矩阵,然后水平拆分,然后分别使用vsplithsplitamax 找到最大值。但是,由于索引超出范围异常,这一直在崩溃,我不确定错误在哪里。有没有更简单的方法将 24 x 24 输入矩阵拆分为 144 个 2x2 矩阵,以便获得最大值。

为此,我正在执行以下操作:

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]

等等……

【问题讨论】:

  • 添加一个示例案例并向我们展示预期的输出?
  • @Divakar 在编辑中添加了示例
  • 但是最终的预期输出是什么?这将有助于创建块 - stackoverflow.com/questions/16856788/…

标签: python numpy matrix machine-learning deep-learning


【解决方案1】:

第 1 步:获取max_ind_xmax_ind_y

我们需要获取每块最大元素的行、列索引 -

m,n = inputs.shape
a = 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, col
out[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]: inputs
Out[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]: out2d
Out[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]])

【讨论】:

    【解决方案2】:

    这在skimage.util 中实现为view_as_blocks

    blocks = skimage.util.view_as_blocks(a,(2,2))
    maxs = blocks.max((2,3))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 2016-11-12
      相关资源
      最近更新 更多