1. 程式人生 > >numpy中的brodcast

numpy中的brodcast

broadcasting機制的功能是為了方便不同shape的array(numpy庫的核心資料結構)進行數學運算。

當操作兩個array時,numpy會逐個比較它們的shape(構成的元組tuple),只有在下述情況下,兩arrays才算相容:

  1. 相等
  2. 其中一個為1,(進而可進行拷貝拓展已至,shape匹配)

注意比較是從後往前對齊

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):  15 x 3 x 5
B      (1d array):  15 x 1 x 5
Result (2d array):  15 x 3 x 5
 

ref:https://blog.csdn.net/lanchunhui/article/details/50158975