• 李沐66_使用注意力机制的seq2seq——自学笔记


    加入注意力

    1.编码器对每次词的输出作为key和value

    2.解码器RNN对上一个词的输出是query

    3.注意力的输出和下一个词的词嵌入合并进入RNN

    一个带有Bahdanau注意力的循环神经网络编码器-解码器模型

    总结

    1.seq2seq通过隐状态在编码器和解码器中传递信息

    2.注意力机制可以根据解码器RNN的输出来匹配到合适的编码器RNN的输出来更有效的传递信息。

    pip install d2l==0.17.6  ### 很重要,不要下载错了,对于colab
    
    • 1
    import torch
    from torch import nn
    from d2l import torch as d2l
    
    • 1
    • 2
    • 3

    注意力解码器

    AttentionDecoder类定义了带有注意力机制解码器的基本接口

    class AttentionDecoder(d2l.Decoder):
        """带有注意力机制解码器的基本接口"""
        def __init__(self, **kwargs):
            super(AttentionDecoder, self).__init__(**kwargs)
    
        @property
        def attention_weights(self):
            raise NotImplementedError
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    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)
            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)
    
        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)
                # 在特征维度上连结
                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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    使用包含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 = d2l.zeros((4, 7), dtype=torch.long)  # (batch_size,num_steps)
    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    (torch.Size([4, 7, 10]), 3, torch.Size([4, 7, 16]), 2, torch.Size([4, 16]))
    
    • 1

    实例化一个带有Bahdanau注意力的编码器和解码器, 并对这个模型进行机器翻译训练。

    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)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    loss 0.020, 7390.3 tokens/sec on cuda:0
    
    • 1

    在这里插入图片描述

    模型训练后,我们用它将几个英语句子翻译成法语并计算它们的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}')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    go . => va !,  bleu 1.000
    i lost . => j'ai perdu .,  bleu 1.000
    he's calm . => il est mouillé .,  bleu 0.658
    i'm home . => je suis chez moi .,  bleu 1.000
    
    • 1
    • 2
    • 3
    • 4
    attention_weights = torch.cat([step[0][0][0] for step in dec_attention_weight_seq], 0).reshape((
        1, 1, -1, num_steps))
    
    • 1
    • 2

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

    # 加上一个包含序列结束词元
    d2l.show_heatmaps(
        attention_weights[:, :, :, :len(engs[-1].split()) + 1].cpu(),
        xlabel='Key positions', ylabel='Query positions')
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

  • 相关阅读:
    JS实现简易观察者模式
    TCP练习
    ZooKeeper中节点的操作命令(查看、创建、删除节点)
    2023-09-14力扣每日一题
    Miniconda创建paddlepaddle环境
    贪心算法题
    第三章-Mybatis源码解析-以xml方式走流程-mapper解析(三)
    c# IEnumerable--扩展方法
    现代 CSS 解决方案:文字颜色自动适配背景色!
    快速发布服务到生产环境(手动操作)
  • 原文地址:https://blog.csdn.net/Rrrrrr900/article/details/138195921