NLP算法(四)- seq2seq

1 背景

RNN模型虽然能够将语义信息在序列间传递,但其输入和输出长度必须相同。因此RNN模型在解决如:机器翻译、摘要生成 等问题时比较束手无策。
因此在这基础上,Seq2Seq模型被提出,用以解决这种由一个序列产生另一个序列的问题。

2 模型结构

Seq2Seq模型包含两个部分,编码器(Encoder)解码器(Decoder)。与RNN结构不同的是,Seq2Seq结构不再要求输入和输出序列有相同的时间长度。

Encoder把所有的输入序列都编码成一个统一的语义向量Context,然后再由Decoder解码。
在解码过程中,不断地将前一个时刻 t − 1 t-1 t1 的输出作为后一个时刻 t t t 的输入,循环解码,直到输出停止符为止。

除此之外,在现实情况中,目标文本中的单词与源文本中的单词是有对应关系的。因此Seq2Seq模型中,会构建一个Attention Layer,将目标文本中的单词与源文本中的各单词分别计算相关性,我们将这种相关性称为注意力
Seq2Seq模型结构

3 Attention Layer

Attention Layer
以Luong Attention为例,其模型结构如上所示。
其中:

  • h ˉ s \bar{h}_s hˉs 代表Encoder状态, h t h_t ht 代表Decoder状态。
  • h ˉ t \bar{h}_t hˉt 代表Attention Layer输出的最终Decoder状态。
  • h ˉ s \bar{h}_s hˉs h t h_t ht [ n h , 1 ] [n_h, 1] [nh,1] 大小的向量。

其具体实现方式为:

  1. 计算Decoder t t t 时刻的状态 h t h_t ht 对Encoder每一个隐藏层状态 h ˉ s \bar{h}_s hˉs 的权重:
    α t ( s ) = e x p [ s c o r e ( h ˉ s , h t ) ] ∑ s ′ e x p [ s c o r e ( h ˉ s ′ , h t ) ] \alpha_t(s) = \frac{exp[score(\bar{h}_s, h_t)]}{\sum_{s'}{exp[score(\bar{h}_{s'}, h_t)]}} αt(s)=sexp[score(hˉs,ht)]exp[score(hˉs,ht)]
    其中score可以通过以下三种方式计算:
    s c o r e ( h ˉ s , h t ) = { h t T h ˉ s ′ d o t h t T W a h ˉ s ′ g e n e r a l v a T t a n h [ W a ⋅ c o n c a t ( h t , h ˉ s ′ ) ] c o n c a t \begin{aligned} score(\bar{h}_s, h_t) = \left\{ \begin{matrix} h_t^T \bar{h}_{s'} \quad &dot \\ h_t^T W_a \bar{h}_{s'} \quad &general \\ v_a^T tanh[W_a \cdot concat(h_t,\bar{h}_{s'})] \quad &concat \\ \end{matrix} \right. \end{aligned} score(hˉs,ht)=htThˉshtTWahˉsvaTtanh[Waconcat(ht,hˉs)]dotgeneralconcat

  2. 利用权重 α t ( s ) \alpha_t(s) αt(s) 计算所有隐藏层状态 h ˉ s \bar{h}_s hˉs 加权之和 c t c_t ct,即生成新的大小为 [ n h , 1 ] [n_h, 1] [nh,1] 的Context状态向量。

c t = ∑ s α t ( s ) ⋅ h ˉ s c_t = \sum_s{\alpha_t(s) \cdot \bar{h}_s} ct=sαt(s)hˉs

  1. 利用Context Vector结合Decoder上一时刻隐藏层向量 h t − 1 h_{t-1} ht1 计算当前时刻Decoder的输出 y t y_t yt
    h ~ t = t a n h [ W h ⋅ c o n c a t ( c t , h t ) ] = t a n h ( W h ⋅ [ c t ; h t ] ) y t = W o h ~ t + b o \begin{aligned} \widetilde{h}_t &= tanh[W_h \cdot concat(c_t, h_t)] \\ &= tanh(W_h \cdot [c_t;h_t]) \\ y_t &= W_o \widetilde{h}_t + b_o \end{aligned} h tyt=tanh[Whconcat(ct,ht)]=tanh(Wh[ct;ht])=Woh t+bo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anycall201

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值