Try   HackMD
tags: ML數學分部

Backpropagation 反向傳播算法

簡介

反向傳播算法 (BPP) 是拿來計算梯度、更新神經網路參數的方法
在之前我們知道該怎麼更新 linear regression 的參數
也就是計算 loss 的梯度並更新權重

w1w0ηLw

那神經網路我們可以看成是由多個 linear regression 所組成 ( 加上 Activation funciton )
( 詳情可見:從 Linear Regression 到神經網路 )

也就是有很多的權重 w 要計算,
而 Backpropagation 就是一種有效率來計算每個權重梯度的方法

目標

我們最終的目標是算出 Update 參數時的梯度

L(θ)
這邊將
L(θ)
(loss) 定義為

L(θ)=n=1Nln(θ)

( 定義

l 的意思是個別資料的
loss
)

那梯度可以寫成下列式

L(θ)=Lw=n=1Nlnw

於是我們的目標就是要計算出

=lw
並將它加總


Forward Pass & Backward Pass

這邊使用老師舉的範例來說明
( 會用到微積分的 Chain Rule )

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

如果我們神經網路長上述這樣 ( 先不考慮 Activation function )
那要我的計算目標

lw 利用 Chain Rule 可以化簡為以下式子

lw=zwlz

在這個階段我們會將任務變為兩個
也就是 BPP 的兩步驟

  1. Forward Pass : 使用神經網路進行預測,同時也會計算出
    zw
  2. Backward Pass : 向後傳播計算
    lz

都算出後就可得到目標值

Step1. Forward Pass

向前傳播其實就是讓神經網路取預測 y

zw 呢 ?

我們將 z 攤開

可以驚訝發現因為

z=x1w1+x2w2+b

所以

zw1=x1

代表

zw 的解會是 input

所以 forward 就結束啦 ~



Step2. Backward Pass

因為

lz 無法直接計算,所以要將它攤開
這時可以考慮 Activation function ,神經網路如下

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

lz 做分解
lz=azla

在這邊

az=σ(z)
因為 z 在 forward 就算出來了(不然你 y 怎麼來 ^^ )
所以
σ(z)
為一常數 (scalar)


我們再將 Activation Func 後面加一層 Layer

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

繼續分解

la
la=zalz+zalz

我們細看

za
帶入 z 公式且設 x=a 時,對 a 微分後會剩下
w3

(
z=aw3+ajwj...
)


帶回

lz

lz=σ(z)[w3lz+w4lz]

當此 layer 是輸出層時,便可計算

lz
lz=y1zly1


Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

最後再將上述結果帶回

lz=σ(z)[w3lz+w4lz]

即求出

lz


有了

lz
zw

我們就算出了梯度

lw=zwlz


為啥叫 Backward Pass 呢 ?
將公式列出 (這邊舉例計算

z=z1 公式 )

lz1=σ(z1)[w3lz3+w4lz4]

lz3 又可展開

lz3=σ(z3)[w5lz5+w6lz6]

同理

lz4

並繪製成圖

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

會發現我們是從靠近 y 的參數慢慢計算回來
因為前面參數的偏微分都會需要後面的參數
所以這樣是比較有效率的方法 ( 不然你每次都要重算 TT )
也稱為 Backward Pass ~