【Python】numpy廣播機制

【Python】numpy廣播機制

一,簡介
當兩個數組的形狀並不相同的時候,我們可以通過擴展數組的方法來實現相加、相減、相乘等操作,這種機制叫做廣播(broadcasting)。

二,規則
網上和書上都有對規則的描述,看到最多的有以下兩種
第一種:

  1. 讓所有輸入數組都向其中形狀最長的數組看齊,形狀中不足的部分都通過在前面加 1 補齊。
  2. 輸出數組的形狀是輸入數組形狀的各個維度上的最大值。
  3. 如果輸入數組的某個維度和輸出數組的對應維度的長度相同或者其長度爲 1 時,這個數組能夠用來計算,否則出錯。
  4. 當輸入數組的某個維度的長度爲 1 時,沿着此維度運算時都用此維度上的第一組值。

第二種:
廣播的原則:如果兩個數組的後緣維度(trailing dimension,即從末尾開始算起的維度)的軸長度相符,或其中的一方的長度爲1,則認爲它們是廣播兼容的。廣播會在缺失和(或)長度爲1的維度上進行。

第一種描述相對第二種就比較全面點,但是也不太好理解。結合兩種描述後得到一個通俗的理解是:
1,無論兩個數據維度是否相等,都將維度進行右對齊。
2,比較對應維度上的數值,存在這三種情況則進行廣播,輸出的維度大小取數值最大值
(1),數值相等
(2),存在一個爲1
(3),存在一個爲空

三,例子

import numpy as np

arr = np.arange(24).reshape(3, 4, 2)
arr2 = np.arange(8).reshape(4, 2)
arr3 = arr+arr2
print(arr3.shape)  # (3, 4, 2)
"""
1,arr 與 arr2 右對齊
2,比較對應的數值,滿足條件(1),(2)
arr  3 4 2
arr2   4 2
—————————————
arr3 3 4 2
"""
import numpy as np

arr = np.arange(24).reshape(3, 4, 2)
arr2 = np.arange(2).reshape(1, 1, 2)
arr3 = arr + arr2
print(arr3.shape)  # (3, 4, 2)
"""
1,arr 與 arr2 右對齊
2,比較對應的數值,滿足條件(1),(3)
arr  3 4 2
arr2 1 1 2
—————————————
arr3 3 4 2
"""
import numpy as np

arr = np.arange(24).reshape(3, 4, 2)
arr2 = np.arange(2).reshape(1, 2)
arr3 = arr + arr2
print(arr3.shape)  # (3, 4, 2)
"""
1,arr 與 arr2 右對齊
2,比較對應的數值,滿足條件(1),(2),(3)
arr  3 4 2
arr2   1 2
—————————————
arr3 3 4 2
"""
import numpy as np

arr = np.arange(24).reshape(3, 4, 2)
arr2 = np.arange(2).reshape(2)
arr3 = arr + arr2
print(arr3.shape)  # (3, 4, 2)
"""
1,arr 與 arr2 右對齊
2,比較對應的數值,滿足條件(1),(3)
arr  3 4 2
arr2     2
—————————————
arr3 3 4 2
"""
import numpy as np

arr = np.arange(24).reshape(3, 4, 2)
arr2 = np.arange(4).reshape(1, 4)
arr3 = arr + arr2
print(arr3.shape)  # (3, 4, 2)
"""
1,arr 與 arr2 右對齊
2,比較對應的數值,不滿足條件(1),報錯
arr  3 4 2
arr2   1 4
—————————————
arr3 
"""

在這裏插入圖片描述

參考:
https://finthon.com/numpy-broadcast/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章