PyTorch NLP From Scratch: 基于注意力機(jī)制的 seq2seq 神經(jīng)網(wǎng)絡(luò)翻譯

2020-09-11 10:28 更新
原文: https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html

作者: Sean Robertson

這是關(guān)于“從頭開始進(jìn)行 NLP”的第三篇也是最后一篇教程,我們?cè)谄渲芯帉懽约旱念惡秃瘮?shù)來預(yù)處理數(shù)據(jù)以完成 NLP 建模任務(wù)。 我們希望在完成本教程后,您將繼續(xù)學(xué)習(xí)緊接著本教程的三本教程, <cite>torchtext</cite> 如何為您處理許多此類預(yù)處理。

在這個(gè)項(xiàng)目中,我們將教授將法語翻譯成英語的神經(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ò)的簡(jiǎn)單但強(qiáng)大的構(gòu)想,使這成為可能,在該網(wǎng)絡(luò)中,兩個(gè)循環(huán)神經(jīng)網(wǎng)絡(luò)協(xié)同工作,將一個(gè)序列轉(zhuǎn)換為另一個(gè)序列。 編碼器網(wǎng)絡(luò)將輸入序列壓縮為一個(gè)向量,而解碼器網(wǎng)絡(luò)將該向量展開為一個(gè)新序列。

為了改進(jìn)此模型,我們將使用注意機(jī)制,該機(jī)制可讓解碼器學(xué)習(xí)將注意力集中在輸入序列的特定范圍內(nèi)。

推薦讀物:

我假設(shè)您至少已經(jīng)安裝了 PyTorch,了解 Python 和了解 Tensors:

  • https://pytorch.org/ 有關(guān)安裝說明
  • 使用 PyTorch 進(jìn)行深度學(xué)習(xí):60 分鐘的閃電戰(zhàn)通常開始使用 PyTorch
  • 使用示例學(xué)習(xí) PyTorch 進(jìn)行廣泛而深入的概述
  • PyTorch(以前的 Torch 用戶)(如果您以前是 Lua Torch 用戶)

了解序列到序列網(wǎng)絡(luò)及其工作方式也將很有用:

您還將找到先前的 NLP 從零開始:使用字符級(jí) RNN 對(duì)名稱進(jìn)行分類的教程,以及 NLP 從零開始:使用字符級(jí) RNN 生成名稱的指南,因?yàn)檫@些概念是有用的 分別與編碼器和解碼器模型非常相似。

有關(guān)更多信息,請(qǐng)閱讀介紹以下主題的論文:

要求

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ù)文件

該項(xiàng)目的數(shù)據(jù)是成千上萬的英語到法語翻譯對(duì)的集合。

開放數(shù)據(jù)堆棧交換上的這個(gè)問題使我指向開放翻譯站點(diǎn) https://tatoeba.org/ ,該站點(diǎn)可從  https://tatoeba.org/下載。 eng / downloads -更好的是,有人在這里做了額外的工作,將語言對(duì)拆分為單獨(dú)的文本文件: https://www.manythings.org/anki/

英文對(duì)法文對(duì)太大,無法包含在倉庫中,因此請(qǐng)先下載到data/eng-fra.txt,然后再繼續(xù)。 該文件是制表符分隔的翻譯對(duì)列表:

I am cold.    J'ai froid.

注意:

從的下載數(shù)據(jù),并將其提取到當(dāng)前目錄。

與字符級(jí) RNN 教程中使用的字符編碼類似,我們將一種語言中的每個(gè)單詞表示為一個(gè)單向矢量,或者零外的一個(gè)巨大矢量(除了單個(gè)索引(在單詞的索引處))。 與一種語言中可能存在的數(shù)十個(gè)字符相比,單詞有很多,因此編碼向量要大得多。 但是,我們將作弊并整理數(shù)據(jù)以使每種語言僅使用幾千個(gè)單詞。

我們需要每個(gè)單詞一個(gè)唯一的索引,以便以后用作網(wǎng)絡(luò)的輸入和目標(biāo)。 為了跟蹤所有這些信息,我們將使用一個(gè)名為Lang的幫助程序類,該類具有單詞→索引(word2index)和索引→單詞(index2word)字典,以及每個(gè)要使用的單詞word2count的計(jì)數(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,為簡(jiǎn)化起見,我們將 Unicode 字符轉(zhuǎn)換為 ASCII,將所有內(nèi)容都轉(zhuǎn)換為小寫,并修剪大多數(shù)標(biāo)點(diǎn)符號(hào)。

# 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ù)文件,我們將文件分成幾行,然后將行分成兩對(duì)。 這些文件都是英語→其他語言的,因此,如果我們要從其他語言→英語進(jìn)行翻譯,我添加了reverse標(biāo)志來反轉(zhuǎn)對(duì)。

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ù)量很多,并且我們想快速訓(xùn)練一些東西,因此我們將數(shù)據(jù)集修剪為僅相對(duì)較短和簡(jiǎn)單的句子。 在這里,最大長(zhǎng)度為 10 個(gè)字(包括結(jié)尾的標(biāo)點(diǎn)符號(hào)),并且我們正在過濾翻譯成“我是”或“他是”等形式的句子(考慮到前面已替換掉撇號(hào)的情況)。

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)]

準(zhǔn)備數(shù)據(jù)的完整過程是:

  • 讀取文本文件并拆分為行,將行拆分為成對(duì)
  • 規(guī)范文本,按長(zhǎng)度和內(nèi)容過濾
  • 成對(duì)建立句子中的單詞列表
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 .']

Seq2Seq 模型

遞歸神經(jīng)網(wǎng)絡(luò)(RNN)是在序列上運(yùn)行并將其自身的輸出用作后續(xù)步驟的輸入的網(wǎng)絡(luò)。

序列到序列網(wǎng)絡(luò)或 seq2seq 網(wǎng)絡(luò)或編碼器解碼器網(wǎng)絡(luò)是由兩個(gè)稱為編碼器和解碼器的 RNN 組成的模型。 編碼器讀取輸入序列并輸出單個(gè)向量,而解碼器讀取該向量以產(chǎn)生輸出序列。

與使用單個(gè) RNN 進(jìn)行序列預(yù)測(cè)(每個(gè)輸入對(duì)應(yīng)一個(gè)輸出)不同,seq2seq 模型使我們擺脫了序列長(zhǎng)度和順序的限制,這使其非常適合在兩種語言之間進(jìn)行翻譯。

考慮一下句子“ Je ne suis pas le chat noir”→“我不是黑貓”。 輸入句子中的大多數(shù)單詞在輸出句子中具有直接翻譯,但是順序略有不同,例如 “黑貓聊天”和“黑貓”。 由于采用“ ne / pas”結(jié)構(gòu),因此在輸入句子中還有一個(gè)單詞。 直接從輸入單詞的序列中產(chǎn)生正確的翻譯將是困難的。

使用 seq2seq 模型,編碼器創(chuàng)建單個(gè)矢量,在理想情況下,該矢量將輸入序列的“含義”編碼為單個(gè)矢量-句子的某些 N 維空間中的單個(gè)點(diǎn)。

編碼器

seq2seq 網(wǎng)絡(luò)的編碼器是 RNN,它為輸入句子中的每個(gè)單詞輸出一些值。 對(duì)于每個(gè)輸入字,編碼器輸出一個(gè)向量和一個(gè)隱藏狀態(tài),并將隱藏狀態(tài)用于下一個(gè)輸入字。

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)

解碼器

解碼器是另一個(gè) RNN,它采用編碼器輸出矢量并輸出單詞序列來創(chuàng)建翻譯。

簡(jiǎn)單解碼器

在最簡(jiǎn)單的 seq2seq 解碼器中,我們僅使用編碼器的最后一個(gè)輸出。 最后的輸出有時(shí)稱為上下文向量,因?yàn)樗鼘?duì)整個(gè)序列的上下文進(jìn)行編碼。 該上下文向量用作解碼器的初始隱藏狀態(tài)。

在解碼的每個(gè)步驟中,為解碼器提供輸入令牌和隱藏狀態(tài)。 初始輸入令牌是字符串開始&lt;SOS&gt;令牌,第一個(gè)隱藏狀態(tài)是上下文向量(編碼器的最后一個(gè)隱藏狀態(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)

我鼓勵(lì)您訓(xùn)練并觀察該模型的結(jié)果,但是為了節(jié)省空間,我們將直接努力,并引入注意機(jī)制。

注意解碼器

如果僅上下文向量在編碼器和解碼器之間傳遞,則該單個(gè)向量承擔(dān)對(duì)整個(gè)句子進(jìn)行編碼的負(fù)擔(dān)。

注意使解碼器網(wǎng)絡(luò)可以針對(duì)解碼器自身輸出的每一步,“專注”于編碼器輸出的不同部分。 首先,我們計(jì)算一組注意權(quán)重。 將這些與編碼器輸出向量相乘以創(chuàng)建加權(quán)組合。 結(jié)果(在代碼中稱為attn_applied)應(yīng)包含有關(guān)輸入序列特定部分的信息,從而幫助解碼器選擇正確的輸出字。

計(jì)算注意力權(quán)重的方法是使用另一個(gè)前饋層attn,并使用解碼器的輸入和隱藏狀態(tài)作為輸入。 由于訓(xùn)練數(shù)據(jù)中包含各種大小的句子,因此要實(shí)際創(chuàng)建和訓(xùn)練該層,我們必須選擇可以應(yīng)用的最大句子長(zhǎng)度(輸入長(zhǎng)度??,用于編碼器輸出)。 最大長(zhǎng)度的句子將使用所有注意權(quán)重,而較短的句子將僅使用前幾個(gè)。

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)

注意;

還有其他形式的注意力可以通過使用相對(duì)位置方法來解決長(zhǎng)度限制問題。 閱讀基于注意力的神經(jīng)機(jī)器翻譯的有效方法中的“本地注意力”信息。

訓(xùn)練

準(zhǔn)備訓(xùn)練數(shù)據(jù)

為了訓(xùn)練,對(duì)于每一對(duì),我們將需要一個(gè)輸入張量(輸入句子中單詞的索引)和目標(biāo)張量(目標(biāo)句子中單詞的索引)。 創(chuàng)建這些向量時(shí),我們會(huì)將 EOS 令牌附加到兩個(gè)序列上。

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)

訓(xùn)練模型

為了進(jìn)行訓(xùn)練,我們通過編碼器運(yùn)行輸入語句,并跟蹤每個(gè)輸出和最新的隱藏狀態(tài)。 然后,為解碼器提供&lt;SOS&gt;令牌作為其第一個(gè)輸入,并將編碼器的最后一個(gè)隱藏狀態(tài)作為其第一個(gè)隱藏狀態(tài)。

“教師強(qiáng)制”的概念是使用實(shí)際目標(biāo)輸出作為每個(gè)下一個(gè)輸入,而不是使用解碼器的猜測(cè)作為下一個(gè)輸入。 使用教師強(qiáng)制會(huì)導(dǎo)致其收斂更快,但是當(dāng)使用受過訓(xùn)練的網(wǎng)絡(luò)時(shí),可能會(huì)顯示不穩(wěn)定。

您可以觀察到以教師為主導(dǎo)的網(wǎng)絡(luò)的輸出,這些輸出閱讀的是連貫的語法,但卻偏離了正確的翻譯-直觀地,它學(xué)會(huì)了代表輸出語法,并且一旦老師說了最初的幾個(gè)單詞就可以“理解”含義,但是 首先,它還沒有正確地學(xué)習(xí)如何從翻譯中創(chuàng)建句子。

由于 PyTorch 的 autograd 具有給我們的自由,我們可以通過簡(jiǎn)單的 if 語句隨意選擇是否使用教師強(qiáng)迫。 調(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

這是一個(gè)幫助功能,用于在給定當(dāng)前時(shí)間和進(jìn)度%的情況下打印經(jīng)過的時(shí)間和估計(jì)的剩余時(shí)間。

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))

整個(gè)訓(xùn)練過程如下所示:

  • 啟動(dòng)計(jì)時(shí)器
  • 初始化優(yōu)化器和標(biāo)準(zhǔn)
  • 創(chuàng)建一組訓(xùn)練對(duì)
  • 啟動(dòng)空損耗陣列進(jìn)行繪圖

然后我們多次調(diào)用train,并偶爾打印進(jìn)度(示例的百分比,到目前為止的時(shí)間,估計(jì)的時(shí)間)和平均損失。

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)

繪圖結(jié)果

使用訓(xùn)練時(shí)保存的損失值數(shù)組plot_losses,使用 matplotlib 進(jìn)行繪制。

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)

評(píng)價(jià)

評(píng)估與訓(xùn)練基本相同,但是沒有目標(biāo),因此我們只需將解碼器的預(yù)測(cè)反饋給每一步。 每當(dāng)它預(yù)測(cè)一個(gè)單詞時(shí),我們都會(huì)將其添加到輸出字符串中,如果它預(yù)測(cè)到 EOS 令牌,我們將在此處停止。 我們還將存儲(chǔ)解碼器的注意輸出,以供以后顯示。

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]

我們可以從訓(xùn)練集中評(píng)估隨機(jī)句子,并打印出輸入,目標(biāo)和輸出以做出一些主觀的質(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('')

訓(xùn)練與評(píng)估

有了所有這些幫助器功能(看起來像是額外的工作,但它使運(yùn)行多個(gè)實(shí)驗(yàn)更加容易),我們實(shí)際上可以初始化網(wǎng)絡(luò)并開始訓(xùn)練。

請(qǐng)記住,輸入句子已被嚴(yán)格過濾。 對(duì)于這個(gè)小的數(shù)據(jù)集,我們可以使用具有 256 個(gè)隱藏節(jié)點(diǎn)和單個(gè) GRU 層的相對(duì)較小的網(wǎng)絡(luò)。 在 MacBook CPU 上運(yùn)行約 40 分鐘后,我們將獲得一些合理的結(jié)果。

注意:

如果運(yùn)行此筆記本,則可以進(jìn)行訓(xùn)練,中斷內(nèi)核,評(píng)估并在以后繼續(xù)進(jìn)行訓(xùn)練。 注釋掉編碼器和解碼器已初始化的行,然后再次運(yùn)行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)
  • ../_images/sphx_glr_seq2seq_translation_tutorial_002.png

得出:

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>

可視化注意力

注意機(jī)制的一個(gè)有用特性是其高度可解釋的輸出。 因?yàn)樗糜诩訖?quán)輸入序列的特定編碼器輸出,所以我們可以想象一下在每個(gè)時(shí)間步長(zhǎng)上網(wǎng)絡(luò)最關(guān)注的位置。

您可以簡(jiǎn)單地運(yùn)行plt.matshow(attentions)以將注意力輸出顯示為矩陣,其中列為輸入步驟,行為輸出步驟:

output_words, attentions = evaluate(
    encoder1, attn_decoder1, "je suis trop froid .")
plt.matshow(attentions.numpy())

../_images/sphx_glr_seq2seq_translation_tutorial_003.png

為了獲得更好的觀看體驗(yàn),我們將做一些額外的工作來添加軸和標(biāo)簽:

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 .")
  • ../_images/sphx_glr_seq2seq_translation_tutorial_004.png
  • ../_images/sphx_glr_seq2seq_translation_tutorial_005.png
  • ../_images/sphx_glr_seq2seq_translation_tutorial_006.png
  • ../_images/sphx_glr_seq2seq_translation_tutorial_007.png

得出:

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>

練習(xí)題

  • 嘗試使用其他數(shù)據(jù)集另一對(duì)語言人機(jī)→機(jī)器(例如 IOT 命令)聊天→回復(fù)問題→答案
  • 用預(yù)先訓(xùn)練的單詞嵌入(例如 word2vec 或 GloVe)替換嵌入
  • 嘗試使用更多層,更多隱藏單元和更多句子。 比較訓(xùn)練時(shí)間和結(jié)果。
  • 如果您使用的翻原文件中,對(duì)具有兩個(gè)相同的詞組(I am test \t I am test),則可以將其用作自動(dòng)編碼器。 嘗試這個(gè):訓(xùn)練為自動(dòng)編碼器僅保存編碼器網(wǎng)絡(luò)從那里訓(xùn)練新的解碼器進(jìn)行翻譯

腳本的總運(yùn)行時(shí)間:(27 分鐘 45.966 秒)

Download Python source code: seq2seq_translation_tutorial.py Download Jupyter notebook: seq2seq_translation_tutorial.ipynb

由獅身人面像畫廊生成的畫廊


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)