Search code examples
pythonarraysnumpymultidimensional-arraydimension

numpy array extension before sum


I want to increase the dimension of an array loaded with data by 1. Before sum up an hidden layer of a neural network. Somehow I thought for example:

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

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

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

after: new shape(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.]]]]

I don't want to use a "for" loop statement, I prefer array functions or array operations. Thanks in advance for the help!


Solution

  • repeat gives the desired result. The result isn't a memory efficient as the 'broadcast_to`, but it may be easier to understand:

    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]]]])
    

    Another, x[:,:,None]*np.ones((3,1),int)