在NumPy中如果遇到大小不一致的数组运算,就会触发广播机制。
广播(broadcasting)指的是不同形状的数组之间的算术运算的执行方式。
如果两个数组的后缘维度(trailing dimension,即从末尾开始算起的维度)的轴长度相符,或其中的一方的长度为1,则认为它们是广播兼容的。广播会在缺失和(或)长度为1的维度上进行。
通俗的理解就是:将两个数组的维度大小右对齐,然后比较对应维度上的数值,如果数值相等或其中有一个为1或者为空,则能进行广播运算,并且输出的维度大小为取数值大的数值。否则不能进行数组运算。
A = np.zeros((2,5,3,4)) B = np.zeros((3,4)) print((A+B).shape) # 输出 (2, 5, 3, 4) A = np.zeros((4)) B = np.zeros((3,4)) print((A+B).shape) # 输出(3,4) A = np.zeros((2,5,3,4)) B = np.zeros((3,3)) print((A+B).shape) 报错: ValueError: operands could not be broadcast together with shapes (2,5,3,4) (3,3) 为啥呢?因为最后一维的大小A是4,B是3,不一致。 A = np.zeros((2,5,3,4)) B = np.zeros((3,1)) print((A+B).shape) # 输出:(2, 5, 3, 4) A = np.zeros((2,5,3,4)) B = np.zeros((2,1,1,4)) print((A+B).shape) # 输出:(2, 5, 3, 4) A = np.zeros((1)) B = np.zeros((3,4)) print((A+B).shape) # 输出(3,4) # 下面是报错案例 A = np.zeros((2,5,3,4)) B = np.zeros((2,4,1,4)) print((A+B).shape) ValueError: operands could not be broadcast together with shapes (2,5,3,4) (2,4,1,4) 为啥报错?因为A和B的第2维不相等。并且都不等于1.



