廣播陣列操作

算術運算在 Numpy 陣列上以元素方式執行。對於相同形狀的陣列,這意味著在相應索引處的元素之間執行操作。

# Create two arrays of the same size
a = np.arange(6).reshape(2, 3)
b = np.ones(6).reshape(2, 3)

a
# array([0, 1, 2],
#       [3, 4, 5])
b
# array([1, 1, 1],
#       [1, 1, 1])

# a + b: a and b are added elementwise
a + b
# array([1, 2, 3],
#       [4, 5, 6])

也可以通過 Numpy 廣播在不同形狀的陣列上執行算術運算。通常,一個陣列在另一個陣列上廣播,以便在全等形狀的子陣列上執行元素運算。

# Create arrays of shapes (1, 5) and (13, 1) respectively
a = np.arange(5).reshape(1, 5)
a
# array([[0, 1, 2, 3, 4]])
b = np.arange(4).reshape(4, 1)
b
# array([0],
#       [1],
#       [2],
#       [3])

# When multiplying a * b, slices with the same dimensions are multiplied
# elementwise. In the case of a * b, the one and only row of a is multiplied
# with each scalar down the one and only column of b.
a*b
# array([[ 0,  0,  0,  0,  0],
#        [ 0,  1,  2,  3,  4],
#        [ 0,  2,  4,  6,  8],
#        [ 0,  3,  6,  9, 12]])

為了進一步說明這一點,請考慮 2D 和 3D 陣列與全等子維度的乘法。

# Create arrays of shapes (2, 2, 3) and (2, 3) respectively
a = np.arange(12).reshape(2, 2, 3)
a
# array([[[ 0  1  2]
#         [ 3  4  5]]
#
#        [[ 6  7  8]
#         [ 9 10 11]]])
b = np.arange(6).reshape(2, 3)
# array([[0, 1, 2],
#        [3, 4, 5]])

# Executing a*b broadcasts b to each (2, 3) slice of a,
# multiplying elementwise.
a*b
# array([[[ 0,  1,  4],
#         [ 9, 16, 25]],
#
#        [[ 0,  7, 16],
#         [27, 40, 55]]])

# Executing b*a gives the same result, i.e. the smaller
# array is broadcast over the other.

何時應用陣列廣播?

當兩個陣列具有相容的形狀時進行廣播。

從尾隨形狀開始逐個比較形狀。如果兩個維度相同或者其中一個是 1,則它們是相容的。如果一個形狀具有比另一個更高的尺寸,則不比較超出的部件。

相容形狀的一些示例:

(7, 5, 3)    # compatible because dimensions are the same
(7, 5, 3)

(7, 5, 3)    # compatible because second dimension is 1  
(7, 1, 3)

(7, 5, 3, 5) # compatible because exceeding dimensions are not compared
      (3, 5)

(3, 4, 5)    # incompatible 
   (5, 5) 

(3, 4, 5)    # compatible 
   (1, 5) 

這是關於陣列廣播的官方文件。