赞
踩
本案例取自PyTorch官网的NLP FROM SCRATCH: TRANSLATION WITH A SEQUENCE TO SEQUENCE NETWORK AND ATTENTION,在此基础上增加了完整的注释以及通俗的讲解,完整代码在文章最后
本项目将会完成 法语 → \rightarrow → 英语 的翻译任务,效果如下:
[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 .
seq2seq模型架构:
为了改进此模型,将会使用到注意力机制,该机制可使解码器更专注于输入序列的特定范围
本案例大致分为如下步骤:
from io import open
import unicodedata
import string
import re
import random
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
数据下载地址: https://download.pytorch.org/tutorial/data.zip,下载到./data/eng-fra.txt
还有一些其他语言翻译的文件,可以从这里下载
单词向量:
我们将需要每个单词一个唯一的索引,以便以后用作网络的输入和目标。 为了跟踪这些,我们将建立一个名为Lang的类,该类具有 单词
→
\rightarrow
→索引(word2index
) 和 索引
→
\rightarrow
→单词(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
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 码,并将所有内容都转换为小写,修剪标点符号
def unicodeToAscii(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def normalizeString(s):
# 将传入字符变为小写并去除两侧空白字符,再传入到unicodeToAscii
s = unicodeToAscii(s.lower().strip())
# 在.!?的前面加一个空格
s = re.sub(r"([.!?])", r" \1", s)
# 将不是字母和标点的都替换为空格
s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
return s
Example:
s = "Are you kidding me?"
nsr = normalizeString(s)
print(nsr)
Out:
are you kidding me ?
re.sub()
用法,这篇文章讲比较全
读取数据文件,将文件拆分为行,然后将每一行拆分为对儿,这些文件都是 英语
→
\rightarrow
→其他语言 的,这里添加了reverse
标志来翻转对儿,使得可以进行 其他语言
→
\rightarrow
→英语 的翻译
def readLangs(lang1, lang2, reverse=False):
print("Reading lines...")
# 读取文件以\n划分,并存到列表lines中
lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\
read().strip().split('\n')
# 对lines列表中的句子进行标准化处理,以\t划分成语言对儿
pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
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
Example:
lang1 = "eng"
lang2 = "fra"
input_lang, output_lang, pairs = readLangs(lang1, lang2)
print("input_lang:", input_lang)
print("output_lang:", output_lang)
print("pairs中的前五个:", pairs[:5])
Out:
Reading lines...
input_lang: <__main__.Lang object at 0x0000026E39FA5430>
output_lang: <__main__.Lang object at 0x0000026E797EB070>
pairs中的前五个: [['go .', 'va !'], ['run !', 'cours !'], ['run !', 'courez !'], ['wow !', 'ca alors !'], ['fire !', 'au feu !']]
Example:
input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse=True)
print("pairs中的前五个:", pairs[:5])
Out:
Reading lines...
pairs中的前五个: [['va !', 'go .'], ['cours !', 'run !'], ['courez !', 'run !'], ['ca alors !', 'wow !'], ['au feu !', 'fire !']]
由于示例句子过多,并且我们想快速的训练,因此我们可以将数据集修剪一下,剩下那些较短的句子以及特定开头的句子。在这里,我们限制句子最大长度为10
# 设置组成句子的最大长度
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)]
Example:
fpairs = filterPairs(pairs)
print("过滤后的pairs前五个:", fpairs[:5])
Out:
过滤后的pairs前五个: [['j ai ans .', 'i m .'], ['je vais bien .', 'i m ok .'], ['ca va .', 'i m ok .'], ['je suis gras .', 'i m fat .'], ['je suis gros .', 'i m fat .']]
准备数据的完整过程:
# 准备数据函数
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))
Out:
Reading lines...
Read 135842 sentence pairs
Trimmed to 10599 sentence pairs
Counting words...
Counted words:
fra 4345
eng 2803
['je suis desolee de vous avoir mal compris .', 'i m sorry i misunderstood you .']
seq2seq 网络的编码器是 RNN(GRU),它为输入句子中的每个单词输出一些值。 对于每个输入字,编码器输出一个向量和一个隐藏状态,并将隐藏状态用于下一个输入字
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
"""
input_size代表编码器的输入尺寸,即源语言的词表大小
hidden_size代表GRU隐层结点个数,也是词嵌入的维度,也是GRU的输入尺寸
"""
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)
def forward(self, input, hidden):
embedded = self.embedding(input).view(1, 1, -1)
output = embedded
output, hidden = self.gru(output, hidden)
return output, hidden
def initHidden(self):
return torch.zeros(1, 1, self.hidden_size, device=device)
解码器是另一个 RNN(GRU),它采用编码器输出向量并输出单词序列来创建翻译
在简单的 seq2seq 解码器中,仅使用编码器的最后一个输出。 该最后的输出有时称为上下文向量
,因为它是从整个序列中编码所得。 该上下文向量用作解码器的初始隐藏状态。
在解码的每个步骤中,为解码器提供输入标记和隐藏状态。 初始输入标记是字符串开始<SOS>
标记,第一个隐藏状态是上下文向量(编码器的最后一个隐藏状态)。
class DecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size):
"""
hidden_size代表解码器中GRU输入尺寸,也是隐层节点数
output_size代表输出尺寸,也是目标语言词表大小
"""
super(DecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(output_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, input, hidden):
output = self.embedding(input).view(1, 1, -1)
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = self.softmax(self.out(output[0]))
return output, hidden
def initHidden(self):
return torch.zeros(1, 1, self.hidden_size, device=device)
如果仅上下文向量在编码器和解码器之间传递,则这单个向量承担对整个句子进行编码的负担。
注意力机制使解码器网络可以专注”于编码器输出的不同部分。 首先,我们计算一组注意力权重attn_weights
。 将这些与编码器输出向量相乘以创建加权组合。 结果(在代码中称为attn_applied
)应包含有关输入序列特定部分的信息,从而帮助解码器选择正确的输出字
另一个前馈层attn
使用解码器的输入和隐藏状态作为输入来计算注意力权重。 由于训练数据中包含各种大小的句子,因此要实际创建和训练该层,我们必须选择可以应用的最大句子长度(输入长度,用于编码器输出)。 最大长度的句子将使用所有注意权重,而较短的句子将仅使用前几个,在代码中创建了注意力权重的矩阵。
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):
"""
hidden_size代表解码器中GRU输入尺寸,也是隐层节点数
output_size代表输出尺寸,也是目标语言词表大小
dropout_p为dropout的概率
max_length为句子最大长度
"""
super(AttnDecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.output_size = output_size
self.dropout_p = dropout_p
self.max_length = max_length
self.embedding = nn.Embedding(output_size, hidden_size)
self.attn = nn.Linear(hidden_size * 2, max_length) # Q,K做拼接之后线性变换
self.attn_combine = nn.Linear(hidden_size * 2, hidden_size)
self.dropout = nn.Dropout(dropout_p)
self.gru = nn.GRU(hidden_size, hidden_size)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, input, hidden, encoder_outputs):
embedded = self.embedding(input).view(1, 1, -1)
embedded = self.dropout(embedded)
attn_weights = F.softmax(
self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)
attn_applied = torch.bmm(attn_weights.unsqueeze(0),
encoder_outputs.unsqueeze(0))
output = torch.cat((embedded[0],attn_applied[0]), 1)
output = self.attn_combine(output).unsqueeze(0)
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = F.log_softmax(self.out(output[0]), dim=1)
return output, hidden, attn_weights
def initHidden(self):
return torch.zeros(1, 1, self.hidden_size, device=device)
为了训练,对每一对儿句子我们需要输入张量input_tensor
(indexes of the words in the input sentence) ,和目标张量target_tensor
(indexes of the words in the target sentence) , 创建这些张量时,我们会将会对两个序列附加EOS
标记
def indexexFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def tensorFromSentence(lang, sentence):
indexes = indexexFromSentence(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)
Example:
前面我们已经做好了pairs
,这里取出pairs
中下标为5的语言对儿看一看
pair = pairs[5]
print(pair) # ['je suis en forme .', 'i m fit .']
print('')
pair_tensor = tensorsFromPair(pair)
print(pair_tensor)
Out:
['je suis en forme .', 'i m fit .']
(tensor([[ 6],
[11],
[14],
[15],
[ 5],
[ 1]], device='cuda:0'),
tensor([[2],
[3],
[7],
[4],
[1]], device='cuda:0'))
我们通过对编码器输入语句,并跟踪每个输出和最新的隐藏状态。 然后,为解码器提供<SOS>
标记作为其第一个输入,为解码器提供编码器最后的隐藏状态作为其第一个输入的隐藏状态。
“Teacher forcing” 的作用是使用实际目标输出作为下一个输入,而不是使用解码器的猜测作为下一个输入。 使用教师强制会导致其收敛更快,但是当使用受过训练的网络时,可能会显示不稳定。通俗的理解也就是不要让解码器一错再错,这里会给“Teacher forcing”一个概率,使模型朝着正确的方向训练。
可以观察到使用“Teacher forcing”网络的输出,这些输出阅读起来比较连贯,但是却偏离了正确直观的翻译,它已经学会了输出语法,并且一旦“Teacher forcing”了最初的几个单词,网络就可以领会意思,但是网络还没有正确地学习如何从翻译中创建句子。
teacher_forcing_ratio = 0.5
def train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):
encoder_hidden = encoder.initHidden()
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
input_length = input_tensor.size(0)
target_length = target_tensor.size(0)
encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)
loss = 0
for ei in range(input_length):
encoder_output, encoder_hidden = encoder(
input_tensor[ei], encoder_hidden)
encoder_outputs[ei] = encoder_output[0, 0]
decoder_input = torch.tensor([[SOS_token]], device=device)
decoder_hidden = encoder_hidden
use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False
if use_teacher_forcing:
# 使用teacher_forcing
for di in range(target_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs)
loss += criterion(decoder_output, target_tensor[di])
decoder_input = target_tensor[di] # Teacher forcing
else:
# 未使用teacher_forcing
for di in range(target_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs)
loss += criterion(decoder_output, target_tensor[di])
topv, topi = decoder_output.topk(1)
decoder_input = topi.squeeze().detach()
if decoder_input.item() == EOS_token:
break
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
return loss.item() / target_length
创建一个辅助函数,用于显示当前使用时间以及剩余时间
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))
整个训练过程大致如下:
def trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=100, learning_rate=0.01):
start = time.time()
plot_losses = []
print_loss_total = 0
plot_loss_total = 0
encoder_optimizer = optim.SGD(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.SGD(decoder.parameters(), lr=learning_rate)
training_pairs = [tensorsFromPair(random.choice(pairs)) for i in range(n_iters)]
criterion = nn.NLLLoss()
for iter in range(1, n_iters + 1):
training_pair = training_pairs[iter - 1]
input_tensor = training_pair[0]
target_tensor = training_pair[1]
loss = train(input_tensor, target_tensor, encoder,
decoder, encoder_optimizer, decoder_optimizer, criterion)
print_loss_total += loss
plot_loss_total += loss
if iter % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),
iter, iter / n_iters * 100, print_loss_avg))
if iter % plot_every == 0:
plot_loss_avg = plot_loss_total / plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
showPlot(plot_losses)
import matplotlib.pyplot as plt
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)
plt.show()
首先来看隐藏层为256,75000轮的训练
hidden_size = 256
encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
attn_decoder = AttnDecoderRNN(hidden_size, output_lang.n_words).to(device)
trainIters(encoder, attn_decoder, 75000, print_every=5000)
Out:
2m 42s (- 37m 50s) (5000 6%) 2.8619
5m 11s (- 33m 41s) (10000 13%) 2.2712
7m 41s (- 30m 44s) (15000 20%) 1.9341
10m 12s (- 28m 4s) (20000 26%) 1.7109
12m 45s (- 25m 31s) (25000 33%) 1.4950
15m 19s (- 22m 58s) (30000 40%) 1.3228
17m 55s (- 20m 29s) (35000 46%) 1.1795
20m 37s (- 18m 2s) (40000 53%) 1.0768
23m 23s (- 15m 35s) (45000 60%) 0.9753
26m 0s (- 13m 0s) (50000 66%) 0.8512
28m 33s (- 10m 23s) (55000 73%) 0.7900
31m 7s (- 7m 46s) (60000 80%) 0.6997
33m 40s (- 5m 10s) (65000 86%) 0.6590
36m 14s (- 2m 35s) (70000 93%) 0.5747
38m 48s (- 0m 0s) (75000 100%) 0.5467
之后我感觉预估效果不是特别的理想,改为了隐层大小512,100000轮的训练,由于在前面的语料处理过程中,我们剔除了大量的语句,所以模型的泛化也是有限的。
hidden_size = 512
encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
attn_decoder = AttnDecoderRNN(hidden_size, output_lang.n_words).to(device)
trainIters(encoder, attn_decoder, 100000, print_every=5000)
Out:
2m 52s (- 54m 32s) (5000 5%) 2.7670
5m 22s (- 48m 19s) (10000 10%) 2.1351
7m 53s (- 44m 43s) (15000 15%) 1.7443
10m 26s (- 41m 45s) (20000 20%) 1.4394
12m 59s (- 38m 59s) (25000 25%) 1.1715
15m 31s (- 36m 14s) (30000 30%) 1.0099
18m 3s (- 33m 32s) (35000 35%) 0.8444
20m 40s (- 31m 0s) (40000 40%) 0.7230
23m 14s (- 28m 24s) (45000 45%) 0.6176
25m 48s (- 25m 48s) (50000 50%) 0.5188
28m 22s (- 23m 13s) (55000 55%) 0.4567
30m 54s (- 20m 36s) (60000 60%) 0.4013
33m 26s (- 18m 0s) (65000 65%) 0.3555
36m 4s (- 15m 27s) (70000 70%) 0.3091
38m 46s (- 12m 55s) (75000 75%) 0.2962
41m 22s (- 10m 20s) (80000 80%) 0.2382
43m 58s (- 7m 45s) (85000 85%) 0.2223
46m 38s (- 5m 10s) (90000 90%) 0.2037
49m 13s (- 2m 35s) (95000 95%) 0.1809
51m 56s (- 0m 0s) (100000 100%) 0.1664
可以看到损失确实是比前面降低了不少
评估与训练基本相同,但是由于没有目标语句,因此我们只需记录解码器每一步的预测,每当它预测一个单词时,添加到输出列表中,如果它预测到EOS
标记,则停止。 我们还将存储解码器的注意力输出,接下来绘图使用。
def evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):
with torch.no_grad():
input_tensor = tensorFromSentence(input_lang, sentence)
input_length = input_tensor.size(0)
encoder_hidden = encoder.initHidden()
encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)
for ei in range(input_length):
encoder_output, encoder_hidden = encoder(input_tensor[ei], encoder_hidden)
encoder_outputs[ei] += encoder_output[0, 0]
decoder_input = torch.tensor([[SOS_token]], device=device)
decoder_hidden = encoder_hidden
decoded_words = []
decoder_attentions = torch.zeros(max_length, max_length)
for di in range(max_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs)
decoder_attentions[di] = decoder_attention.data
topv, topi = decoder_output.data.topk(1)
if topi.item() == EOS_token:
decoded_words.append('<EOS>')
break
else:
decoded_words.append(output_lang.index2word[topi.item()])
decoder_input = topi.squeeze().detach()
# di+1即为拿到当前运行到的di步的注意力张量即可
return decoded_words, decoder_attentions[:di + 1]
def evaluateRandomly(encoder, decoder, n=10):
for i in range(n):
pair = random.choice(pairs)
print('>', pair[0])
print('=', pair[1])
output_words, attentions = evaluate(encoder, decoder, pair[0])
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
evaluateRandomly(encoder, attn_decoder)
Out:
> il est respecte par tout le monde .
= he is respected by everyone .
< he is respected by everybody . <EOS>
> tu as probablement tort .
= you are probably wrong .
< you are probably wrong . <EOS>
> je compte devenir ingenieur .
= i am going to be an engineer .
< i am going to be an engineer . <EOS>
> j y compte .
= i m counting on it .
< i m counting on it . <EOS>
> il n est pas a la maison .
= he isn t at home .
< he s not at home . <EOS>
> j en ai assez d ecouter tes rodomontades .
= i m tired of listening to your bragging .
< i m tired of listening to your bragging . <EOS>
> tu es parfois si puerile .
= you are so childish sometimes .
< you are so childish sometimes . <EOS>
> nous faisons tout ce que nous pouvons .
= we re doing all we can .
< we re doing all we can . <EOS>
> je lis un magazine .
= i am reading a magazine .
< i am reading a magazine . <EOS>
> vous etes pleines de ressources .
= you re very resourceful .
< you re very resourceful . <EOS>
output_words, attentions = evaluate(
encoder, attn_decoder, "il a l habitude des ordinateurs")
output_words = ' '.join(output_words)
print(output_words)
plt.matshow(attentions.numpy())
Out:
'he is familiar with computers . <EOS>'
为了便于观看,加入轴与标签
def showAttention(input_sentence, output_words, attentions):
# Set up figure with colorbar
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.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, attn_decoder, input_sentence)
print('input =', input_sentence)
print('output =', ' '.join(output_words))
showAttention(input_sentence, output_words, attentions)
evaluateAndShowAttention("elle a cinq ans de moins que moi .")
evaluateAndShowAttention("elle est trop petit .")
evaluateAndShowAttention("je ne crains pas de mourir .")
evaluateAndShowAttention("c est un jeune directeur plein de talent .")
Out:
input = elle a cinq ans de moins que moi .
output = she s five years younger than i am . <EOS>
input = elle est trop petit .
output = she s too short . <EOS>
input = je ne crains pas de mourir .
output = i m not scared of dying . <EOS>
input = c est un jeune directeur plein de talent .
output = he s a talented young . <EOS>
热力图颜色参数:这里
分析:横坐标为输入语言单词,这里为法语,纵坐标为目标语言英语,每个目标单词对应一行,每一行为一个注意力张量。
举例:看上面最后的一幅图,第一行为he,在预测这个单词的时候更加注意源语句的est单词,依次类推
注意力热力图越类似一个对角线,代表预测的更精准,因为大部分的翻译都是从前向后的依次翻译。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。