Attention基本公式及其变种

本篇博文介绍的Attention,全部是Seq2Sqeq的attention机制的变种,本质上也还是Seq2Seq的attention,区别于Transformer的self attention,下一篇博文会介绍self attention。

Attention Mechanism 机制基本公式

attention机制本质上是一种加权值,对文本进行加权求和后得到整个文本的中间语义变换函数,关于其原理的介绍文章已经有很多了,这里不在赘述。其基本公式如下:

  • address memory (score function)
    e i j = f ( q i , p j ) e_{ij}=f(q_i, p_j) eij=f(qi,pj)
  • normalize (aligment function)
    α i j = s o f t m a x ( e i j ) = e x p ( f ( q i , p j ) ) ∑ j e x p ( f ( q i , p j ) ) \alpha_{ij}=softmax(e_{ij})=\frac{exp(f(q_i,p_j))}{\sum_jexp(f(q_i,p_j))} αij=softmax(eij)=jexp(f(qi,pj))exp(f(qi,pj))
  • read content (generate context vector function)
    c i = ∑ i α i j h i c_i = \sum_{i}\alpha_{ij}h_i ci=iαijhi

Score fucntion本质上是在求一种匹配度(相似度),Aligment function是把所有位置上的权值归一化,使其相加等于1(softmax正是这种功能),最后的加权求和是为了使得经过LSTM/RNN encode之后的文本与权值关联起来得到加权的中间语义表示。Attention被提出了是为了解决较长文本中依赖关系的捕捉,传统的序列模型虽然有一定这方面的能力,但文本一旦边长效果随之变差。

Score function f f f通常是两段文本q(表示query),p(表示passage)的点积,因为两个矩阵相乘是最简单直观的相似度度量。这就是最基本的attention机制的实现公式了。
f = Q T P f = Q^TP f=QTP

基本attention公式变种

通过改变 f f f函数的计算方式,可以产生很多attention机制的变种,这些变种可能在某些特定的任务下比基本attention机制公式效果更好。

下面就列出一篇论文下给出的四种attention机制变种。 s s s即为前述 f f f

Concat Attention

s j t = v c T t a n h ( W c 1 h j q + W c 2 h t p ) s_j^t=v_c^Ttanh(W_c^1h_j^q+W_c^2h_t^p) sjt=vcTtanh(Wc1hjq+Wc2htp)
a i t = e x p ( s i t ) / ∑ j = 1 N e x p ( s j t ) a_i^t=exp(s_i^t)/\sum_{j=1}^Nexp(s_j^t) ait=exp(sit)/j=1Nexp(sjt)
q t c = ∑ i = 1 N a i t h i q q_t^c=\sum_{i=1}^Na_i^th_i^q qtc=i=1Naithiq

Bilinear Attention

s j t = h j q T W b h t p s_j^t=h_j^{q^T}W_bh_t^p sjt=hjqTWbhtp
a i t = e x p ( s i t ) / ∑ j = 1 N e x p ( s j t ) a_i^t=exp(s_i^t)/ \sum_{j=1}^Nexp(s_j^t) ait=exp(sit)/j=1Nexp(sjt)
q t b = ∑ i = 1 N a i t h i q q_t^b=\sum_{i=1}^Na_i^th_i^q qtb=i=1Naithiq

Dot Attention

s j t = v d T t a n h ( W d ( h j q ⊙ h t p ) ) s_j^t=v_d^Ttanh(W_d(h_j^q\odot h_t^p)) sjt=vdTtanh(Wd(hjqhtp))
a i t = e x p ( s i t ) / ∑ j = 1 N e x p ( s j t ) a_i^t=exp(s_i^t)/\sum_{j=1}^Nexp(s_j^t) ait=exp(sit)/j=1Nexp(sjt)
q t d = ∑ i = 1 N a i t h i q q_t^d=\sum_{i=1}^Na_i^th_i^q qtd=i=1Naithiq

Minus Attention

s j t = v m T t a n h ( W m ( h j q − h t p ) ) s_j^t=v_m^Ttanh(W_m(h_j^q-h_t^p)) sjt=vmTtanh(Wm(hjqhtp))
a i t = e x p ( s i t ) / ∑ j = 1 N e x p ( s j t ) a_i^t=exp(s_i^t)/\sum_{j=1}^Nexp(s_j^t) ait=exp(sit)/j=1Nexp(sjt)
q t m = ∑ i = 1 N a i t h i q q_t^m=\sum_{i=1}^Na_i^th_i^q qtm=i=1Naithiq

Add Attention

再补充一个,出处不一样,跟上面四个相比应该叫做Add attention原出处称为perceptron attetion。它跟Concat好像是一样的。

s j t = v a T t a n h ( W a h j + U a h t ) ) s_j^t=v_a^Ttanh(W_ah_j+U_ah_t)) sjt=vaTtanh(Wahj+Uaht))
a i t = e x p ( s i t ) / s u m j = 1 N e x p ( s j t ) a_i^t=exp(s_i^t)/sum_{j=1}^Nexp(s_j^t) ait=exp(sit)/sumj=1Nexp(sjt)
q t c = ∑ i = 1 N a i t h i q q_t^c=\sum_{i=1}^Na_i^th_i^q qtc=i=1Naithiq

参考资料

大话注意力机制
attetnion各种形式总结
Multiway Attention Networks for Modeling Sentence Pairs (IJCAI 2018)

posted @ 2020-03-09 15:49  从流域到海域  阅读(545)  评论(0编辑  收藏  举报