注意
跳转至页面底部 下载完整示例代码。
从零开始的 NLP:使用序列到序列网络和注意力机制进行翻译#
创建日期:2017 年 3 月 24 日 | 最后更新:2024 年 10 月 21 日 | 最后验证:2024 年 11 月 05 日
作者: Sean Robertson
本教程是三部曲系列的一部分
这是关于从零开始的 NLP (NLP From Scratch) 系列教程的第三篇,也是最后一篇。在这些教程中,我们将编写自己的类和函数来预处理数据,从而完成 NLP 建模任务。
在这个项目中,我们将教一个神经网络将法语翻译成英语。
[KEY: > input, = target, < output]
> il est en train de peindre un tableau .
= he is painting a picture .
< he is painting a picture .
> pourquoi ne pas essayer ce vin delicieux ?
= why not try that delicious wine ?
< why not try that delicious wine ?
> elle n est pas poete mais romanciere .
= she is not a poet but a novelist .
< she not not a poet but a novelist .
> vous etes trop maigre .
= you re too skinny .
< you re all alone .
……翻译效果因情况而异。
这一切归功于简单而强大的序列到序列(sequence to sequence)网络理念,其中两个循环神经网络协同工作,将一个序列转换为另一个序列。编码器网络将输入序列压缩为向量,解码器网络将该向量展开为新的序列。
为了改进该模型,我们将使用注意力机制(attention mechanism),它允许解码器学习关注输入序列的特定范围。
推荐阅读
假设您至少已经安装了 PyTorch,熟悉 Python,并了解张量(Tensors)
https://pytorch.ac.cn/ 获取安装说明
PyTorch 深度学习:60 分钟闪电入门,了解 PyTorch 的基础知识
通过实例学习PyTorch,进行广泛而深入的概览
为前Torch用户准备的PyTorch教程,如果您是前Lua Torch用户
了解序列到序列网络及其工作原理也会很有帮助
您还会发现之前的从零开始的 NLP:使用字符级 RNN 进行姓名分类和从零开始的 NLP:使用字符级 RNN 生成姓名教程很有用,因为这些概念分别与编码器和解码器模型非常相似。
要求
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import re
import random
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import numpy as np
from torch.utils.data import TensorDataset, DataLoader, RandomSampler
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
加载数据文件#
该项目的数据集是由数千个英法翻译对组成的。
Open Data Stack Exchange 上的这个问题向我推荐了开源翻译网站 https://tatoeba.org/,您可以在 https://tatoeba.org/eng/downloads 下载数据。更好的是,有人已经完成了额外的工作,将语言对拆分成了单独的文本文件:https://www.manythings.org/anki/
英法翻译对文件太大,无法包含在代码仓库中,因此在继续之前,请先将其下载到 data/eng-fra.txt。该文件是以制表符分隔的翻译对列表。
I am cold. J'ai froid.
注意
从此处下载数据并解压到当前目录。
与字符级 RNN 教程中使用的字符编码类似,我们将语言中的每个单词表示为一个独热(one-hot)向量,即一个巨大的向量,除了单个位置(单词的索引)为 1 外,其余均为 0。与语言中可能存在的几十个字符相比,单词的数量要多得多,因此编码向量大得多。不过,我们将稍作简化,将数据修剪为每种语言仅使用几千个单词。
稍后我们需要为每个单词分配一个唯一索引,作为网络的输入和目标。为了跟踪这些信息,我们将使用一个名为 Lang 的辅助类,它包含单词到索引 (word2index) 和索引到单词 (index2word) 的字典,以及用于稍后替换稀有词的每个单词的计数 word2count。
SOS_token = 0
EOS_token = 1
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2count = {}
self.index2word = {0: "SOS", 1: "EOS"}
self.n_words = 2 # Count SOS and EOS
def addSentence(self, sentence):
for word in sentence.split(' '):
self.addWord(word)
def addWord(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
这些文件均为 Unicode 编码,为了简化,我们将把 Unicode 字符转换为 ASCII,将所有内容转为小写,并去掉大部分标点符号。
# Turn a Unicode string to plain ASCII, thanks to
# https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
# Lowercase, trim, and remove non-letter characters
def normalizeString(s):
s = unicodeToAscii(s.lower().strip())
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z!?]+", r" ", s)
return s.strip()
读取数据文件时,我们将把文件拆分为行,然后将行拆分为翻译对。文件格式全为“英语 → 其他语言”,因此如果我们想实现“其他语言 → 英语”的翻译,我添加了 reverse 标志来反转翻译对。
def readLangs(lang1, lang2, reverse=False):
print("Reading lines...")
# Read the file and split into lines
lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\
read().strip().split('\n')
# Split every line into pairs and normalize
pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
# Reverse pairs, make Lang instances
if reverse:
pairs = [list(reversed(p)) for p in pairs]
input_lang = Lang(lang2)
output_lang = Lang(lang1)
else:
input_lang = Lang(lang1)
output_lang = Lang(lang2)
return input_lang, output_lang, pairs
由于示例句子非常多,而我们希望快速训练模型,因此我们将数据集修剪为仅包含相对短小且简单的句子。这里的最大长度为 10 个单词(包含结束标点符号),并且我们过滤掉了那些翻译成“I am”或“He is”等形式的句子(考虑到了之前替换掉的撇号)。
MAX_LENGTH = 10
eng_prefixes = (
"i am ", "i m ",
"he is", "he s ",
"she is", "she s ",
"you are", "you re ",
"we are", "we re ",
"they are", "they re "
)
def filterPair(p):
return len(p[0].split(' ')) < MAX_LENGTH and \
len(p[1].split(' ')) < MAX_LENGTH and \
p[1].startswith(eng_prefixes)
def filterPairs(pairs):
return [pair for pair in pairs if filterPair(pair)]
准备数据的完整流程如下:
读取文本文件并拆分为行,将行拆分为翻译对
规范化文本,按长度和内容过滤
从翻译对中的句子创建单词列表
def prepareData(lang1, lang2, reverse=False):
input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse)
print("Read %s sentence pairs" % len(pairs))
pairs = filterPairs(pairs)
print("Trimmed to %s sentence pairs" % len(pairs))
print("Counting words...")
for pair in pairs:
input_lang.addSentence(pair[0])
output_lang.addSentence(pair[1])
print("Counted words:")
print(input_lang.name, input_lang.n_words)
print(output_lang.name, output_lang.n_words)
return input_lang, output_lang, pairs
input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
print(random.choice(pairs))
Reading lines...
Read 135842 sentence pairs
Trimmed to 11445 sentence pairs
Counting words...
Counted words:
fra 4601
eng 2991
['je suis tres occupe ces jours ci', 'i am very busy these days']
Seq2Seq 模型#
循环神经网络(RNN)是一种对序列进行操作的网络,它使用自身的输出作为后续步骤的输入。
序列到序列(Sequence to Sequence)网络,也称为 seq2seq 网络或 编码器-解码器网络,是由两个分别称为编码器和解码器的 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,它为输入句子中的每个单词输出一个值。对于每个输入单词,编码器都会输出一个向量和一个隐藏状态,并将该隐藏状态用于下一个输入单词。
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, dropout_p=0.1):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
self.dropout = nn.Dropout(dropout_p)
def forward(self, input):
embedded = self.dropout(self.embedding(input))
output, hidden = self.gru(embedded)
return output, hidden
解码器#
解码器是另一个 RNN,它接收编码器的输出向量,并输出单词序列以完成翻译。
简单解码器#
在最简单的 seq2seq 解码器中,我们仅使用编码器的最后输出。这个最后输出有时被称为上下文向量(context vector),因为它编码了整个序列的上下文。该上下文向量被用作解码器的初始隐藏状态。
在解码的每一步,解码器都会被赋予一个输入标记和隐藏状态。初始输入标记是字符串开始标记 <SOS>,第一个隐藏状态是上下文向量(编码器的最后一个隐藏状态)。
class DecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size):
super(DecoderRNN, self).__init__()
self.embedding = nn.Embedding(output_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
batch_size = encoder_outputs.size(0)
decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
decoder_hidden = encoder_hidden
decoder_outputs = []
for i in range(MAX_LENGTH):
decoder_output, decoder_hidden = self.forward_step(decoder_input, decoder_hidden)
decoder_outputs.append(decoder_output)
if target_tensor is not None:
# Teacher forcing: Feed the target as the next input
decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
else:
# Without teacher forcing: use its own predictions as the next input
_, topi = decoder_output.topk(1)
decoder_input = topi.squeeze(-1).detach() # detach from history as input
decoder_outputs = torch.cat(decoder_outputs, dim=1)
decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
return decoder_outputs, decoder_hidden, None # We return `None` for consistency in the training loop
def forward_step(self, input, hidden):
output = self.embedding(input)
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = self.out(output)
return output, hidden
我鼓励您训练并观察该模型的结果,但为了节省空间,我们将直接引入注意力机制(Attention Mechanism)以追求更好的效果。
注意力解码器#
如果编码器和解码器之间仅传递上下文向量,那么这单个向量将承担编码整个句子的负担。
注意力机制允许解码器网络在解码自身输出的每一步,“聚焦”于编码器输出的不同部分。首先,我们计算一组注意力权重。这些权重将与编码器的输出向量相乘,从而创建一个加权组合。结果(在代码中称为 attn_applied)应该包含关于输入序列特定部分的信息,从而帮助解码器选择正确的输出单词。
计算注意力权重是通过另一个前馈层 attn 完成的,使用解码器的输入和隐藏状态作为输入。由于训练数据中存在各种长度的句子,为了实际创建和训练这一层,我们必须选择一个该层可以应用的最大句子长度(即编码器输出的输入长度)。最大长度的句子将使用所有的注意力权重,而较短的句子则仅使用前几个。
Bahdanau 注意力,也称为加性注意力(additive attention),是序列到序列模型中常用的注意力机制,特别是在神经机器翻译任务中。它由 Bahdanau 等人在其论文《通过联合学习对齐和翻译进行神经机器翻译》中提出。该注意力机制采用学习到的对齐模型来计算编码器和解码器隐藏状态之间的注意力分数。它利用前馈神经网络来计算对齐分数。
此外,还有其他可用的注意力机制,例如 Luong 注意力,它通过计算解码器隐藏状态与编码器隐藏状态之间的点积来计算注意力分数。它不涉及 Bahdanau 注意力中使用的非线性变换。
在本教程中,我们将使用 Bahdanau 注意力。不过,尝试将其修改为使用 Luong 注意力将是一项非常有价值的练习。
class BahdanauAttention(nn.Module):
def __init__(self, hidden_size):
super(BahdanauAttention, self).__init__()
self.Wa = nn.Linear(hidden_size, hidden_size)
self.Ua = nn.Linear(hidden_size, hidden_size)
self.Va = nn.Linear(hidden_size, 1)
def forward(self, query, keys):
scores = self.Va(torch.tanh(self.Wa(query) + self.Ua(keys)))
scores = scores.squeeze(2).unsqueeze(1)
weights = F.softmax(scores, dim=-1)
context = torch.bmm(weights, keys)
return context, weights
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, dropout_p=0.1):
super(AttnDecoderRNN, self).__init__()
self.embedding = nn.Embedding(output_size, hidden_size)
self.attention = BahdanauAttention(hidden_size)
self.gru = nn.GRU(2 * hidden_size, hidden_size, batch_first=True)
self.out = nn.Linear(hidden_size, output_size)
self.dropout = nn.Dropout(dropout_p)
def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
batch_size = encoder_outputs.size(0)
decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
decoder_hidden = encoder_hidden
decoder_outputs = []
attentions = []
for i in range(MAX_LENGTH):
decoder_output, decoder_hidden, attn_weights = self.forward_step(
decoder_input, decoder_hidden, encoder_outputs
)
decoder_outputs.append(decoder_output)
attentions.append(attn_weights)
if target_tensor is not None:
# Teacher forcing: Feed the target as the next input
decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
else:
# Without teacher forcing: use its own predictions as the next input
_, topi = decoder_output.topk(1)
decoder_input = topi.squeeze(-1).detach() # detach from history as input
decoder_outputs = torch.cat(decoder_outputs, dim=1)
decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
attentions = torch.cat(attentions, dim=1)
return decoder_outputs, decoder_hidden, attentions
def forward_step(self, input, hidden, encoder_outputs):
embedded = self.dropout(self.embedding(input))
query = hidden.permute(1, 0, 2)
context, attn_weights = self.attention(query, encoder_outputs)
input_gru = torch.cat((embedded, context), dim=2)
output, hidden = self.gru(input_gru, hidden)
output = self.out(output)
return output, hidden, attn_weights
注意
还有其他形式的注意力,它们通过使用相对位置方法来克服长度限制。请参阅 《基于注意力的神经机器翻译的有效方法》中关于“局部注意力”的内容。
训练#
准备训练数据#
为了训练,对于每一对翻译,我们需要一个输入张量(输入句子中单词的索引)和一个目标张量(目标句子中单词的索引)。在创建这些向量时,我们将把 EOS(字符串结束)标记追加到两个序列中。
def indexesFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def tensorFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
return torch.tensor(indexes, dtype=torch.long, device=device).view(1, -1)
def tensorsFromPair(pair):
input_tensor = tensorFromSentence(input_lang, pair[0])
target_tensor = tensorFromSentence(output_lang, pair[1])
return (input_tensor, target_tensor)
def get_dataloader(batch_size):
input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
n = len(pairs)
input_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
target_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
for idx, (inp, tgt) in enumerate(pairs):
inp_ids = indexesFromSentence(input_lang, inp)
tgt_ids = indexesFromSentence(output_lang, tgt)
inp_ids.append(EOS_token)
tgt_ids.append(EOS_token)
input_ids[idx, :len(inp_ids)] = inp_ids
target_ids[idx, :len(tgt_ids)] = tgt_ids
train_data = TensorDataset(torch.LongTensor(input_ids).to(device),
torch.LongTensor(target_ids).to(device))
train_sampler = RandomSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
return input_lang, output_lang, train_dataloader
训练模型#
训练时,我们将输入句子通过编码器,并跟踪每个输出和最新的隐藏状态。然后,解码器接收 <SOS> 标记作为其第一个输入,并将编码器的最后一个隐藏状态作为其第一个隐藏状态。
“教师强制(Teacher forcing)”的概念是使用真实的目标输出作为下一个输入,而不是使用解码器的猜测作为输入。使用教师强制可以使模型收敛得更快,但当训练好的网络被投入使用时,它可能会表现出不稳定性。
您可以观察到,经过教师强制训练的网络输出语法连贯,但会偏离正确翻译——直观地说,它学会了表示输出语法,并且一旦教师告诉它前几个单词,它就能“捕捉”到含义,但它并没有从根本上学会如何从翻译中构建句子。
得益于 PyTorch autograd 提供的自由度,我们可以使用简单的 if 语句随机选择是否使用教师强制。调高 teacher_forcing_ratio 可以更频繁地使用它。
def train_epoch(dataloader, encoder, decoder, encoder_optimizer,
decoder_optimizer, criterion):
total_loss = 0
for data in dataloader:
input_tensor, target_tensor = data
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
encoder_outputs, encoder_hidden = encoder(input_tensor)
decoder_outputs, _, _ = decoder(encoder_outputs, encoder_hidden, target_tensor)
loss = criterion(
decoder_outputs.view(-1, decoder_outputs.size(-1)),
target_tensor.view(-1)
)
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
这是一个辅助函数,用于根据当前时间和进度百分比打印已用时间和预计剩余时间。
import time
import math
def asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def timeSince(since, percent):
now = time.time()
s = now - since
es = s / (percent)
rs = es - s
return '%s (- %s)' % (asMinutes(s), asMinutes(rs))
整个训练过程如下:
启动计时器
初始化优化器和准则
创建训练集对
创建空的损失数组以便绘图
然后我们多次调用 train 并定期打印进度(示例百分比、已用时间、预计时间)和平均损失。
def train(train_dataloader, encoder, decoder, n_epochs, learning_rate=0.001,
print_every=100, plot_every=100):
start = time.time()
plot_losses = []
print_loss_total = 0 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate)
criterion = nn.NLLLoss()
for epoch in range(1, n_epochs + 1):
loss = train_epoch(train_dataloader, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)
print_loss_total += loss
plot_loss_total += loss
if epoch % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
print('%s (%d %d%%) %.4f' % (timeSince(start, epoch / n_epochs),
epoch, epoch / n_epochs * 100, print_loss_avg))
if epoch % plot_every == 0:
plot_loss_avg = plot_loss_total / plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
showPlot(plot_losses)
绘制结果#
绘图使用 matplotlib 完成,利用训练时保存的损失值数组 plot_losses。
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.ticker as ticker
import numpy as np
def showPlot(points):
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
评估#
评估过程与训练基本相同,但由于没有目标,我们只需在每一步将解码器的预测反馈给自己。每次预测一个单词时,我们都将其添加到输出字符串中,如果预测到 EOS 标记,则停止。我们还会存储解码器的注意力输出,以便稍后展示。
def evaluate(encoder, decoder, sentence, input_lang, output_lang):
with torch.no_grad():
input_tensor = tensorFromSentence(input_lang, sentence)
encoder_outputs, encoder_hidden = encoder(input_tensor)
decoder_outputs, decoder_hidden, decoder_attn = decoder(encoder_outputs, encoder_hidden)
_, topi = decoder_outputs.topk(1)
decoded_ids = topi.squeeze()
decoded_words = []
for idx in decoded_ids:
if idx.item() == EOS_token:
decoded_words.append('<EOS>')
break
decoded_words.append(output_lang.index2word[idx.item()])
return decoded_words, decoder_attn
我们可以评估训练集中的随机句子,并打印出输入、目标和输出,从而进行主观质量评判。
def evaluateRandomly(encoder, decoder, n=10):
for i in range(n):
pair = random.choice(pairs)
print('>', pair[0])
print('=', pair[1])
output_words, _ = evaluate(encoder, decoder, pair[0], input_lang, output_lang)
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
训练与评估#
有了这些辅助函数(看起来额外工作不少,但它使运行多个实验变得更容易),我们就可以初始化网络并开始训练了。
请记住,输入句子经过了大量的过滤。对于这个小数据集,我们可以使用相对较小的网络,即 256 个隐藏节点和一层 GRU。在 MacBook CPU 上运行约 40 分钟后,我们将获得一些合理的结果。
注意
如果您运行此笔记本,您可以训练、中断内核、评估,然后再继续训练。只需注释掉初始化编码器和解码器的行,然后再次运行 trainIters 即可。
hidden_size = 128
batch_size = 32
input_lang, output_lang, train_dataloader = get_dataloader(batch_size)
encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
decoder = AttnDecoderRNN(hidden_size, output_lang.n_words).to(device)
train(train_dataloader, encoder, decoder, 80, print_every=5, plot_every=5)
Reading lines...
Read 135842 sentence pairs
Trimmed to 11445 sentence pairs
Counting words...
Counted words:
fra 4601
eng 2991
0m 31s (- 7m 55s) (5 6%) 1.5549
1m 3s (- 7m 21s) (10 12%) 0.6985
1m 34s (- 6m 49s) (15 18%) 0.3633
2m 5s (- 6m 17s) (20 25%) 0.1988
2m 37s (- 5m 46s) (25 31%) 0.1208
3m 8s (- 5m 14s) (30 37%) 0.0825
3m 40s (- 4m 43s) (35 43%) 0.0624
4m 11s (- 4m 11s) (40 50%) 0.0508
4m 43s (- 3m 40s) (45 56%) 0.0451
5m 14s (- 3m 8s) (50 62%) 0.0397
5m 45s (- 2m 37s) (55 68%) 0.0363
6m 17s (- 2m 5s) (60 75%) 0.0346
6m 48s (- 1m 34s) (65 81%) 0.0327
7m 19s (- 1m 2s) (70 87%) 0.0317
7m 51s (- 0m 31s) (75 93%) 0.0302
8m 22s (- 0m 0s) (80 100%) 0.0291
将 dropout 层设置为 eval 模式
encoder.eval()
decoder.eval()
evaluateRandomly(encoder, decoder)
> il est independant de ses parents
= he is independent of his parents
< he is independent of his parents <EOS>
> tu passes trop de temps a l ordinateur
= you re spending too much time on the computer
< you re spending too much time on the computer <EOS>
> ils ne sont pas si mauvais
= they re not so bad
< they re not so bad <EOS>
> vous etes talentueuse
= you re talented
< you re talented <EOS>
> nous sommes a court de munitions
= we re out of ammunition
< we re out of ammunition <EOS>
> vous etes fort emotifs
= you re very emotional
< you re very emotional again <EOS>
> nous ne sommes pas des tueurs
= we re not killers
< we re not killers <EOS>
> il est en train de vous regarder
= he s looking at you
< he s looking at you <EOS>
> tu es celui qui m a entraine
= you re the one who trained me
< you re the one who trained me <EOS>
> nous sommes en train de nous en occuper
= we re handling it
< we re handling it <EOS>
可视化注意力#
注意力机制的一个有用特性是其高度可解释的输出。因为它用于对输入序列的特定编码器输出进行加权,我们可以直观地观察网络在每个时间步最关注的位置。
您可以简单地运行 plt.matshow(attentions) 来查看显示为矩阵的注意力输出。为了获得更好的观看体验,我们将执行额外的步骤来添加坐标轴和标签。
def showAttention(input_sentence, output_words, attentions):
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
fig.colorbar(cax)
# Set up axes
ax.set_xticklabels([''] + input_sentence.split(' ') +
['<EOS>'], rotation=90)
ax.set_yticklabels([''] + output_words)
# Show label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def evaluateAndShowAttention(input_sentence):
output_words, attentions = evaluate(encoder, decoder, input_sentence, input_lang, output_lang)
print('input =', input_sentence)
print('output =', ' '.join(output_words))
showAttention(input_sentence, output_words, attentions[0, :len(output_words), :])
evaluateAndShowAttention('il n est pas aussi grand que son pere')
evaluateAndShowAttention('je suis trop fatigue pour conduire')
evaluateAndShowAttention('je suis desole si c est une question idiote')
evaluateAndShowAttention('je suis reellement fiere de vous')
input = il n est pas aussi grand que son pere
output = he is not as tall as his father <EOS>
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:827: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_xticklabels([''] + input_sentence.split(' ') +
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:829: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_yticklabels([''] + output_words)
input = je suis trop fatigue pour conduire
output = i m too tired to drive <EOS>
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:827: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_xticklabels([''] + input_sentence.split(' ') +
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:829: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_yticklabels([''] + output_words)
input = je suis desole si c est une question idiote
output = i m sorry if this is a stupid question <EOS>
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:827: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_xticklabels([''] + input_sentence.split(' ') +
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:829: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_yticklabels([''] + output_words)
input = je suis reellement fiere de vous
output = i m really proud of you <EOS>
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:827: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_xticklabels([''] + input_sentence.split(' ') +
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:829: UserWarning: set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.
ax.set_yticklabels([''] + output_words)
练习#
尝试其他数据集
其他语言对
人机交互(例如 IOT 命令)
聊天 → 回复
问题 → 回答
将嵌入替换为预训练的词嵌入,例如
word2vec或GloVe尝试更多的层、更多的隐藏单元和更多的句子。比较训练时间和结果。
如果您使用翻译对中包含两个相同短语的文件(
I am test \t I am test),您可以将其用作自编码器。试试这个。作为自编码器进行训练
仅保存编码器网络
在此基础上训练一个新的解码器用于翻译
脚本总运行时间: (8 分 31.132 秒)





