Broadcasting自動擴展的用法

1. Broadcasting 自動擴展

  1. Expand
  2. without copying data

2. 關鍵理念

  1. Insert 1 dim ahead
  2. Expand dims with size 1 to same size

假設圖片經過卷積神經網絡之後得到一個Feature maps,有32個channel,在每一個channel上面添加一個Bias。如何讓一個一維的Bias與四維的Feature maps疊加?Bias:[32] Expand 爲 Bias:[32,1,1]
[b,c,h,w] ,一般把後面的維度理解爲小維度,前面的維度理解爲大維度。比如b代表圖片的數量,w代表圖片的列數,這樣一對比就知道哪個概念小,哪個概念大。這樣越靠前的維度就定義爲大維度,越靠後的維度就定義爲小維度。對齊的時候是從小維度開始的。
Feature maps:[4,32,14,14]
Bias:[ 32, 1, 1]
根據Broadcasting意思會在dim=0插入1,使原來Bias變成四維Bias:[1,32,1,1],最後Bias就能根據Feature maps維度擴展成Bias:[4,32,14,14],其實就是在小維度1上面進行擴張。
總的來說基本過程是這樣:Bias:[3,1,1] => [1,32,1,1] => [4,32,14,14]
unsqueeze expand
這樣雙方的dim、shape就都一樣了。若size一致,可進行對應位置元素相加。

在這裏插入圖片描述

3. why broadcasting

  1. for actual demanding
    [class,students,scores]
    Add bias for every students: +5 score
    [4,32,8] + [4,32,8]
    [4,32,8] + [5.0] ,此處的[5.0]是標量的意思,標量的dim可以理解爲dim=0或dim=1也可以,要理解數據的內容和數據的shape之間的區別。
  2. memory consumption
    一個浮點數是4byte,本來[5.0]只佔用1byte,如何人爲將[5.0] 重複成[4,32,8],那麼這個tensor的大小就是4 x 32 x 8 = 1024 byte,內存消耗比原來增加1000倍。若這個部分使用broadcasting就能很好節省內存,這1000倍對於內存或顯存的消耗來說就會產生很大的差距。
    設計broadcasting初衷就是1滿足自動擴張2滿足數學要求3不用人爲手動完成這項操作又節省內存空間。

4. Is it broadcasting-able?

  1. Match from Last dim!
    if current dim=1,expand to same
    if either has no dim,insert one dim and expand to same
    otherwise,NOT broadcasting-able
    小維度指定,大維度隨意
    A:[4,32,8]
    B:[1, 1,4]
    A與B的這種情況就無法broadcasting
    在這裏插入圖片描述

broadcasting-able

Situation 1:
[4,32,14,14]
[1,32, 1, 1] => [4,32,14,14]
Situation 2:
[4,32,14,14]
[14,14] => [1,1,14,14] => [4,32,14,14]

NOT broadcasting-able

Situation 1:
A:[4,32,14,14]
B:[2,32,14,14]
遇到這種情況只能手動操作,取出B[0] = [32,14,14] => [1,32,14,14] => [4,32,14,14]

  • Dim 0 has dim,can NOT insert and expand to same
  • Dim 0 has distinct dim,NOT size 1
  • NOT broadcasting-able
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章