使用注意力机制的seq2seq

注意力

image

在机器翻译的时候,每个生成的词可能相关于源句子中不同的词,中文和英文之间的翻译可能会存在倒装。但是可能在西方语言之间,相同意思的句子中的词的位置可能近似地是对应的,所以在翻译句子的某个部位的时候,只需要去看源句子中对应的位置就可以了。
然而,Seq2Seq模型中不能对此直接建模。Seq2Seq模型中编码器向解码器中传递的信息是编码器最后时刻的隐藏状态,解码器只用到了编码器最后时刻的隐藏状态作为初始化,从而进行预测,所以解码器看不到编码器最后时刻的隐藏状态之前的其他隐藏状态。
源句子中的所有信息虽然都包含在这个隐藏状态中,但是要想在翻译某个词的时候,每个解码步骤使用编码相同的上下文变量,但是并非所有输入(源)词元都对解码某个词元有用。将注意力关注在源句子中的对应位置,这也是将注意力机制应用在Seq2Seq模型中的动机。

加入注意力之后:

image
编码器对每次词的输出(隐藏状态)作为key和value,序列中有多少个词元,就有多少个key-value 对,它们是等价的,都是第i个词元的RNN的输出

解码器RNN对上一个词的预测输出(隐藏状态)是query(假设RNN的输出都是在同一个语义空间中,所以在解码器中对某个词元进行解码的时候,需要用到的是RNN的输出,而不能使用词嵌入之后的输入,因为key和value也是RNN的输出,所以key和query做匹配的时候,最好都使用RNN的输出,这样能够保证它们差不多在同一个语义空间)

注意力的输出和下一个词的词嵌入合并进入RNN解码器

对Seq2Seq的改进之处在于:之前Seq2Seq的RNN解码器的输入是RNN编码器最后时刻的隐藏状态,加入注意力机制之后的模型相当于是对所有的词进行了加权平均,根据翻译的词的不同使用不同时刻的RNN编码器输出的隐藏状态

import torch
from torch import nn
from d2l import torch as d2l

定义注意力解码器

下面看看如何定义Bahdanau注意力,实现循环神经网络编码器‐解码器。其实,我们只需重新定义解码器即可。为了更方便地显示学习的注意力权重,以下AttentionDecoder类定义了带有注意力机制解码器的基本接口。

class AttentionDecoder(d2l.Decoder):
    """带有注意力机制的解码器基本接口"""
    def __init__(self, **kwargs):
        super(AttentionDecoder, self).__init__(**kwargs)

    @property
    def attention_weights(self):
        raise NotImplementedError

接下来,让我们在接下来的Seq2SeqAttentionDecoder类中实现带有Bahdanau注意力的循环神经网络解码器。
首先,初始化解码器的状态,需要下面的输入:

  1. 编码器在所有时间步的最终层隐状态,将作为注意力的键和值;
  2. 上一时间步的编码器全层隐状态,将作为初始化解码器的隐状态;
  3. 编码器有效长度(排除在注意力池中填充词元)。
    在每个解码时间步骤中,解码器上一个时间步的最终层隐状态将用作查询。因此,注意力输出和输入嵌入都连结为循环神经网络解码器的输入。
class Seq2SeqAttentionDecoder(AttentionDecoder):
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,
                 dropout=0, **kwargs):
        super(Seq2SeqAttentionDecoder, self).__init__(**kwargs)
        # 加性Attention
        self.attention = d2l.AdditiveAttention(num_hiddens, num_hiddens,
                                               num_hiddens, dropout)
        self.embedding = nn.Embedding(vocab_size, embed_size)
        self.rnn = nn.GRU(embed_size + num_hiddens, num_hiddens, num_layers,
                          dropout=dropout)
        self.dense = nn.Linear(num_hiddens, vocab_size)

        #这个enc_valid_lens就是一个句子真实的单词个数
    def init_state(self, enc_outputs, enc_valid_lens, *args):
        # outputs的形状为(batch_size,num_steps,num_hiddens).
        # hidden_state的形状为(num_layers,batch_size,num_hiddens)
        outputs, hidden_state = enc_outputs
        return (outputs.permute(1, 0, 2), hidden_state, enc_valid_lens)

    def forward(self, X, state):
        # enc_outputs的形状为(batch_size,num_steps,num_hiddens).
        # hidden_state的形状为(num_layers,batch_size,num_hiddens)
        enc_outputs, hidden_state, enc_valid_lens = state
        # 输出X的形状为(num_steps,batch_size,embed_size)
        X = self.embedding(X).permute(1, 0, 2)
        outputs, self._attention_weights = [], []
        for x in X:
            # query的形状为(batch_size,1,num_hiddens)
            query = torch.unsqueeze(hidden_state[-1], dim=1)
            # context的形状为(batch_size,1,num_hiddens)
            context = self.attention(query, enc_outputs, enc_outputs,
                                     enc_valid_lens)
        
            #这个enc_valid_lens是一个句子真实的单词个数,就是一开始这个单词会有补充的。
            
            # 在特征维度上连结
            x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
            # 将x变形为(1,batch_size,embed_size+num_hiddens)
            out, hidden_state = self.rnn(x.permute(1, 0, 2), hidden_state)
            outputs.append(out)
            self._attention_weights.append(self.attention.attention_weights)
        # 全连接层变换后,outputs的形状为
        # (num_steps,batch_size,vocab_size)
        outputs = self.dense(torch.cat(outputs, dim=0))
        return outputs.permute(1, 0, 2),[
            enc_outputs, hidden_state, enc_valid_lens]

    @property
    def attention_weights(self):
        return self._attention_weights

接下来,使用包含7个时间步的4个序列输入的小批量测试Bahdanau注意力解码器

encoder = d2l.Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16,
                             num_layers=2)
encoder.eval()
decoder = Seq2SeqAttentionDecoder(vocab_size=10, embed_size=8, num_hiddens=16,
                                  num_layers=2)
decoder.eval()
X = torch.zeros((4, 7), dtype=torch.long)
state = decoder.init_state(encoder(X), None)
output, state = decoder(X, state)
output.shape, len(state), state[0].shape, len(state[1]), state[1][0].shape

(torch.Size([4, 7, 10]), 3, torch.Size([4, 7, 16]), 2, torch.Size([4, 16]))

训练

embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1
batch_size, num_steps = 64, 10
lr, num_epochs, device = 0.005, 250, d2l.try_gpu()

train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)
encoder = d2l.Seq2SeqEncoder(len(src_vocab), embed_size, num_hiddens,
                             num_layers, dropout)
decoder = Seq2SeqAttentionDecoder(len(tgt_vocab), embed_size, num_hiddens,
                                  num_layers, dropout)
net = d2l.EncoderDecoder(encoder, decoder)
d2l.train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)

image
模型训练后,我们用它将几个英语句子翻译成法语并计算它们的BLEU分数。

engs = ['go .', "i lost .", 'he\'s calm .', 'i\'m home .']
fras = ['va !', 'j\'ai perdu .', 'il est calme .', 'je suis chez moi .']
for eng, fra in zip(engs, fras):
    translation, dec_attention_weight_seq = d2l.predict_seq2seq(
        net, eng, src_vocab, tgt_vocab, num_steps, device, True)
    print(f'{eng} => {translation}, ',
          f'bleu {d2l.bleu(translation, fra, k=2):.3f}')
go . => va !,  bleu 1.000
i lost . => j'ai perdu .,  bleu 1.000
he's calm . => il est riche .,  bleu 0.658
i'm home . => je suis chez moi .,  bleu 1.000
attention_weights = torch.cat([step[0][0][0] for step in dec_attention_weight_seq],0).reshape((
1, 1, -1, num_steps))

训练结束后,下面通过可视化注意力权重会发现,每个查询都会在键值对上分配不同的权重,这说明在每个解码步中,输入序列的不同部分被选择性地聚集在注意力池中。

d2l.show_heatmaps(
    attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
    xlabel='Key posistions', ylabel='Query posistions')

image
从这个图中,我们可以看出,当"Q"=0的时候这个四个基本都在起作用,当"Q"=1第二个起的作用比较大,当"Q"=2第四个起的作用比较大,当"Q"=3第二个起的作用比较大.....。

posted @   lipu123  阅读(76)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2020-09-12 (二进制枚举+bitset)
2020-09-12 队列+排序(送礼物)
2020-09-12 转01串
2020-09-12 BFS+螺旋矩阵
点击右上角即可分享
微信分享提示