【问题标题】:numpy array extension before sumsum 之前的 numpy 数组扩展
【发布时间】:2020-09-22 22:50:52
【问题描述】:

我想将加载数据的数组的维度增加 1。在总结神经网络的隐藏层之前。例如,我以某种方式想到:

之前: x = np.arange(12).reshape(2,2,3)

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

 [[ 6  7  8]
  [ 9 10 11]]]

之后:新形状(2,2,3,3)

[[[[ 0.  1.  2.]
   [ 0.  1.  2.]
   [ 0.  1.  2.]]

  [[ 3.  4.  5.]
   [ 3.  4.  5.]
   [ 3.  4.  5.]]]


 [[[ 6.  7.  8.]
   [ 6.  7.  8.]
   [ 6.  7.  8.]]

  [[ 9. 10. 11.]
   [ 9. 10. 11.]
   [ 9. 10. 11.]]]]

我不想使用“for”循环语句,我更喜欢数组函数或数组操作。 提前感谢您的帮助!

【问题讨论】:

    标签: python arrays numpy multidimensional-array dimension


    【解决方案1】:

    repeat 给出了想要的结果。结果不像'broadcast_to`那样节省内存,但它可能更容易理解:

    In [78]: x = np.arange(12).reshape(2,2,3)
    
    In [81]: x1 = x[:,:,None,:].repeat(3,2)
    In [82]: x1
    Out[82]: 
    array([[[[ 0,  1,  2],
             [ 0,  1,  2],
             [ 0,  1,  2]],
    
            [[ 3,  4,  5],
             [ 3,  4,  5],
             [ 3,  4,  5]]],
    
    
           [[[ 6,  7,  8],
             [ 6,  7,  8],
             [ 6,  7,  8]],
    
            [[ 9, 10, 11],
             [ 9, 10, 11],
             [ 9, 10, 11]]]])
    

    另一个,x[:,:,None]*np.ones((3,1),int)

    【讨论】:

      【解决方案2】:

      重塑和使用np.broadcast_to

      x_out = np.broadcast_to(x[...,None,:], (2,2,3,3))
      
      Out[1131]:
      array([[[[ 0,  1,  2],
               [ 0,  1,  2],
               [ 0,  1,  2]],
      
              [[ 3,  4,  5],
               [ 3,  4,  5],
               [ 3,  4,  5]]],
      
      
             [[[ 6,  7,  8],
               [ 6,  7,  8],
               [ 6,  7,  8]],
      
              [[ 9, 10, 11],
               [ 9, 10, 11],
               [ 9, 10, 11]]]])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-22
        • 1970-01-01
        • 1970-01-01
        • 2019-08-31
        • 1970-01-01
        • 2017-12-15
        • 1970-01-01
        • 2020-04-15
        相关资源
        最近更新 更多