原文: https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html
作者: Sean Robertson
這是關(guān)于“從頭開始進行 NLP”的第三篇也是最后一篇教程,我們在其中編寫自己的類和函數(shù)來預(yù)處理數(shù)據(jù)以完成 NLP 建模任務(wù)。 我們希望在完成本教程后,您將繼續(xù)學習緊接著本教程的三本教程, <cite>torchtext</cite> 如何為您處理許多此類預(yù)處理。
在這個項目中,我們將教授將法語翻譯成英語的神經(jīng)網(wǎng)絡(luò)。
[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 .
……取得不同程度的成功。
通過序列到序列網(wǎng)絡(luò)的簡單但強大的構(gòu)想,使這成為可能,在該網(wǎng)絡(luò)中,兩個循環(huán)神經(jīng)網(wǎng)絡(luò)協(xié)同工作,將一個序列轉(zhuǎn)換為另一個序列。 編碼器網(wǎng)絡(luò)將輸入序列壓縮為一個向量,而解碼器網(wǎng)絡(luò)將該向量展開為一個新序列。
為了改進此模型,我們將使用注意機制,該機制可讓解碼器學習將注意力集中在輸入序列的特定范圍內(nèi)。
推薦讀物:
我假設(shè)您至少已經(jīng)安裝了 PyTorch,了解 Python 和了解 Tensors:
了解序列到序列網(wǎng)絡(luò)及其工作方式也將很有用:
您還將找到先前的 NLP 從零開始:使用字符級 RNN 對名稱進行分類的教程,以及 NLP 從零開始:使用字符級 RNN 生成名稱的指南,因為這些概念是有用的 分別與編碼器和解碼器模型非常相似。
有關(guān)更多信息,請閱讀介紹以下主題的論文:
要求
from __future__ import unicode_literals, print_function, division
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")
該項目的數(shù)據(jù)是成千上萬的英語到法語翻譯對的集合。
開放數(shù)據(jù)堆棧交換上的這個問題使我指向開放翻譯站點 https://tatoeba.org/ ,該站點可從 https://tatoeba.org/下載。 eng / downloads -更好的是,有人在這里做了額外的工作,將語言對拆分為單獨的文本文件: https://www.manythings.org/anki/
英文對法文對太大,無法包含在倉庫中,因此請先下載到data/eng-fra.txt
,然后再繼續(xù)。 該文件是制表符分隔的翻譯對列表:
I am cold. J'ai froid.
注意:
從的下載數(shù)據(jù),并將其提取到當前目錄。
與字符級 RNN 教程中使用的字符編碼類似,我們將一種語言中的每個單詞表示為一個單向矢量,或者零外的一個巨大矢量(除了單個索引(在單詞的索引處))。 與一種語言中可能存在的數(shù)十個字符相比,單詞有很多,因此編碼向量要大得多。 但是,我們將作弊并整理數(shù)據(jù)以使每種語言僅使用幾千個單詞。
我們需要每個單詞一個唯一的索引,以便以后用作網(wǎng)絡(luò)的輸入和目標。 為了跟蹤所有這些信息,我們將使用一個名為Lang
的幫助程序類,該類具有單詞→索引(word2index
)和索引→單詞(index2word
)字典,以及每個要使用的單詞word2count
的計數(shù) 以便以后替換稀有詞。
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 字符轉(zhuǎn)換為 ASCII,將所有內(nèi)容都轉(zhuǎn)換為小寫,并修剪大多數(shù)標點符號。
# 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
要讀取數(shù)據(jù)文件,我們將文件分成幾行,然后將行分成兩對。 這些文件都是英語→其他語言的,因此,如果我們要從其他語言→英語進行翻譯,我添加了reverse
標志來反轉(zhuǎn)對。
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
由于示例句子的數(shù)量很多,并且我們想快速訓練一些東西,因此我們將數(shù)據(jù)集修剪為僅相對較短和簡單的句子。 在這里,最大長度為 10 個字(包括結(jié)尾的標點符號),并且我們正在過濾翻譯成“我是”或“他是”等形式的句子(考慮到前面已替換掉撇號的情況)。
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)]
準備數(shù)據(jù)的完整過程是:
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 10599 sentence pairs
Counting words...
Counted words:
fra 4345
eng 2803
['je ne suis pas grand .', 'i m not tall .']
遞歸神經(jīng)網(wǎng)絡(luò)(RNN)是在序列上運行并將其自身的輸出用作后續(xù)步驟的輸入的網(wǎng)絡(luò)。
序列到序列網(wǎng)絡(luò)或 seq2seq 網(wǎng)絡(luò)或編碼器解碼器網(wǎng)絡(luò)是由兩個稱為編碼器和解碼器的 RNN 組成的模型。 編碼器讀取輸入序列并輸出單個向量,而解碼器讀取該向量以產(chǎn)生輸出序列。
與使用單個 RNN 進行序列預(yù)測(每個輸入對應(yīng)一個輸出)不同,seq2seq 模型使我們擺脫了序列長度和順序的限制,這使其非常適合在兩種語言之間進行翻譯。
考慮一下句子“ Je ne suis pas le chat noir”→“我不是黑貓”。 輸入句子中的大多數(shù)單詞在輸出句子中具有直接翻譯,但是順序略有不同,例如 “黑貓聊天”和“黑貓”。 由于采用“ ne / pas”結(jié)構(gòu),因此在輸入句子中還有一個單詞。 直接從輸入單詞的序列中產(chǎn)生正確的翻譯將是困難的。
使用 seq2seq 模型,編碼器創(chuàng)建單個矢量,在理想情況下,該矢量將輸入序列的“含義”編碼為單個矢量-句子的某些 N 維空間中的單個點。
seq2seq 網(wǎng)絡(luò)的編碼器是 RNN,它為輸入句子中的每個單詞輸出一些值。 對于每個輸入字,編碼器輸出一個向量和一個隱藏狀態(tài),并將隱藏狀態(tài)用于下一個輸入字。
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
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,它采用編碼器輸出矢量并輸出單詞序列來創(chuàng)建翻譯。
在最簡單的 seq2seq 解碼器中,我們僅使用編碼器的最后一個輸出。 最后的輸出有時稱為上下文向量,因為它對整個序列的上下文進行編碼。 該上下文向量用作解碼器的初始隱藏狀態(tài)。
在解碼的每個步驟中,為解碼器提供輸入令牌和隱藏狀態(tài)。 初始輸入令牌是字符串開始<SOS>
令牌,第一個隱藏狀態(tài)是上下文向量(編碼器的最后一個隱藏狀態(tài))。
class DecoderRNN(nn.Module):
def __init__(self, hidden_size, 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)
我鼓勵您訓練并觀察該模型的結(jié)果,但是為了節(jié)省空間,我們將直接努力,并引入注意機制。
如果僅上下文向量在編碼器和解碼器之間傳遞,則該單個向量承擔對整個句子進行編碼的負擔。
注意使解碼器網(wǎng)絡(luò)可以針對解碼器自身輸出的每一步,“專注”于編碼器輸出的不同部分。 首先,我們計算一組注意權(quán)重。 將這些與編碼器輸出向量相乘以創(chuàng)建加權(quán)組合。 結(jié)果(在代碼中稱為attn_applied
)應(yīng)包含有關(guān)輸入序列特定部分的信息,從而幫助解碼器選擇正確的輸出字。
計算注意力權(quán)重的方法是使用另一個前饋層attn
,并使用解碼器的輸入和隱藏狀態(tài)作為輸入。 由于訓練數(shù)據(jù)中包含各種大小的句子,因此要實際創(chuàng)建和訓練該層,我們必須選擇可以應(yīng)用的最大句子長度(輸入長度??,用于編碼器輸出)。 最大長度的句子將使用所有注意權(quán)重,而較短的句子將僅使用前幾個。
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=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(self.output_size, self.hidden_size)
self.attn = nn.Linear(self.hidden_size * 2, self.max_length)
self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)
self.dropout = nn.Dropout(self.dropout_p)
self.gru = nn.GRU(self.hidden_size, self.hidden_size)
self.out = nn.Linear(self.hidden_size, self.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)
注意;
還有其他形式的注意力可以通過使用相對位置方法來解決長度限制問題。 閱讀基于注意力的神經(jīng)機器翻譯的有效方法中的“本地注意力”信息。
為了訓練,對于每一對,我們將需要一個輸入張量(輸入句子中單詞的索引)和目標張量(目標句子中單詞的索引)。 創(chuàng)建這些向量時,我們會將 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)
為了進行訓練,我們通過編碼器運行輸入語句,并跟蹤每個輸出和最新的隱藏狀態(tài)。 然后,為解碼器提供<SOS>令牌作為其第一個輸入,并將編碼器的最后一個隱藏狀態(tài)作為其第一個隱藏狀態(tài)。
“教師強制”的概念是使用實際目標輸出作為每個下一個輸入,而不是使用解碼器的猜測作為下一個輸入。 使用教師強制會導致其收斂更快,但是當使用受過訓練的網(wǎng)絡(luò)時,可能會顯示不穩(wěn)定。
您可以觀察到以教師為主導的網(wǎng)絡(luò)的輸出,這些輸出閱讀的是連貫的語法,但卻偏離了正確的翻譯-直觀地,它學會了代表輸出語法,并且一旦老師說了最初的幾個單詞就可以“理解”含義,但是 首先,它還沒有正確地學習如何從翻譯中創(chuàng)建句子。
由于 PyTorch 的 autograd 具有給我們的自由,我們可以通過簡單的 if 語句隨意選擇是否使用教師強迫。 調(diào)高teacher_forcing_ratio
以使用更多功能。
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: Feed the target as the next input
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:
# Without teacher forcing: use its own predictions as the next input
for di in range(target_length):
decoder_output, decoder_hidden, decoder_attention = decoder(
decoder_input, decoder_hidden, encoder_outputs)
topv, topi = decoder_output.topk(1)
decoder_input = topi.squeeze().detach() # detach from history as input
loss += criterion(decoder_output, target_tensor[di])
if decoder_input.item() == EOS_token:
break
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
return loss.item() / target_length
這是一個幫助功能,用于在給定當前時間和進度%的情況下打印經(jīng)過的時間和估計的剩余時間。
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))
整個訓練過程如下所示:
然后我們多次調(diào)用train
,并偶爾打印進度(示例的百分比,到目前為止的時間,估計的時間)和平均損失。
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 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
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)
使用訓練時保存的損失值數(shù)組plot_losses
,使用 matplotlib 進行繪制。
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)
評估與訓練基本相同,但是沒有目標,因此我們只需將解碼器的預(yù)測反饋給每一步。 每當它預(yù)測一個單詞時,我們都會將其添加到輸出字符串中,如果它預(yù)測到 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) # SOS
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()
return decoded_words, decoder_attentions[:di + 1]
我們可以從訓練集中評估隨機句子,并打印出輸入,目標和輸出以做出一些主觀的質(zhì)量判斷:
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('')
有了所有這些幫助器功能(看起來像是額外的工作,但它使運行多個實驗更加容易),我們實際上可以初始化網(wǎng)絡(luò)并開始訓練。
請記住,輸入句子已被嚴格過濾。 對于這個小的數(shù)據(jù)集,我們可以使用具有 256 個隱藏節(jié)點和單個 GRU 層的相對較小的網(wǎng)絡(luò)。 在 MacBook CPU 上運行約 40 分鐘后,我們將獲得一些合理的結(jié)果。
注意:
如果運行此筆記本,則可以進行訓練,中斷內(nèi)核,評估并在以后繼續(xù)進行訓練。 注釋掉編碼器和解碼器已初始化的行,然后再次運行trainIters
。
hidden_size = 256
encoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device)
attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)
trainIters(encoder1, attn_decoder1, 75000, print_every=5000)
得出:
1m 54s (- 26m 42s) (5000 6%) 2.8452
3m 44s (- 24m 19s) (10000 13%) 2.2926
5m 34s (- 22m 17s) (15000 20%) 1.9628
7m 24s (- 20m 23s) (20000 26%) 1.7224
9m 15s (- 18m 31s) (25000 33%) 1.4997
11m 7s (- 16m 41s) (30000 40%) 1.3610
12m 58s (- 14m 49s) (35000 46%) 1.2299
14m 48s (- 12m 57s) (40000 53%) 1.0881
16m 38s (- 11m 5s) (45000 60%) 0.9991
18m 29s (- 9m 14s) (50000 66%) 0.9053
20m 19s (- 7m 23s) (55000 73%) 0.8031
22m 8s (- 5m 32s) (60000 80%) 0.7141
23m 58s (- 3m 41s) (65000 86%) 0.6693
25m 48s (- 1m 50s) (70000 93%) 0.6342
27m 38s (- 0m 0s) (75000 100%) 0.5604
evaluateRandomly(encoder1, attn_decoder1)
得出:
> je suis tres serieux .
= i m quite serious .
< i m very serious . <EOS>
> tu es creatif .
= you re creative .
< you re creative . <EOS>
> j attends de vos nouvelles .
= i m looking forward to hearing from you .
< i m looking forward to hearing from you . <EOS>
> tu es un de ces pauvres types !
= you re such a jerk .
< you re such a jerk . <EOS>
> je ne suis pas si preoccupe .
= i m not that worried .
< i m not that worried . <EOS>
> vous etes avides .
= you re greedy .
< you re greedy . <EOS>
> ils ne sont pas satisfaits .
= they re not happy .
< they re not happy . <EOS>
> nous avons tous peur .
= we re all afraid .
< we re all scared . <EOS>
> nous sommes tous uniques .
= we re all unique .
< we re all unique . <EOS>
> c est un tres chouette garcon .
= he s a very nice boy .
< he s a very nice boy . <EOS>
注意機制的一個有用特性是其高度可解釋的輸出。 因為它用于加權(quán)輸入序列的特定編碼器輸出,所以我們可以想象一下在每個時間步長上網(wǎng)絡(luò)最關(guān)注的位置。
您可以簡單地運行plt.matshow(attentions)
以將注意力輸出顯示為矩陣,其中列為輸入步驟,行為輸出步驟:
output_words, attentions = evaluate(
encoder1, attn_decoder1, "je suis trop froid .")
plt.matshow(attentions.numpy())
為了獲得更好的觀看體驗,我們將做一些額外的工作來添加軸和標簽:
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(
encoder1, attn_decoder1, 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 .")
得出:
input = elle a cinq ans de moins que moi .
output = she is five years years years years . <EOS>
input = elle est trop petit .
output = she is 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 director . <EOS>
I am test \t I am test
),則可以將其用作自動編碼器。 嘗試這個:訓練為自動編碼器僅保存編碼器網(wǎng)絡(luò)從那里訓練新的解碼器進行翻譯腳本的總運行時間:(27 分鐘 45.966 秒)
Download Python source code: seq2seq_translation_tutorial.py
Download Jupyter notebook: seq2seq_translation_tutorial.ipynb
由獅身人面像畫廊生成的畫廊
更多建議: