一、廣播的定義
二、廣播的規則
- 如果兩個數組的維度數量不同,NumPy 會在維度較少的數組前面補 1,直到兩個數組的維度數量相同。
- 然後,比較它們的每一對維度大小。對於每一對維度,以下情況視為兼容:a. 兩個維度大小相等。b. 其中一個維度大小為1。
- 如果兩個數組根據上述規則是兼容的,那麼廣播後的結果數組的形狀,將在每一個維度上取兩個數組對應維度大小的最大值。
- 維度大小為 1 的數組,會在其維度上進行複製,以匹配另一個數組對應維度的大小。
三、廣播的示例
示例 1:標量(0-D 數組)與數組
python
運行
import numpy as np
a = np.array([1, 2, 3])
b = 2
result = a + b
print(f"a: {a}, shape: {a.shape}")
print(f"b: {b}, shape: {b.shape}")
print(f"a + b: {result}, shape: {result.shape}")
plaintext
a: [1 2 3], shape: (3,)
b: 2, shape: ()
a + b: [3 4 5], shape: (3,)
示例 2:二維數組與一維數組
python
運行
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.array([10, 20, 30])
result = a + b
print(f"a:\n{a}, shape: {a.shape}")
print(f"b: {b}, shape: {b.shape}")
print(f"a + b:\n{result}, shape: {result.shape}")
plaintext
a:
[[1 2 3]
[4 5 6]], shape: (2, 3)
b: [10 20 30], shape: (3,)
a + b:
[[11 22 33]
[14 25 36]], shape: (2, 3)
示例 3:兩個數組都需要廣播
python
運行
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[10],
[20]])
result = a + b
print(f"a:\n{a}, shape: {a.shape}")
print(f"b:\n{b}, shape: {b.shape}")
print(f"a + b:\n{result}, shape: {result.shape}")
plaintext
a:
[[1 2]
[3 4]], shape: (2, 2)
b:
[[10]
[20]], shape: (2, 1)
a + b:
[[11 12]
[23 24]], shape: (2, 2)
示例 4:不兼容的情況
python
運行
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6]])
b = np.array([10, 20])
# 嘗試相加
try:
result = a + b
except ValueError as e:
print(f"錯誤: {e}")
plaintext
錯誤: operands could not be broadcast together with shapes (2,3) (2,)
- 從尾部開始:
3vs2。 3和2既不相等,也沒有一個是 1。不兼容。
四、廣播的優勢
五、總結
- 廣播遵循一套從右到左的維度兼容性規則。
- 維度大小為 1 的數組可以被 “複製” 以匹配另一個數組的維度。
- 如果兩個數組的維度在任何位置都不兼容(既不相等也非 1),則廣播失敗。
- 熟練掌握廣播規則,能讓你寫出更簡潔、更高效的 NumPy 代碼。