# Self Attention 筆記 ## 背景  Model 輸入是一串 Vectors (Sequence),而且 Sequence 長度有可能改變 例如:句子、聲音訊號(切成 25ms 的 frames)、Graph、Image 輸出可以分為以下幾種:  1. Sequence 中每個 Vector 都對應一個 label (例:詞性分類) 2. 一整個 Sequence 輸出一個 label (例:辨別評價是否正向) 3. Model 自行決定要輸出幾個 label (例:翻譯、語音辨識) ## 處理 Sequence Labeling 問題 ### Fully Connected 解法  一個 Sequence 裡面,前後可能有關聯性 雖然可以用 Window 來取某一段 Vectors 來使用,但還是有極限 為了更好的考慮一整個 Sequence,於是出現 Self Attention 機制 ### Self Attention  輸入幾個向量,就會輸出幾個向量,而且輸出的每一個向量都是考慮過每一個 Input 最後再經過 Fully Connected 得到 output (也可經過多層 Self Attention + FC) ## Self Attention 機制 ### 計算 Attention 的模組 Attention:Sequence 中兩個向量的關聯程度(以 $\alpha$ 表示)  向量乘上 $W^q$ 矩陣得到 q、乘上 $W^k$ 矩陣得到 k q:query、k:key,兩者做 dot product(inner product 內積)以後得到 $\alpha$ ### 算出與 $a^i$ 的關係  拿 $q^i$ 與其他人的 key 做 dot product,並通過 softmax(或ReLU) 以此為例,會得到 $4*4=16$ 個相關性分數 $\alpha$ ### 求出 Output Vector  每個向量乘上 $W^v$ 矩陣得到 $v^i$ $\alpha$ 乘上 $v^i$ 即是 Output $b^i$,而 $b^i$ 經過以上運算會與整個 Sequence 相關 註:每個 Vector 用一樣的 $W^q$、$W^k$ 和 $W^v$ ## 實際運算方法簡化(矩陣運算)  矩陣 I 為所有 Input Vectors 結合,分別乘上 $W^q$、$W^k$、$W^v$ 後得到 Q、K、V Q 與 K 的 Transpose 相乘後(inner product)得到 A (所有 $\alpha$ 結合) A 經過 Normalization 變成 A$^\prime$,最後乘上 V 得到 Output Unknown Parameters 只有 $W^q$、$W^k$、$W^v$ 整個 Sequence 是平行處理的,不需向RNN一樣前後等待 ## Multi-head Self-attention Vectors 的相關性可能不只一種形式和定義,需要不同算法來運算相關程度  $q^i$ 再乘上不同的 $W$ 後分支成多個 $q$(此例為 2 個分支) $k^i$ 和 $v^i$ 亦是如此,並一樣以 self attention 運算方法求出 output 但最後要再將多個 output vectors 乘上 $W^O$ 結合起來:  ## 位置資訊(Position Encoding)  $a^i$ Vector 再加上一個專屬的 $e^i$,加入在 Sequence 中的位置資訊 $e^i$ 有可能是手動產生的、或是用資料學習而來 ## CNN 和 Self-attention 的關係  CNN 已經定好 Reception field,Self Attention 可以自己依照相關性去找出合適的 Reception field CNN 為 Self-Attention 中的一個特例: 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up