求和之前的numpy数组扩展

问题描述

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

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

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

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

之后:新形状(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”循环语句,我更喜欢数组函数或数组操作。 预先感谢您的帮助!

解决方法

重塑并使用np.broadcast_to

x_out = np.broadcast_to(x[...,None,:],(2,2,3,3))

Out[1131]:
array([[[[ 0,1,2],[ 0,2]],[[ 3,4,5],[ 3,5]]],[[[ 6,7,8],[ 6,8]],[[ 9,10,11],[ 9,11]]]])
,

repeat给出了所需的结果。结果并不能像'broadcast_to`那样提高内存效率,但可能更容易理解:

In [78]: x = np.arange(12).reshape(2,3)

In [81]: x1 = x[:,:,:].repeat(3,2)
In [82]: x1
Out[82]: 
array([[[[ 0,11]]]])

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