这一章节与前面写好的function关联太大,建议看书P291.
这章节主要讲述了添加attention的seq2seq,且只在decoder里面添加,所以全文都在讲这个decoter
目录
1.训练
#@save
class AttentionDecoder(d2l.Decoder):
"""带有注意⼒机制解码器的基本接⼝"""
def __init__(self, **kwargs):
super(AttentionDecoder, self).__init__(**kwargs)
@property
def attention_weights(self):
raise self._attention_weights
Encoder对每个词的rnn输出作为key-values,输出为(bs,k-v,h)
Decoder对上一个词的rnn输出作为query(bs,1,h)
要预测下一词时,当前预测的作为query,编码器对应的各个原文输出为key-values,进行attention,来找到对应预测下一个词的查询
原seq2seq是将上一个rnn里最后一个state,现在允许所有词的输出都获取,根据上下文对应找到(bs,q,h///values)
只有decoder使用attention
前面的init只增加了一个attention,其他的emb、rnn、dense与seq2seq一样
init_state相比之前增加了enc_valid_lens,告知encoder中的有效长度
class Seq2SeqAttentionDecoder(AttentionDecoder):
def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
dropout=0, **kwargs):
super(Seq2SeqAttentionDe

文章介绍了在解码器中添加注意力机制的seq2seq模型,特别是只在decoder中应用注意力。AttentionDecoder类被定义,它使用AdditiveAttention,并在训练和预测阶段进行操作。编码器的输出作为key-values,解码器的上一个词状态作为query,通过注意力机制找到相关的信息来预测下一个词。
最低0.47元/天 解锁文章
462

被折叠的 条评论
为什么被折叠?



