Seq2Seq中的Attention

公式

这篇博客主要讲基础的 seq2seq 中 attention 机制:

  • 输入: X = ( x 1 , x 2 , ⋯   , x T x ) X = (x_1, x_2, \cdots, x_{T_x}) X=(x1,x2,,xTx)
  • 输出: Y = ( y 1 , y 2 , ⋯   , y T y ) Y = (y_1, y_2, \cdots, y_{T_y}) Y=(y1,y2,,yTy)

公式推导:

  • h t = R N N e n c ( x t , h t − 1 ) h_t = RNN_{enc}(x_t, h_{t-1}) ht=RNNenc(xt,ht1), Encoder 只要它的 hidden state。
  • s t = R N N d e c ( y t − 1 , s t − 1 ) s_t = RNN_{dec}(y_{t-1}, s_{t-1}) st=RNNdec(yt1,st1),这里相当于用 teacher forcing,这里 s 也是指 hidden state。

此时,做 attention:

  • e i j = s c o r e ( s i − 1 , h j ) e_{ij} = score(s_{i-1}, h_j) eij=score(si1,hj) s i − 1 s_{i-1} si1 先跟每个 h h h 分别计算的得到一个分数,这样所以 s s s 计算后,得到一个矩阵,行相当于代表每个词,列相当于分配给每个 h h h 的权重。也就是每个decoder的 hidden state 与每个 encoder 的 hidden state 计算一个相似度。
  • α i j = e x p ( e i j ) ∑ k = 1 T x e x p ( e i k ) \alpha_{ij} = \frac{exp(e_{ij})}{\sum_{k=1}^{T_x} exp(e_{ik})} αij=k=1Txexp(eik)exp(eij),softmax操作。
  • c i = ∑ j = 1 T x α i j h j c_i = \sum_{j=1}^{T_x}\alpha_{ij}h_j ci=j=1Txαijhj,attention output。

最后

  • s t ^ = t a n h ( W c [ c t ; s t ] ) \hat{s_t} = tanh(W_c[c_t; s_t]) st^=tanh(Wc[ct;st]),concate 操作, W W W 为需要学习的参数。
  • p ( y t ∣ y < t , x ) = s o f t m a x ( W s s t ^ ) p(y_t|y_{<t}, x) = softmax(W_s\hat{s_t}) p(yty<t,x)=softmax(Wsst^),输出概率。

备注:计算score那一步有几种操作,可以直接点乘、加一个可学习矩阵相乘、cos相似度、多层感知机等:
s c o r e ( s i , h i ) = { s i T h i s i T W h i v T t a n h ( W [ s i ; h i ] ) score(s_i, h_i)=\left\{ \begin{aligned} & s_i^{\mathrm T}h_i \\ & s_i^{\mathrm T}Wh_i \\ & v^{\mathrm T}tanh(W[s_i;h_i]) \end{aligned} \right. score(si,hi)=siThisiTWhivTtanh(W[si;hi])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值