几种情况:
这里只讲加减,矩阵乘法严格按照矩阵乘法规则(尾首同)。
- 注意比较维度数时从右至左。
- (2, 3, 5)维数为3, 各维维度数为2, 3, 5
1.维数相等时。
- 各维度数均相等。这个不需多说。按位运算即可。
- 至少有一维维度数不等,不可广播。
Exception:上条中,不等的维度数,有为1者,可广播。
看例子:
a = np.arange(9).reshape( 3, 3)
b = np.arange(6).reshape( 2, 3)
print(a, "\n", b, "\n", a+b)
# ValueError: operands could not be broadcast together with shapes (3,3) (2,3)
a = np.arange(9).reshape( 3, 3)
b = np.arange(6).reshape( 3, 2)
print(a, "\n", b, "\n", a+b)
# ValueError: operands could not be broadcast together with shapes (3,3) (3,2)
a = np.arange(9).reshape( 3, 3)
b = np.arange(3).reshape( 3, 1)
print(a, "\n", b, "\n", a+b) # 可打印
a = np.arange(9).reshape( 3, 3)
b = np.arange(2).reshape( 2, 1)
print(a, "\n", b, "\n", a+b)
# ValueError: operands could not be broadcast together with shapes (3,3) (2,1)
2.维度不等时。
- 从右至左,至少有一维维度数不等时不可广播。(同上:不同处,为空或维度数为1者除外)
a = np.arange(24).reshape(4, 2, 3)
b = np.arange(9).reshape(3, 3)
print(a, "\n", b, "\n", a+b)
# ValueError: operands could not be broadcast together with shapes (4,2,3) (3,3)
a = np.arange(18).reshape(2, 3, 3)
b = np.arange(2).reshape(2)
print(a, "\n", b, "\n", a+b)
# ValueError: operands could not be broadcast together with shapes (2,3,3) (2,)
a = np.arange(12).reshape(4,1,3)
b = np.arange(9).reshape(3, 3)
print(a, "\n", b, "\n", a+b) # 可打印
a = np.arange(18).reshape(2,3,3)
b = np.arange(3).reshape(3)
print(a, "\n", b, "\n", a+b) # 可打印
其实抓住第二点。就可以全部概括这个BroadCast。