注意
跳至末尾 下載完整的示例程式碼。
從零開始學 NLP:使用 Seq2Seq 網路和注意力機制進行翻譯#
創建於: 2017年3月24日 | 最後更新: 2024年10月21日 | 最後驗證: 2024年11月05日
作者: Sean Robertson
本教程是三部曲系列的一部分
這是關於“從零開始學 NLP”系列的第三篇也是最後一篇教程,我們將編寫自己的類和函式來預處理資料,以完成 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 .
… 翻譯效果參差不齊。
這一切得益於簡單而強大的 序列到序列網路 思想,其中兩個迴圈神經網路協同工作,將一個序列轉換為另一個序列。編碼器網路將輸入序列壓縮成一個向量,解碼器網路將該向量展開成一個新的序列。
為了改進此模型,我們將使用 注意力機制,該機制允許解碼器學會關注輸入序列的特定範圍。
推薦閱讀
我假設您至少已安裝 PyTorch,瞭解 Python,並且理解張量。
https://pytorch.com.tw/ 獲取安裝說明
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 教程中使用的字元編碼類似,我們將每種語言中的每個單詞表示為一個獨熱向量,即一個除了一個 1(在單詞的索引處)之外全為零的巨大向量。與語言中可能存在的幾十個字元相比,單詞的數量要多得多,因此編碼向量也大得多。然而,我們將稍微偷點懶,將資料截斷,每種語言只使用幾千個單詞。
稍後,我們將需要每個單詞的唯一索引作為網路的輸入和目標。為了跟蹤所有這些,我們將使用一個名為 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 en conge cette semaine', 'i am on holiday this week']
Seq2Seq 模型#
迴圈神經網路(RNN)是一種在序列上執行並將其自身輸出用作後續步驟輸入的網路。
序列到序列網路,或稱 seq2seq 網路,或 編碼器-解碼器網路,是由兩個稱為編碼器和解碼器的 RNN 組成的模型。編碼器讀取輸入序列並輸出一個單一向量,解碼器讀取該向量以產生輸出序列。
與單個 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 解碼器中,我們僅使用編碼器的最後一次輸出。這個最後的輸出有時被稱為上下文向量,因為它編碼了整個序列的上下文。這個上下文向量用作解碼器的初始隱藏狀態。
在解碼的每一步,解碼器都接收一個輸入 token 和隱藏狀態。初始輸入 token 是開始字串 <SOS> token,第一個隱藏狀態是上下文向量(編碼器的最後隱藏狀態)。
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
我鼓勵您訓練並觀察此模型的結果,但為了節省空間,我們將直接進入重點,介紹注意力機制。
注意力解碼器#
如果只有上下文向量在編碼器和解碼器之間傳遞,那麼這個單一向量就承擔了編碼整個句子的重負。
注意力機制允許解碼器網路在解碼器自身輸出的每一步“關注”編碼器輸出的不同部分。首先,我們計算一組注意力權重。這些權重將乘以編碼器輸出向量,以建立加權組合。結果(在程式碼中稱為 attn_applied)應該包含關於輸入序列特定部分的資訊,從而幫助解碼器選擇正確的輸出單詞。
注意力權重的計算是透過另一個前饋層 attn 來完成的,該層使用解碼器的輸入和隱藏狀態作為輸入。由於訓練資料中存在各種長度的句子,為了實際建立和訓練這個層,我們必須選擇一個它可以適用的最大句子長度(輸入長度,用於編碼器輸出)。最大長度的句子將使用所有注意力權重,而較短的句子將僅使用前面的幾個。
Bahdanau 注意力,也稱為加性注意力,是序列到序列模型中常用的注意力機制,尤其是在神經機器翻譯任務中。它由 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 token。
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> token 作為其第一個輸入,並將編碼器的最後隱藏狀態作為其第一個隱藏狀態。
“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 token,我們就停止。我們還儲存解碼器的注意力輸出來供以後顯示。
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 分鐘後,我們將獲得一些不錯的結果。
注意
如果您執行此 notebook,您可以訓練、中斷核心、評估,並稍後繼續訓練。註釋掉初始化編碼器和解碼器的行,然後再次執行 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 32s (- 8m 8s) (5 6%) 1.5530
1m 4s (- 7m 34s) (10 12%) 0.6872
1m 37s (- 7m 0s) (15 18%) 0.3559
2m 9s (- 6m 28s) (20 25%) 0.1985
2m 41s (- 5m 55s) (25 31%) 0.1246
3m 13s (- 5m 22s) (30 37%) 0.0872
3m 44s (- 4m 48s) (35 43%) 0.0668
4m 16s (- 4m 16s) (40 50%) 0.0547
4m 47s (- 3m 43s) (45 56%) 0.0463
5m 18s (- 3m 11s) (50 62%) 0.0419
5m 50s (- 2m 39s) (55 68%) 0.0375
6m 21s (- 2m 7s) (60 75%) 0.0356
6m 53s (- 1m 35s) (65 81%) 0.0331
7m 24s (- 1m 3s) (70 87%) 0.0319
7m 56s (- 0m 31s) (75 93%) 0.0299
8m 28s (- 0m 0s) (80 100%) 0.0296
將 dropout 層設定為 eval 模式
encoder.eval()
decoder.eval()
evaluateRandomly(encoder, decoder)
> je vais reflechir a ca
= i m going to figure this out
< i m going to figure this out <EOS>
> j en ai marre de vous
= i m sick of you
< i m sick of you happy <EOS>
> c est un beau mec
= he s a hunk
< he s a hunk <EOS>
> vous avez parfaitement raison
= you re totally right
< you re absolutely right <EOS>
> tu es vieux
= you re old
< you re old enough <EOS>
> je suis desole d entendre ca
= i m sorry to hear it
< i m sorry to hear it <EOS>
> tu es malin
= you re clever
< you re clever <EOS>
> il est en train de jouer dans sa chambre
= he is playing in his room
< he is playing in his room <EOS>
> je ne suis pas le patron
= i m not the boss
< i m not the manager <EOS>
> je ne suis pas votre ami
= i m no friend of yours
< i m not your friend <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.
/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.
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.
/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.
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.
/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.
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.
/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.
練習#
嘗試使用不同的資料集
其他語言對
人類 → 機器(例如,物聯網命令)
聊天 → 回覆
問題 → 答案
將嵌入替換為預訓練的詞嵌入,例如
word2vec或GloVe嘗試使用更多層、更多隱藏單元和更多句子。比較訓練時間和結果。
如果您使用的是一對短語相同的翻譯檔案(
I am test \t I am test),則可以將其用作自編碼器。嘗試此操作:訓練為自編碼器
僅儲存編碼器網路
從此開始訓練一個新的解碼器進行翻譯
指令碼總執行時間: (8 分 37.025 秒)





