前言
本系列教程為pytorch官網文檔翻譯。本文對應官網地址:https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html
系列教程總目錄傳送門:我是一個傳送門
本系列教程對應的 jupyter notebook 可以在我的Github倉庫下載:
本教程我們將會搭建一個網絡來將法語翻譯成英語。
[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 network 簡單而又強大的 idea來實現,該實現包含兩個循環神經網絡,它們共同工作從而將一個序列轉化為另一個序列:編碼器網絡將輸入壓縮成矢量;解碼器網絡將該矢量展開成新的序列。
依賴包
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')
1. 加載數據文件
本教程的數據文件是幾千個英語到法語的翻譯句子對。
翻譯開源下載地址:http://www.manythings.org/anki/
點擊這里下載本教程所需的翻譯文件。
解壓到當前目錄下,得到一個 data/eng-fra.txt文件,該文件每一行是由 tab 分隔開的翻譯對:
I am cold. J'ai froid.
類似於字符級RNN編碼字母序列,我們仍然將源語言的每個單詞編碼為一個one-hot向量。與語言中可能存在的幾十個字符相比,詞語的量顯然更大,因此編碼向量要大得多。我們在這里做個小小的弊,修剪數據----每種語言我們只采用幾千個單詞。
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編碼的,我們需要簡單得將字符轉化為ASCII編碼,全部轉化為小寫字母,並修剪大部分標點符號。
# Turn a Unicode string to plain ASCII, thanks to
# http://stackoverflow.com/a/518232/2809427
def unicode2Ascii(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 = unicode2Ascii(s.lower().strip())
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z.!?]+", r" ", s)
return s
讀取數據,我們將文件分割成行,進一步分割成句子對。文件是 English\(\rightarrow\)其他語言 ,所以這里加上一個 reverse 參數,可以用來獲取 其他語言\(\rightarrow\)英語 的翻譯對。
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'm" 這種形式)。
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))
out:
Reading lines...
Read 135842 sentence pairs
Trimmed to 11893 sentence pairs
Counting words...
Counted words:
fra 4920
eng 3228
['tu es merveilleux .', 'you re wonderful .']
2. Seq2Seq 模型
循環神經網絡對一個序列操作,然后將其輸出作為下一個子操作的輸入。
一個 Sequence to Sequence,或者叫 seq2seq 網絡,又或者叫 編碼-解碼網絡,包含了兩個RNN部分:編碼器和解碼器。編碼器網絡將輸入序列轉化為單個向量,解碼器讀取這個向量,將其轉化為序列輸出。圖1 展示了這個結構。這里我們回顧下圖1:
與使用單個RNN的序列預測不同(單個RNN序列預測的每個輸入都對應一個輸出), seq2seq模型使得我們能從序列的長度和順序中解放出來,這使得其能夠成為兩種語言之間相互轉換的理想選擇。
考慮一個句子對:
Je ne suis pas le char noir I am not the black cat
輸入句子中很多單詞可以直接翻譯到對應的輸出句子中,但是可能會有細微的順序變動,比如 chat noir 和 black cat。此外由於ne/pas結構,輸入句子比輸出句子多一個單詞。直接通過翻譯輸入詞語的產生正確的翻譯句子是很困難的。
使用seq2seq模型,編碼器創建單個向量,在理想情況下,將輸入序列的“語義”編碼為單個向量---代表句子的某些N維空間中的單個點
2.1 編碼器
seq2seq網絡的編碼器是一個RNN,它通過閱讀輸入句子的每個單詞,來生成一些值。對每一個輸入單詞,編碼器輸出一個向量和一個隱藏狀態,並且使用這個隱藏狀態作為下一個單詞的輸入。
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)
2.2 解碼器
解碼器使用編碼器輸出的向量作為輸入,輸出一串單詞,從而完成翻譯。
簡單的解碼器
在最簡單的解碼器中我們僅僅使用編碼器最后一步的輸出作為輸入。這個最后一步的輸出有時候被稱為(上下文向量)context vector 因為它編碼了整個文本序列。這個上下文向量被用作解碼器的初始隱藏狀態。
在解碼的每一步,解碼器接受一個詞語和一個隱藏狀態。初始的輸入詞語是單詞開始標記<SOS>,初始隱藏狀態是上文提到的上下文向量。
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)
我鼓勵你訓練和觀察這個模型的結果,但為了節省空間,我們將"直搗黃龍"並引入注意機制。
注意力的解碼器
如果僅僅是在編碼器和解碼器之間傳遞上下文向量, 對單個向量來說,表達整個句子是很困難的。
注意力機制允許解碼器在解碼的每一步獲得一個關於原始句子的注意量(即是說,這一步的翻譯需要在原始句子的不同部分投入多少的注意力)。首先我們計算一個注意力權重的集合。這些權重將和編碼器的輸出向量相乘來獲得一個權重敏感的輸出。這個步驟的結果(在代碼里為attn_applied)應包含有關輸入序列特定部分的信息,從而幫助解碼器選擇正確的輸出字。
使用一個前饋層 attn 來計算注意力權重,它使用解碼器的輸入和隱藏狀態作為輸入。因為訓練數據中的句子長短不一,因此要創建和訓練這一層,就必須選擇最長的句子長度。最大長度的句子將使用所有注意力量,而較短的句子將僅使用前幾個。
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)
通過使用相對位置方法,還有其他形式的注意力可以解決長度限制問題。參考 Effective Approaches to Attention-based Neural Machine Translation
3. 訓練
3.1 准備訓練數據
對每個訓練樣本對,我們需要一個輸入張量(輸入句子中每個詞語在詞典中的位置)和目標張量(目標句子中每個詞語在詞典中的的位置)。在創建這些向量的同時,我們給兩個都句子都加上 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)
3.2 訓練模型
我們將句子輸入到編碼器網絡中,同時跟蹤其每一步的輸出和最后一步的隱藏狀態。然后解碼器網絡接受一個 <SOS> 作為第一步的輸入,編碼器最后一步的隱藏狀態作為其初始隱藏狀態。
這里有個選擇問題:關於解碼器的每一步,我們到底使用目標字母直接輸入,還是使用前一步的網絡預測結果作為輸入?
Teacher forcing 概念:使用真實目標輸出作為下一個輸入,而不是使用解碼器的預測作為下一個輸入。使用teacher forcing可以使網絡更快地收斂,但是當受過訓練的網絡被運用時,它可能表現出不穩定性。
你可以觀察下網絡的輸出,讀起來看似語法相關,但是實際上遠離正確的翻譯---直覺上網絡學到了如何表示輸出語法,並且一旦'Teacher'告訴它前面幾個單詞,它就會“提取”含義,但它還沒有正確地學習如何從翻譯中創建句子。
由於PyTorch的autograd為我們提供了自由度,我們可以隨意選擇使用teacher forcing或不使用通過簡單的if語句。將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 targer 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 teaching 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
下面是一個輔助函數,用於打印經過的時間和估計的剩余時間,通過給定的當前時間和進度%。
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 trainIters(encoder, decoder, n_iters, print_every=1000, plot_every=1000, 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)
3.3 可視化結果
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)
4. 評估
評估與訓練大致相同,但沒有目標,因此我們只需將解碼器的預測反饋給每個步驟。每次它預測一個單詞時我們都會將它添加到輸出字符串中,如果它預測了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]
我們可以從訓練集中評估隨機句子並打印輸入,目標和輸出以做出一些主觀質量判斷:
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('')
5. 訓練與評估
有了所有這些輔助函數(它看起來像是額外的工作,但它使得更容易運行多個實驗)我們實際上可以初始化網絡並開始訓練。
請記住,輸入句子被嚴重過濾。對於這個小數據集,我們可以使用256個隱藏節點和單個GRU層的相對較小的網絡。在MacBook CPU上大約40分鍾后,我們將得到一些合理的結果。
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)
out:
3m 53s (- 54m 26s) (5000 6%) 3.0454
7m 35s (- 49m 23s) (10000 13%) 2.4611
11m 4s (- 44m 16s) (15000 20%) 2.1786
14m 31s (- 39m 55s) (20000 26%) 1.8817
17m 59s (- 35m 59s) (25000 33%) 1.7361
21m 27s (- 32m 10s) (30000 40%) 1.5839
24m 53s (- 28m 26s) (35000 46%) 1.4429
28m 18s (- 24m 46s) (40000 53%) 1.2940
31m 45s (- 21m 10s) (45000 60%) 1.1935
35m 19s (- 17m 39s) (50000 66%) 1.1049
38m 52s (- 14m 8s) (55000 73%) 1.0309
42m 23s (- 10m 35s) (60000 80%) 0.9482
45m 54s (- 7m 3s) (65000 86%) 0.8536
49m 29s (- 3m 32s) (70000 93%) 0.8255
53m 15s (- 0m 0s) (75000 100%) 0.7671
evaluateRandomly(encoder1, attn_decoder1)
out:
> j y travaille encore .
= i m still working on it .
< i m still working on it . <EOS>
> je suis fatigue de toutes ces reflexions .
= i m tired of all this nagging .
< i am tired of all this room . <EOS>
> vous etes timide n est ce pas ?
= you re shy aren t you ?
< you re shy aren t you ? <EOS>
> je suis pret pour mon prochain defi .
= i m ready for my next challenge .
< i m ready for my own days . <EOS>
> il est tres fier de sa moto trafiquee .
= he s very proud of his custom motorcycle .
< he is very proud of his parents of success .
> vous etes responsable .
= you are to blame .
< you are early . <EOS>
> vous avez tout a fait raison .
= you re absolutely right .
< you are always right . <EOS>
> tu es l ainee .
= you re the oldest .
< you re the oldest . <EOS>
> tu veux juste paraitre diplomate .
= you re just being diplomatic .
< you re just being . . <EOS>
> vous n etes pas le bienvenu ici .
= you re not welcome here .
< you re not welcome here . <EOS>
4.1 可視化注意力
注意機制的一個很有用的特性是其高度可解釋的輸出。因為它用於對輸入序列的特定編碼器輸出進行加權,所以我們可以想象在每個時間步長看網絡最關注的位置。
你可以簡單地運行plt.matshow(attentions) 以將注意力輸出顯示為矩陣,其中列是輸入步驟,行是輸出步驟:
%matplotlib inline
output_words, attentions = evaluate(
encoder1, attn_decoder1, "je suis trop froid .")
plt.matshow(attentions.numpy())
out:

為了更好地展示結果,我們給軸添加上標簽
def showAttention(input_sentence, output_words, attentions):
# Set up figure with color bar
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 .")
out:
input = elle a cinq ans de moins que moi .
output = she s five years younger than me . <EOS>

