Numpy中的Broadcasting

Broadcasing即扩展,推广的意思,是为了使不同shape的array相互能够进行运算。
例子如下:

>>> a = np.array([1.0, 2.0, 3.0])
>>> b = np.array([2.0, 2.0, 2.0])
>>> a * b
array([ 2.,  4.,  6.])

>>> a = np.array([1.0, 2.0, 3.0])
>>> b = 2.0
>>> a * b
array([ 2.,  4.,  6.])

其中扩展规则如下,从后往前依次对shape中的各个值进行比较,兼容的情况有如下三种:

  1. 二者的数值一样
  2. 其中有一个数值为1
  3. shape长度不一样时,扩展时长度不够的那一个自动进行长度扩展,扩展值为1.

下面是详细的例子:

Image  (3d array): 256 x 256 x 3
Scale  (1d array): 3
Result (3d array): 256 x 256 x 3

A  (4d array):  8 x 1 x 6 x 1
B  (3d array):  7 x 1 x 5
Result (4d array):  8 x 7 x 6 x 5

A  (2d array):  5 x 4
B  (1d array):  1
Result (2d array):  5 x 4

A  (2d array):  5 x 4
B  (1d array):  4
Result (2d array):  5 x 4

A  (3d array):  15 x 3 x 5
B  (3d array):  15 x 1 x 5
Result (3d array):  15 x 3 x 5

A  (3d array):  15 x 3 x 5
B  (2d array):   3 x 5
Result (3d array):  15 x 3 x 5

A  (3d array):  15 x 3 x 5
B  (2d array):   3 x 1
Result (3d array):  15 x 3 x 5