【问题标题】:Multiple 2D numpy arrays in 1 array1 个数组中的多个 2D numpy 数组
【发布时间】:2021-04-09 18:25:48
【问题描述】:

我正在研究基本神经网络的反向传播,对于每个示例,我都必须计算新的权重。我将权重保存在一个名为 weights 的二维 numpy 数组中,如下所示:

 [[0.09719335 0.03077288 0.84256845 0.78993436]
 [0.87452232 0.9833483  0.803617   0.46675746]
 [0.77805488 0.11567956 0.63747511 0.14045771]]

对于新的权重,我需要一对神经元之间每个权重的平均值。我的想法是为我的训练集中的所有数据项计算它,然后计算平均值。 为此,我想用 np.zeros 制作一个零数组,上面数组的大小乘以我的集合中的数据项数量。我是这样试的

newWeights = np.zeros((2,(weights.shape)))

但这没有用。有没有办法像这样初始化一个数组,或者有没有另一种方法可以让我更容易做到这一点 (我想过 np.append 但无法弄清楚)

【问题讨论】:

    标签: python arrays numpy numpy-ndarray


    【解决方案1】:

    weights.shape 是一个元组,因此不能按原样包含它,因为维度必须是整数。您可以使用 * 解包元组:

    newWeights = np.zeros((2, *weights.shape))
    

    这基本上解开了weights.shape,因此它相当于尺寸的 (2, x, y)。

    【讨论】:

      【解决方案2】:

      你可以这样做

      import numpy as np
      arr = np.array( [[0.09719335, 0.03077288, 0.84256845, 0.78993436],
       [0.87452232, 0.9833483,  0.803617,   0.46675746],
       [0.77805488, 0.11567956, 0.63747511, 0.14045771]])
      
      arr3D = np.zeros((2,*arr.shape))
      

      然后你像这样在 3D 数组中保存一个 2D 数组:

      arr3D[0,:,:] = arr
      

      平均数组的计算是这样的:

      mean_arr = arr3D.mean(axis=0)
      

      【讨论】:

        【解决方案3】:

        假设您可以就地修改 weights-array,np.ndarray.resize 会将您的数组大小调整为 (2, 3, 4) 并使用 0 填充新值:

        import numpy as np
        
        weights = np.asarray([[0.09719335, 0.03077288, 0.84256845, 0.78993436], [0.87452232, 0.9833483, 0.803617, 0.46675746],
                        [0.77805488, 0.11567956, 0.63747511, 0.14045771]])
        print(weights.shape) # (3, 4)
        
        weights.resize((2, *weights.shape), refcheck=False)
        print(weights.shape) # (2, 3, 4)
        
        [[[0.09719335 0.03077288 0.84256845 0.78993436]
          [0.87452232 0.9833483  0.803617   0.46675746]
          [0.77805488 0.11567956 0.63747511 0.14045771]]
        
         [[0.         0.         0.         0.        ]
          [0.         0.         0.         0.        ]
          [0.         0.         0.         0.        ]]]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-19
          • 2021-08-15
          • 2022-07-08
          • 2022-01-07
          相关资源
          最近更新 更多