1 背景
RNN模型虽然能够将语义信息在序列间传递,但其输入和输出长度必须相同。因此RNN模型在解决如:机器翻译、摘要生成 等问题时比较束手无策。
因此在这基础上,Seq2Seq模型被提出,用以解决这种由一个序列产生另一个序列的问题。
2 模型结构
Seq2Seq模型包含两个部分,编码器(Encoder) 和 解码器(Decoder)。与RNN结构不同的是,Seq2Seq结构不再要求输入和输出序列有相同的时间长度。
Encoder把所有的输入序列都编码成一个统一的语义向量Context,然后再由Decoder解码。
在解码过程中,不断地将前一个时刻
t
−
1
t-1
t−1 的输出作为后一个时刻
t
t
t 的输入,循环解码,直到输出停止符为止。
除此之外,在现实情况中,目标文本中的单词与源文本中的单词是有对应关系的。因此Seq2Seq模型中,会构建一个Attention Layer,将目标文本中的单词与源文本中的各单词分别计算相关性,我们将这种相关性称为注意力。
3 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] 大小的向量。
其具体实现方式为:
-
计算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)=∑s′exp[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ˉs′htTWahˉs′vaTtanh[Wa⋅concat(ht,hˉs′)]dotgeneralconcat -
利用权重 α 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
- 利用Context Vector结合Decoder上一时刻隐藏层向量
h
t
−
1
h_{t-1}
ht−1 计算当前时刻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[Wh⋅concat(ct,ht)]=tanh(Wh⋅[ct;ht])=Woh t+bo