默認情況下,ND數組(例如A)與一維1(B)的乘法是在最后一個軸上執行的,這意味著乘法A * B僅在下有效
A.shape[-1] == len(B)
要在另一個軸上將A與B相乘而不是-1,一種解決方法是在相乘前后交換A的軸:
要在軸“ axis”上乘以A和B,請使用
C = (A.swapaxes(axis, -1) * B).swapaxes(axis, -1)
示例
A = np.arange(2 * 3 * 4).reshape((2, 3, 4))
B = np.array([0., 1., 2.])
print(A, B)
array([[[ 0., 0., 0., 0.],
[ 4., 5., 6., 7.],
[16., 18., 20., 22.]],
[[ 0., 0., 0., 0.],
[16., 17., 18., 19.],
[40., 42., 44., 46.]]])
C = A * B
ValueError: operands could not be broadcast together with shapes (2,3,4) (3,)
C = (A.swapaxes(1, -1) * B).swapaxes(1, -1)
array([[[ 0., 0., 0., 0.],
[ 4., 5., 6., 7.],
[16., 18., 20., 22.]],
[[ 0., 0., 0., 0.],
[16., 17., 18., 19.],
[40., 42., 44., 46.]]])
請注意,A的第一個原始數已乘以0
最后的原始數乘以2