求和前的 numpy 数组扩展
numpy array extension before sum
我想将加载数据的数组的维度增加 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”循环语句,我更喜欢数组函数或数组操作。
在此先感谢您的帮助!
重塑并使用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]]]])
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)
我想将加载数据的数组的维度增加 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”循环语句,我更喜欢数组函数或数组操作。 在此先感谢您的帮助!
重塑并使用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]]]])
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)