66Bahdanau 注意力

点击查看代码
import torch
from torch import nn
from d2l import torch as d2l

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

    @property
    # 画图
    def attention_weights(self):
        raise NotImplementedError


# 编码器不变
# 实现带有Bahdanau注意力的循环神经网络解码器
class Seq2SeqAttentionDecoder(AttentionDecoder):
    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers, dropout=0, **kwargs):
        super(Seq2SeqAttentionDecoder, self).__init__(**kwargs)
        # 𝑎(𝐪,𝐤)=𝐰⊤𝑣 tanh(𝐖𝑞𝐪+𝐖𝑘𝐤)
        # key_size, query_size, num_hiddens
        # AdditiveAttention可以学参
        self.attention = d2l.AdditiveAttention(num_hiddens, num_hiddens, num_hiddens, dropout)
        # seq2seq
        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):
        # enc_valid_lens 英语哪些哪些是填充的
        # 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)
        # 上面的init_state展开
        enc_outputs, hidden_state, enc_valid_lens = state
        # 输入X的形状为(batch_size,num_steps)
        # 输出X的形状为(num_steps,batch_size,embed_size)
        X = self.embedding(X).permute(1, 0, 2)
        outputs, self._attention_weights = [], []
        for x in X:
            # hidden_state[-1]上一时刻最后一层rnn的输出
            # hidden_state大小为(num_layers, batch_size, num_hiddens)
            # hidden_state[-1]取出了大小为(batch_size, num_hiddens)的矩阵
            # dim=1 加一个num_query的维度
            # query的形状为(batch_size, 1, num_hiddens)
            query = torch.unsqueeze(hidden_state[-1], dim=1)
            # context的形状为(batch_size,1,num_hiddens)
            # (batch_size, num_query, value_size)
            context = self.attention(query, enc_outputs, enc_outputs, enc_valid_lens)
            # 在特征维度上连结
            # print('torch.unsqueeze(x, dim=1)).shape : ', torch.unsqueeze(x, dim=1).shape)
            # """torch.unsqueeze(x, dim=1)).shape :  torch.Size([4, 1, 8])"""
            x = torch.cat((context, torch.unsqueeze(x, dim=1)), dim=-1)
            # print('x.shape : ', x.shape)
            # """x.shape :  torch.Size([4, 1, 24])"""
            # 在循环神经网络模型中,第一个轴对应于时间步
            # 将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


# 测试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)  # (batch_size,num_steps)
state = decoder.init_state(encoder(X), None)
output, state = decoder(X, state)
print('output.shape : ', output.shape)
print('len(state) : ', len(state))
print('state[0].shape : ', state[0].shape)
print('len(state[1]) : ', len(state[1]))
print('state[1].shape : ', state[1].shape)
print('state[1][0].shape : ', state[1][0].shape)
"""
                        (num_steps,batch_size,vocab_size)
output.shape :  torch.Size([4, 7, 10])
len(state) :  3
state[0] enc_outputs        (num_steps,batch_size,num_hiddens)
state[0].shape :  torch.Size([4, 7, 16])
len(state[1]) :  2
hidden_state                (num_layers,batch_size,num_hiddens)
state[1].shape :  torch.Size([2, 4, 16])
state[1][0].shape :  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)

# 将几个英语句子翻译成法语
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}')


posted @   荒北  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示