代码之家  ›  专栏  ›  技术社区  ›  Alk

将矩阵分解为平方2x2子矩阵-最大池fprop

  •  2
  • Alk  · 技术社区  · 7 年前

    我正在尝试在没有重叠和池区域2x2的Conv网络中为MaxPooling层实现fprop。为此,我需要将输入矩阵拆分为2x2大小的矩阵,以便提取最大值。然后我创建了一个面具,我可以稍后在中使用 bprop . 为了进行拆分,我首先垂直拆分输入矩阵,然后水平拆分,然后使用 vsplit , hsplit amax 分别地然而,由于索引越界异常,这会不断崩溃,我不确定错误在哪里。是否有更简单的方法将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]
    

    编辑:

    这是整形产生的输出:

    enter image description here

    我想要的是

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

    等等

    2 回复  |  直到 7 年前
        1
  •  2
  •   B. M.    7 年前

    这是按照以下方式实现的: view_as_blocks 在里面 skimage.util :

    blocks = skimage.util.view_as_blocks(a,(2,2))
    maxs = blocks.max((2,3))
    
        2
  •  1
  •   Divakar    7 年前

    第1步:获取 max_ind_x , max_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]])