当前位置:   article > 正文

PyTorch翻译官网教程-NLP FROM SCRATCH: TRANSLATION WITH A SEQUENCE TO SEQUENCE NETWORK AND ATTENTION_from-scratch translation

from-scratch translation

官网链接

NLP From Scratch: Translation with a Sequence to Sequence Network and Attention — PyTorch Tutorials 2.0.1+cu117 documentation

使用Seq2Seq网络和注意力机制进行翻译

这是关于“NLP From Scratch”的第三个也是最后一个教程,在这里我们编写自己的类和函数来预处理数据以完成我们的NLP建模任务。我们希望在您完成本教程后,您可学习到torchtext在这三个教程中如何预处理数据的。

在这个项目中,我们将教用一个神经网络将法语翻译成英语。

  1. [KEY: > input, = target, < output]
  2. > il est en train de peindre un tableau .
  3. = he is painting a picture .
  4. < he is painting a picture .
  5. > pourquoi ne pas essayer ce vin delicieux ?
  6. = why not try that delicious wine ?
  7. < why not try that delicious wine ?
  8. > elle n est pas poete mais romanciere .
  9. = she is not a poet but a novelist .
  10. < she not not a poet but a novelist .
  11. > vous etes trop maigre .
  12. = you re too skinny .
  13. < you re all alone .

这是由简单而强大的seq2seq(sequence to sequence network)网络思想实现的,其中两个循环神经网络一起工作,将一个序列转换为另一个序列。编码器网络将输入序列压缩成一个向量,解码器网络将该向量展开成一个新的序列。

为了改进这个模型,我们将使用注意力机制(attention mechanism),它让解码器学习专注于输入序列的特定范围。

推荐阅读:

我假设你至少安装了PyTorch,了解Python,并且理解张量:


了解Sequence to Sequence网络及其工作原理也很有用:

您还可以找到前面的教程NLP From Scratch: Classifying Names with a Character-Level RNNNLP From Scratch: Generating Names with a Character-Level RNN 也非常有用,因为这些概念分别与编码器和解码器模型非常相似。

依赖

  1. from __future__ import unicode_literals, print_function, division
  2. from io import open
  3. import unicodedata
  4. import re
  5. import random
  6. import torch
  7. import torch.nn as nn
  8. from torch import optim
  9. import torch.nn.functional as F
  10. import numpy as np
  11. from torch.utils.data import TensorDataset, DataLoader, RandomSampler
  12. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


加载数据文件

这个项目的数据是一组成千上万的由英语翻译成法语的数据对。

Open Data Stack Exchange 的这个问题指引了 开放网站Tatoeba: Collection of sentences and translations 可以下载数据,下载网址是Download sentences - Tatoeba,有人做了额外的工作,将语言对拆分为单独的文本文件:Tab-delimited Bilingual Sentence Pairs from the Tatoeba Project (Good for Anki and Similar Flashcard Applications)

这个仓库中的英语转成法语的数据对太大,所以我们在这之前下载data/eng-fra.txt该文件是一个tab分隔的翻译对列表:

I am cold.    J'ai froid.

从这里(here)下载数据并将其解压缩到当前目录。

与字符级RNN教程中使用的字符编码类似,我们将把语言中的每个单词表示为一个独热向量,或者巨大的零向量只有一个1(在单词的索引处)。与语言中可能存在的数十个字符相比,有更多的单词,因此编码向量要大得多。然而,我们会稍微做点手脚,将数据精简为每种语言只使用几千个单词。

我们需要每个单词的唯一索引,以便稍后用作网络的输入和目标。为了跟踪这一切,我们将使用一个名为Lang的辅助类,它拥有word->index的映射(word2index)和index->word 的映射(index2word)词典。以及word2count的每个单词的计数,稍后将用于替换罕见单词。

  1. SOS_token = 0
  2. EOS_token = 1
  3. class Lang:
  4. def __init__(self, name):
  5. self.name = name
  6. self.word2index = {}
  7. self.word2count = {}
  8. self.index2word = {0: "SOS", 1: "EOS"}
  9. self.n_words = 2 # Count SOS and EOS
  10. def addSentence(self, sentence):
  11. for word in sentence.split(' '):
  12. self.addWord(word)
  13. def addWord(self, word):
  14. if word not in self.word2index:
  15. self.word2index[word] = self.n_words
  16. self.word2count[word] = 1
  17. self.index2word[self.n_words] = word
  18. self.n_words += 1
  19. else:
  20. self.word2count[word] += 1

这些文件都是Unicode格式的,为了简化,我们将把Unicode字符转换为ASCII,所有字符都小写,并删去大部分标点符号。

  1. # Turn a Unicode string to plain ASCII, thanks to
  2. # https://stackoverflow.com/a/518232/2809427
  3. def unicodeToAscii(s):
  4. return ''.join(
  5. c for c in unicodedata.normalize('NFD', s)
  6. if unicodedata.category(c) != 'Mn'
  7. )
  8. # Lowercase, trim, and remove non-letter characters
  9. def normalizeString(s):
  10. s = unicodeToAscii(s.lower().strip())
  11. s = re.sub(r"([.!?])", r" \1", s)
  12. s = re.sub(r"[^a-zA-Z!?]+", r" ", s)
  13. return s.strip()

为了读取数据文件,我们将文件分成几行,然后再将每行分成一对。所有的文件都是英语→其他语言,所以如果我们想从其他语言翻译→英语,我添加了reverse标志来反转这数据对。

  1. def readLangs(lang1, lang2, reverse=False):
  2. print("Reading lines...")
  3. # Read the file and split into lines
  4. lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\
  5. read().strip().split('\n')
  6. # Split every line into pairs and normalize
  7. pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
  8. # Reverse pairs, make Lang instances
  9. if reverse:
  10. pairs = [list(reversed(p)) for p in pairs]
  11. input_lang = Lang(lang2)
  12. output_lang = Lang(lang1)
  13. else:
  14. input_lang = Lang(lang1)
  15. output_lang = Lang(lang2)
  16. return input_lang, output_lang, pairs

由于有很多例句,我们希望快速训练,因此我们将数据集修剪为相对较短和简单的句子。这里的最大长度是10个单词(包括结尾的标点符号),我们将过滤为翻译为“I am”或“He is”等形式的句子(考虑之前替换的撇号)。

  1. MAX_LENGTH = 10
  2. eng_prefixes = (
  3. "i am ", "i m ",
  4. "he is", "he s ",
  5. "she is", "she s ",
  6. "you are", "you re ",
  7. "we are", "we re ",
  8. "they are", "they re "
  9. )
  10. def filterPair(p):
  11. return len(p[0].split(' ')) < MAX_LENGTH and \
  12. len(p[1].split(' ')) < MAX_LENGTH and \
  13. p[1].startswith(eng_prefixes)
  14. def filterPairs(pairs):
  15. return [pair for pair in pairs if filterPair(pair)]

准备数据的完整过程如下:

  • 读取文本文件并分行,分行成数据对
  • 规范化文本,按长度和内容过滤
  • 将句子数据对制作成单词表
  1. def prepareData(lang1, lang2, reverse=False):
  2. input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse)
  3. print("Read %s sentence pairs" % len(pairs))
  4. pairs = filterPairs(pairs)
  5. print("Trimmed to %s sentence pairs" % len(pairs))
  6. print("Counting words...")
  7. for pair in pairs:
  8. input_lang.addSentence(pair[0])
  9. output_lang.addSentence(pair[1])
  10. print("Counted words:")
  11. print(input_lang.name, input_lang.n_words)
  12. print(output_lang.name, output_lang.n_words)
  13. return input_lang, output_lang, pairs
  14. input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
  15. print(random.choice(pairs))

输出

  1. Reading lines...
  2. Read 135842 sentence pairs
  3. Trimmed to 11445 sentence pairs
  4. Counting words...
  5. Counted words:
  6. fra 4601
  7. eng 2991
  8. ['tu preches une convaincue', 'you re preaching to the choir']

Seq2Seq模型

循环神经网络(Recurrent Neural Network, RNN)是一种对序列进行操作,并将自己的输出作为后续步骤的输入的网络。

Sequence to Sequence network,或seq2seq网络,或编码器解码器网络(Encoder Decoder network),是由两个称为编码器和解码器的rnn组成的模型。编码器读取输入序列并输出单个向量,解码器读取该向量以产生输出序列。

与单个RNN的序列预测不同,其中每个输入对应于一个输出,seq2seq模型将我们从序列长度和顺序中解放出来,使其成为两种语言之间翻译的理想选择。

想想这个句子“Je ne suis pas le chat noir”→“I am not the black cat”。输入句子中的大多数单词在输出句子中都有直接的翻译,但顺序略有不同,例如“chat noir”和“black cat”。由于ne/pas结构,输入句子中还多了一个单词。从输入的单词序列中直接生成正确的译文是很困难的。

使用seq2seq模型,编码器创建单个向量,在理想情况下,该向量将输入序列的“意义”编码为单个向量——句子的某个N维空间中的单个点。

编码器

seq2seq网络的编码器是一个RNN,它从输入句子中为每个单词输出一些值。对于每个输入单词,编码器输出一个向量和一个隐藏状态,并将隐藏状态用于下一个输入单词。

  1. class EncoderRNN(nn.Module):
  2. def __init__(self, input_size, hidden_size, dropout_p=0.1):
  3. super(EncoderRNN, self).__init__()
  4. self.hidden_size = hidden_size
  5. self.embedding = nn.Embedding(input_size, hidden_size)
  6. self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
  7. self.dropout = nn.Dropout(dropout_p)
  8. def forward(self, input):
  9. embedded = self.dropout(self.embedding(input))
  10. output, hidden = self.gru(embedded)
  11. return output, hidden

解码器

解码器是另一个RNN,它接收编码器输出向量并输出单词序列来创建翻译。

简单解码器

在最简单的seq2seq解码器中,我们只使用编码器的最后一个输出。最后一个输出有时被称为上下文向量,因为它对整个序列的上下文进行了编码。这个上下文向量被用作解码器的初始隐藏状态。

在解码的每个步骤中,解码器都会得到一个输入标记和隐藏状态。初始输入标记是字符串的起始处<SOS>标记,第一个隐藏状态是上下文向量(编码器的最后一个隐藏状态)。

  1. class DecoderRNN(nn.Module):
  2. def __init__(self, hidden_size, output_size):
  3. super(DecoderRNN, self).__init__()
  4. self.embedding = nn.Embedding(output_size, hidden_size)
  5. self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
  6. self.out = nn.Linear(hidden_size, output_size)
  7. def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
  8. batch_size = encoder_outputs.size(0)
  9. decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
  10. decoder_hidden = encoder_hidden
  11. decoder_outputs = []
  12. for i in range(MAX_LENGTH):
  13. decoder_output, decoder_hidden = self.forward_step(decoder_input, decoder_hidden)
  14. decoder_outputs.append(decoder_output)
  15. if target_tensor is not None:
  16. # Teacher forcing: Feed the target as the next input
  17. decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
  18. else:
  19. # Without teacher forcing: use its own predictions as the next input
  20. _, topi = decoder_output.topk(1)
  21. decoder_input = topi.squeeze(-1).detach() # detach from history as input
  22. decoder_outputs = torch.cat(decoder_outputs, dim=1)
  23. decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
  24. return decoder_outputs, decoder_hidden, None # We return `None` for consistency in the training loop
  25. def forward_step(self, input, hidden):
  26. output = self.embedding(input)
  27. output = F.relu(output)
  28. output, hidden = self.gru(output, hidden)
  29. output = self.out(output)
  30. return output, hidden

我鼓励你训练并观察这个模型的结果,但为了节省空间,我们将直接介绍注意力机制。

注意力解码器

如果仅在编码器和解码器之间传递上下文向量,则该单个向量承担编码整个句子的负担。

注意力允许解码器网络对解码器自身输出的每一步“关注”编码器输出的不同部分。首先,我们计算一组注意力权重。这些向量将与编码器输出向量相乘,以创建加权组合。结果(在代码中称为attn_applied)应该包含输入序列中特定部分的信息,从而帮助解码器选择正确的输出单词。

注意力权重的计算由另一个前馈层attn完成,使用解码器的输入和隐藏状态作为输入。因为训练数据中有各种大小的句子,为了实际创建和训练这一层,我们必须选择它可以应用的最大句子长度(对于编码器输出来说,输入长度)。最长长度的句子将使用所有注意力权重,而较短的句子将只使用前几个注意力权重。

Bahdanau注意力,也称为加性注意力,是序列到序列模型中常用的注意力机制,特别是在神经机器翻译任务中。Bahdanau等人在他们的论文《Neural Machine Translation by Jointly Learning to Align and Translate》中介绍了它。该注意力机制采用一种学习到的对齐模型来计算编码器和解码器隐藏状态之间的注意力分数。它利用前馈神经网络来计算对齐得分。

然而,也有其他可用的注意力机制,如Luong attention,通过取解码器隐藏状态和编码器隐藏状态之间的点积来计算注意力分数。它不涉及Bahdanau attention中使用的非线性转换。

在本教程中,我们将使用Bahdanau attention。然而,探索修改注意力机制以使用Luong注意力是一项有价值的练习。

  1. class BahdanauAttention(nn.Module):
  2. def __init__(self, hidden_size):
  3. super(BahdanauAttention, self).__init__()
  4. self.Wa = nn.Linear(hidden_size, hidden_size)
  5. self.Ua = nn.Linear(hidden_size, hidden_size)
  6. self.Va = nn.Linear(hidden_size, 1)
  7. def forward(self, query, keys):
  8. scores = self.Va(torch.tanh(self.Wa(query) + self.Ua(keys)))
  9. scores = scores.squeeze(2).unsqueeze(1)
  10. weights = F.softmax(scores, dim=-1)
  11. context = torch.bmm(weights, keys)
  12. return context, weights
  13. class AttnDecoderRNN(nn.Module):
  14. def __init__(self, hidden_size, output_size, dropout_p=0.1):
  15. super(AttnDecoderRNN, self).__init__()
  16. self.embedding = nn.Embedding(output_size, hidden_size)
  17. self.attention = BahdanauAttention(hidden_size)
  18. self.gru = nn.GRU(2 * hidden_size, hidden_size, batch_first=True)
  19. self.out = nn.Linear(hidden_size, output_size)
  20. self.dropout = nn.Dropout(dropout_p)
  21. def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
  22. batch_size = encoder_outputs.size(0)
  23. decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
  24. decoder_hidden = encoder_hidden
  25. decoder_outputs = []
  26. attentions = []
  27. for i in range(MAX_LENGTH):
  28. decoder_output, decoder_hidden, attn_weights = self.forward_step(
  29. decoder_input, decoder_hidden, encoder_outputs
  30. )
  31. decoder_outputs.append(decoder_output)
  32. attentions.append(attn_weights)
  33. if target_tensor is not None:
  34. # Teacher forcing: Feed the target as the next input
  35. decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
  36. else:
  37. # Without teacher forcing: use its own predictions as the next input
  38. _, topi = decoder_output.topk(1)
  39. decoder_input = topi.squeeze(-1).detach() # detach from history as input
  40. decoder_outputs = torch.cat(decoder_outputs, dim=1)
  41. decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
  42. attentions = torch.cat(attentions, dim=1)
  43. return decoder_outputs, decoder_hidden, attentions
  44. def forward_step(self, input, hidden, encoder_outputs):
  45. embedded = self.dropout(self.embedding(input))
  46. query = hidden.permute(1, 0, 2)
  47. context, attn_weights = self.attention(query, encoder_outputs)
  48. input_gru = torch.cat((embedded, context), dim=2)
  49. output, hidden = self.gru(input_gru, hidden)
  50. output = self.out(output)
  51. return output, hidden, attn_weights

还有其他形式的注意力,通过使用相对位置方法来绕过长度限制。请参阅《Effective Approaches to Attention-based Neural Machine Translation》中有关“局部注意力”的内容。

训练

准备训练数据

为了训练,对于每个对,我们将需要一个输入张量(输入句子中单词的索引)和目标张量(目标句子中单词的索引)。在创建这些向量时,我们将EOS token附加到两个序列中。

  1. def indexesFromSentence(lang, sentence):
  2. return [lang.word2index[word] for word in sentence.split(' ')]
  3. def tensorFromSentence(lang, sentence):
  4. indexes = indexesFromSentence(lang, sentence)
  5. indexes.append(EOS_token)
  6. return torch.tensor(indexes, dtype=torch.long, device=device).view(1, -1)
  7. def tensorsFromPair(pair):
  8. input_tensor = tensorFromSentence(input_lang, pair[0])
  9. target_tensor = tensorFromSentence(output_lang, pair[1])
  10. return (input_tensor, target_tensor)
  11. def get_dataloader(batch_size):
  12. input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
  13. n = len(pairs)
  14. input_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
  15. target_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
  16. for idx, (inp, tgt) in enumerate(pairs):
  17. inp_ids = indexesFromSentence(input_lang, inp)
  18. tgt_ids = indexesFromSentence(output_lang, tgt)
  19. inp_ids.append(EOS_token)
  20. tgt_ids.append(EOS_token)
  21. input_ids[idx, :len(inp_ids)] = inp_ids
  22. target_ids[idx, :len(tgt_ids)] = tgt_ids
  23. train_data = TensorDataset(torch.LongTensor(input_ids).to(device),
  24. torch.LongTensor(target_ids).to(device))
  25. train_sampler = RandomSampler(train_data)
  26. train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
  27. return input_lang, output_lang, train_dataloader

训练模型

为了训练,我们通过编码器运行输入句子,并跟踪每个输出和最新的隐藏状态。然后给出解码器的<SOS>;标记作为其第一个输入,编码器的最后一个隐藏状态作为其第一个隐藏状态。

“Teacher forcing”是指使用真实目标输出作为下一个输入,而不是使用解码器的猜测作为下一个输入。使用Teacher forcing可以使其更快地收敛,但当使用训练好的网络时,它可能会表现出不稳定性。(when the trained network is exploited, it may exhibit instability.)

你可以观察到teacher-forced 网络的输出,它们阅读时语法连贯,但偏离了正确的翻译——从直觉上讲,它已经学会了表示输出的语法,并且可以在教师告诉它前几个单词时“拾取”意思,但它还没有正确地学会如何从翻译中创建句子。

由于PyTorch的autograd提供给我们的自由度,我们可以通过一个简单的if语句随机选择是否使用teacher forced。打开teacher_forcing_ratio 来使用更多。

  1. def train_epoch(dataloader, encoder, decoder, encoder_optimizer,
  2. decoder_optimizer, criterion):
  3. total_loss = 0
  4. for data in dataloader:
  5. input_tensor, target_tensor = data
  6. encoder_optimizer.zero_grad()
  7. decoder_optimizer.zero_grad()
  8. encoder_outputs, encoder_hidden = encoder(input_tensor)
  9. decoder_outputs, _, _ = decoder(encoder_outputs, encoder_hidden, target_tensor)
  10. loss = criterion(
  11. decoder_outputs.view(-1, decoder_outputs.size(-1)),
  12. target_tensor.view(-1)
  13. )
  14. loss.backward()
  15. encoder_optimizer.step()
  16. decoder_optimizer.step()
  17. total_loss += loss.item()
  18. return total_loss / len(dataloader)


这是一个辅助函数,根据当前时间和进度%打印经过的时间和估计的剩余时间。

  1. import time
  2. import math
  3. def asMinutes(s):
  4. m = math.floor(s / 60)
  5. s -= m * 60
  6. return '%dm %ds' % (m, s)
  7. def timeSince(since, percent):
  8. now = time.time()
  9. s = now - since
  10. es = s / (percent)
  11. rs = es - s
  12. return '%s (- %s)' % (asMinutes(s), asMinutes(rs))

整个训练过程如下所示:

  • 启动计时器
  • 初始化优化器和准则
  • 创建一组训练数据对
  • 开始绘制空损失数组

然后我们多次调用train,偶尔打印进度(示例的百分比,到目前为止的时间,估计时间)和平均损失。

  1. def train(train_dataloader, encoder, decoder, n_epochs, learning_rate=0.001,
  2. print_every=100, plot_every=100):
  3. start = time.time()
  4. plot_losses = []
  5. print_loss_total = 0 # Reset every print_every
  6. plot_loss_total = 0 # Reset every plot_every
  7. encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
  8. decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate)
  9. criterion = nn.NLLLoss()
  10. for epoch in range(1, n_epochs + 1):
  11. loss = train_epoch(train_dataloader, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)
  12. print_loss_total += loss
  13. plot_loss_total += loss
  14. if epoch % print_every == 0:
  15. print_loss_avg = print_loss_total / print_every
  16. print_loss_total = 0
  17. print('%s (%d %d%%) %.4f' % (timeSince(start, epoch / n_epochs),
  18. epoch, epoch / n_epochs * 100, print_loss_avg))
  19. if epoch % plot_every == 0:
  20. plot_loss_avg = plot_loss_total / plot_every
  21. plot_losses.append(plot_loss_avg)
  22. plot_loss_total = 0
  23. showPlot(plot_losses)

绘制结果

绘图使用matplotlib完成,使用训练时保存的损失值数组plot_loss。

  1. import matplotlib.pyplot as plt
  2. plt.switch_backend('agg')
  3. import matplotlib.ticker as ticker
  4. import numpy as np
  5. def showPlot(points):
  6. plt.figure()
  7. fig, ax = plt.subplots()
  8. # this locator puts ticks at regular intervals
  9. loc = ticker.MultipleLocator(base=0.2)
  10. ax.yaxis.set_major_locator(loc)
  11. plt.plot(points)

评估

评估与训练基本相同,但没有目标,所以我们只是将解码器的预测反馈给自己每一步。每次它预测一个单词时,我们将其添加到输出字符串中,如果它预测EOS token,我们就停止。我们还存储解码器的注意力输出以备以后显示。

  1. def evaluate(encoder, decoder, sentence, input_lang, output_lang):
  2. with torch.no_grad():
  3. input_tensor = tensorFromSentence(input_lang, sentence)
  4. encoder_outputs, encoder_hidden = encoder(input_tensor)
  5. decoder_outputs, decoder_hidden, decoder_attn = decoder(encoder_outputs, encoder_hidden)
  6. _, topi = decoder_outputs.topk(1)
  7. decoded_ids = topi.squeeze()
  8. decoded_words = []
  9. for idx in decoded_ids:
  10. if idx.item() == EOS_token:
  11. decoded_words.append('<EOS>')
  12. break
  13. decoded_words.append(output_lang.index2word[idx.item()])
  14. return decoded_words, decoder_attn

我们可以从训练集中随机评估句子,并打印出输入、目标和输出来做出一些主观质量判断

  1. def evaluateRandomly(encoder, decoder, n=10):
  2. for i in range(n):
  3. pair = random.choice(pairs)
  4. print('>', pair[0])
  5. print('=', pair[1])
  6. output_words, _ = evaluate(encoder, decoder, pair[0], input_lang, output_lang)
  7. output_sentence = ' '.join(output_words)
  8. print('<', output_sentence)
  9. print('')

训练与评估

有了所有这些辅助函数(看起来是额外的工作,但它使运行多个实验更容易),我们可以实际初始化网络并开始训练。

记住,输入的句子是经过严格过滤的。对于这个小数据集,我们可以使用相对较小的网络,包含256个隐藏节点和一个GRU层。在MacBook CPU上运行大约40分钟后,我们将得到一些合理的结果。

如果你运行这个笔记,你可以训练,中断内核,评估,并在以后继续训练。注释掉初始化编码器和解码器的代码行,再次运行trainIters。

  1. hidden_size = 128
  2. batch_size = 32
  3. input_lang, output_lang, train_dataloader = get_dataloader(batch_size)
  4. encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
  5. decoder = AttnDecoderRNN(hidden_size, output_lang.n_words).to(device)
  6. train(train_dataloader, encoder, decoder, 80, print_every=5, plot_every=5)

输出

  1. Reading lines...
  2. Read 135842 sentence pairs
  3. Trimmed to 11445 sentence pairs
  4. Counting words...
  5. Counted words:
  6. fra 4601
  7. eng 2991
  8. 0m 24s (- 6m 8s) (5 6%) 1.5304
  9. 0m 49s (- 5m 43s) (10 12%) 0.6776
  10. 1m 13s (- 5m 18s) (15 18%) 0.3528
  11. 1m 37s (- 4m 53s) (20 25%) 0.1948
  12. 2m 2s (- 4m 29s) (25 31%) 0.1202
  13. 2m 26s (- 4m 4s) (30 37%) 0.0833
  14. 2m 51s (- 3m 40s) (35 43%) 0.0637
  15. 3m 15s (- 3m 15s) (40 50%) 0.0520
  16. 3m 40s (- 2m 51s) (45 56%) 0.0455
  17. 4m 4s (- 2m 26s) (50 62%) 0.0400
  18. 4m 29s (- 2m 2s) (55 68%) 0.0373
  19. 4m 53s (- 1m 37s) (60 75%) 0.0347
  20. 5m 18s (- 1m 13s) (65 81%) 0.0333
  21. 5m 42s (- 0m 48s) (70 87%) 0.0310
  22. 6m 7s (- 0m 24s) (75 93%) 0.0297
  23. 6m 31s (- 0m 0s) (80 100%) 0.0292

设置dropout图层为eval模式

  1. encoder.eval()
  2. decoder.eval()
  3. evaluateRandomly(encoder, decoder)

输出

  1. > il est si mignon !
  2. = he s so cute
  3. < he s so cute <EOS>
  4. > je vais me baigner
  5. = i m going to take a bath
  6. < i m going to take a bath <EOS>
  7. > c est un travailleur du batiment
  8. = he s a construction worker
  9. < he s a construction worker <EOS>
  10. > je suis representant de commerce pour notre societe
  11. = i m a salesman for our company
  12. < i m a salesman for our company <EOS>
  13. > vous etes grande
  14. = you re big
  15. < you are big <EOS>
  16. > tu n es pas normale
  17. = you re not normal
  18. < you re not normal <EOS>
  19. > je n en ai pas encore fini avec vous
  20. = i m not done with you yet
  21. < i m not done with you yet <EOS>
  22. > je suis desole pour ce malentendu
  23. = i m sorry about my mistake
  24. < i m sorry about my mistake <EOS>
  25. > nous ne sommes pas impressionnes
  26. = we re not impressed
  27. < we re not impressed <EOS>
  28. > tu as la confiance de tous
  29. = you are trusted by every one of us
  30. < you are trusted by every one of us <EOS>

注意力可视化

注意力机制的一个有用属性是其高度可解释的输出。因为它用于对输入序列的特定编码器输出进行加权,我们可以想象在每个时间步长查看网络最关注的地方。


你可以简单地运行plt.matshow(attention),以矩阵的形式显示注意力输出。为了获得更好的观看体验,我们将额外添加坐标轴和标签:

  1. def showAttention(input_sentence, output_words, attentions):
  2. fig = plt.figure()
  3. ax = fig.add_subplot(111)
  4. cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
  5. fig.colorbar(cax)
  6. # Set up axes
  7. ax.set_xticklabels([''] + input_sentence.split(' ') +
  8. ['<EOS>'], rotation=90)
  9. ax.set_yticklabels([''] + output_words)
  10. # Show label at every tick
  11. ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
  12. ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
  13. plt.show()
  14. def evaluateAndShowAttention(input_sentence):
  15. output_words, attentions = evaluate(encoder, decoder, input_sentence, input_lang, output_lang)
  16. print('input =', input_sentence)
  17. print('output =', ' '.join(output_words))
  18. showAttention(input_sentence, output_words, attentions[0, :len(output_words), :])
  19. evaluateAndShowAttention('il n est pas aussi grand que son pere')
  20. evaluateAndShowAttention('je suis trop fatigue pour conduire')
  21. evaluateAndShowAttention('je suis desole si c est une question idiote')
  22. evaluateAndShowAttention('je suis reellement fiere de vous')

输出

  1. input = il n est pas aussi grand que son pere
  2. output = he is not as tall as his father <EOS>
  3. /var/lib/jenkins/workspace/intermediate_source/seq2seq_translation_tutorial.py:823: UserWarning:
  4. FixedFormatter should only be used together with FixedLocator
  5. /var/lib/jenkins/workspace/intermediate_source/seq2seq_translation_tutorial.py:825: UserWarning:
  6. FixedFormatter should only be used together with FixedLocator
  7. input = je suis trop fatigue pour conduire
  8. output = i m too tired to drive <EOS>
  9. input = je suis desole si c est une question idiote
  10. output = i m sorry if this is a stupid question <EOS>
  11. input = je suis reellement fiere de vous
  12. output = i m really proud of you <EOS>

练习

  • 请尝试使用不同的数据集
    • 另一对语言
    • 人→机器(例如物联网命令)
    • 聊天→响应
    • 问题→答案
  • 将嵌入替换为预训练的词嵌入,如word2vec或GloVe
  • 尝试使用更多的层、更多的隐藏单元和更多的句子。比较训练时间和结果。
  • 如果您使用一个翻译文件,其中对有两个相同的短语(I am test \t I am test),则可以将其用作自动编码器。试试这个:
    • 训练成一个自动编码器
    • 只保存编码器网络
    • 从那里训练一个新的解码器进行翻译

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/438315
推荐阅读
相关标签
  

闽ICP备14008679号