天天看點

Attention Is All You Need 中的self-attention 以及multi-head attention

前言

attention在語音識别方面越來越受大家的歡迎了,無論是soft attention以及hard attention等等都被大家廣泛應用,從今天起筆者将基于一篇篇的頂會,來複現各家的attention的算法,今天就分享self-attention。

self-attention

Attention Is All You Need 中的self-attention 以及multi-head attention

如圖所示文章中的經典圖例

所采用的公式

Attention Is All You Need 中的self-attention 以及multi-head attention

也就是引入了QKV三個值,用這三個值進行一如上公式,進行系列的操作

代碼展示:

import tensorflow as tf 
import math
length=50#幀長
input=39#MFCC特征維數
###########輸入資料
x = tf.placeholder(tf.float32,[None,length,input])#輸入資料


def self_attention(x,hidden_layer,head):
    x=tf.layers.conv1d(x,hidden_layer*3,1,strides=1, padding='same')
    Q,K,V=tf.split(x, 3, axis=2)
    print(Q,K,V)
    K=tf.transpose(K,[0,2,1])
    print(K)
    result=tf.reduce_sum(tf.matmul(Q,K)/math.sqrt(hidden_layer),axis=1)
    print(result)
    result=tf.reshape(result,[-1,50,1])
    result=tf.nn.softmax(result)
    V=V*result
    return V
           

采用tf.split函數分離出Q,K,V,然後Q與K矩陣相乘,求和,經過softmax最後與V相乘,得到了單頭注意力機制的結果

既然有個單頭的算法了,如何變成多頭的呢?

我們先來看一下論文裡寫的:

Attention Is All You Need 中的self-attention 以及multi-head attention

他是這麼做的呢,他是先把一個語料最後一維先分成h份最後concat到了一起,并且文章中的這句話也驗證了我們的研究:

Attention Is All You Need 中的self-attention 以及multi-head attention

文章中采用的是h=8,這裡我們采用5。

def multi_head_attention(x,head,output_channel):
    xn=tf.split(x,head,axis=2)
    print(xn)
    V1=xn[0]
    print(V1)
    V1=self_attention(V1,32)
    for a in xn[1:]:
        V=self_attention(a,32)
        V1=tf.concat([V1,V],axis=2)
    print(V1)   
    V1=tf.layers.conv1d(V1,output_channel,1,strides=1, padding='same')
    return V1
           

這樣就比較輕松的完成了multi-head attention的代碼編寫

繼續閱讀