numpy广播机制
Broadcast
广播(Broadcast)是numpy对不同形状(shape)的数组进行数值计算的方式,对数组的算术运算通常在相应的元素上进行。如果两个数组a和 b形状相同,即满足 a.shape == b.shape,那么a*b的结果就是a与b数组对应位相乘。这要求维数相同,且各维度的长度相同。
import numpy as np
a = np.array([1.0,2.0,3.0])
b = np.array([2.0,2.0,2.0])
print(a*b)
#[2. 4. 6.]
import numpy as np
a = np.array([1.0,2.0,3.0])
b = 2.0
print(a*b)
#[2. 4. 6.]
In order to broadcast, the size of the trailing axes for both arrays in anoperation must either be the same size or one of them must be one.
两个数组维度不相同进行计算时会进行广播机制,将两个数组维度列出向右对齐,从最后开始匹配,只有相等或者其中一个为1的情况下才会进行广播机制
import numpy as np
a = np.array([[0.0, 0.0, 0.0],
[10.0, 10.0, 10.0],
[20.0, 20.0, 20.0],
[30.0, 30.0, 30.0],
])
b = np.array([0.0, 1.0, 2.0])
print(a.shape)#(4, 3)
print(b.shape)#(3,)
print(a+b)
#[[ 0. 1. 2.]
# [10. 11. 12.]
# [20. 21. 22.]
# [30. 31. 32.]]
#可以进行广播机制
Image (3d array): 256 x 256 x 3
Scale (1d array): 3
Result (3d array): 256 x 256 x 3
A (4d array): 9 x 1 x 7 x 1
B (3d array): 8 x 1 x 5
Result (4d array): 9 x 8 x 7 x 5
A (2d array): 5 x 4
B (1d array): 1
Result (2d array): 5 x 4
A (3d array): 15 x 3 x 5
B (3d array): 15 x 1 x 1
Result (3d array): 15 x 3 x 5
#不能进行广播机制
A (1d array): 10
B (1d array): 12
A (2d array): 2 x 1
B (3d array): 8 x 4 x 3
#Broadcast提供了一种更便捷的计算方式:
import numpy as np
a = np.array([0.0, 10.0, 20.0,30.0])
b = np.array([0.0, 1.0, 2.0])
print(a[:,np.newaxis]+b)
#[[ 0. 1. 2.]
#[10. 11. 12.]
#[20. 21. 22.]
#[30. 31. 32.]]