• Tutorials >
  • 从零开始的NLP:使用序列到序列网络和注意力进行翻译
Shortcuts

从零开始的NLP:使用序列到序列网络和注意力进行翻译

Created On: Mar 24, 2017 | Last Updated: Oct 21, 2024 | Last Verified: Nov 05, 2024

作者: 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 .

…成功的程度各不相同。

这得益于一个简单但强大的想法,即`序列到序列网络 <https://arxiv.org/abs/1409.3215>`__,其中两个循环神经网络协同工作,将一个序列转换为另一个序列。编码器网络将输入序列浓缩为一个向量,解码器网络再将该向量扩展为一个新的序列。

为了改善这个模型,我们将使用一个`注意力机制 <https://arxiv.org/abs/1409.0473>`__,这使解码器能够学习在输入序列的特定范围上集中。

推荐阅读:

我假设你至少安装了 PyTorch,熟悉 Python,理解张量:

了解有关序列到序列网络及其工作原理的内容也很有用:

您还会发现前面的教程 从头开始的 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教程中使用的字符编码,我们将使用单热向量(即一个巨大的零向量,除了单个以单词索引为索引的位置为一)来表示每种语言中的每个单词。与一个语言中的几十个字符相比,单词会更多,因此编码向量要大得多。不过我们会稍作取舍,只使用每种语言中的几千个单词。

为了在后续使用这些数据时作为网络的输入和目标,我们需要为每个单词分配一个唯一索引。为此我们将使用一个名为``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个单词(包括结束标点符号),并会过滤出翻译形式为“我是”或“他是”等句子的句子(考虑前面处理掉的撇号)。

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

Seq2Seq模型

循环神经网络(RNN)是一种根据序列操作并使用自身输出作为后续步骤输入的网络。

一个`序列到序列网络 <https://arxiv.org/abs/1409.3215>`__,又称为seq2seq网络或者`编码器解码器网络 <https://arxiv.org/pdf/1406.1078v3.pdf>`__,是一种由两个RNN组成的模型,分别称为编码器和解码器。编码器读取输入序列并输出一个向量,解码器读取该向量以生成输出序列。

与单一RNN进行的序列预测不同,在seq2seq模型中,每个输入对应一个输出,而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解码器中,我们只使用编码器的最后一个输出。这最后一个输出有时被称为*上下文向量*,因为它编码了整个序列的上下文信息。上下文向量用作解码器的初始隐层状态。

在解码的每一步中,解码器会接收一个输入标记和隐层状态。初始输入标记是“字符串开始``<SOS>``”标记,第一个隐层状态是上下文向量(编码器的最后一个隐层状态)。

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等人在其论文《通过联合学习对齐和翻译进行神经机器翻译》中提出(<https://arxiv.org/pdf/1409.0473.pdf>)。该注意机制采用一个学习的对齐模型来计算编码器和解码器隐藏状态之间的注意分数。它使用一个前馈神经网络来计算对齐分数。

然而,还有其他可选的注意机制,例如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

备注

还有一些其他形式的注意机制通过使用相对位置的方法来解决长度限制问题。阅读关于《基于注意力的神经机器翻译的有效方法》中描述的“局部注意”机制(<https://arxiv.org/abs/1508.04025>)。

训练网络

准备训练数据

为了训练,对于每一对数据,我们需要一个输入张量(输入句子中单词的索引)和一个目标张量(目标句子中单词的索引)。在创建这些向量时,我们会在两个序列后附加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)

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>``标记作为其第一个输入,并使用编码器的最后隐藏状态作为其第一个隐藏状态。

“教师强制”是一种使用真实目标输出作为每个下一输入的概念,而不是使用解码器的预测作为下一输入。使用教师强制能够加速收敛,但在`当使用训练后的网络时,可能会表现出不稳定性`(<http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.378.4095&rep=rep1&type=pdf>)。

你可以观察到教师强制网络的输出,其虽然具有连贯的语法,但可能远离正确的翻译——直观上,它已经学习如何表现输出语法,并“拾取”意义,一旦教师告诉他前几个词,但它并没有从一开始就正确地从翻译创建句子的能力。

由于PyTorch的自动微分功能赋予了我们的自由,我们可以使用一个简单的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标记,我们就在那里停止。同样,我们存储解码器的注意力输出以供稍后显示。

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分钟后,会得到一些不错的结果。

备注

如果你运行这个笔记本,你可以先训练,随后中断内核,评估结果,稍后继续训练。注释掉初始化编码器和解码器的代码行,并再次运行``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)

将dropout层设置为``eval``模式

encoder.eval()
decoder.eval()
evaluateRandomly(encoder, decoder)

可视化注意机制

注意机制的一个有用属性是其输出高度可解释。由于它被用于加权输入序列中特定的编码器输出,我们可以想象观察网络在每个时间步专注的地方。

你可以简单运行``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')

练习

  • 尝试使用不同的数据集

    • 另一种语言对

    • 人类 → 机器(例如,物联网命令)

    • 聊天 → 回复

    • 问题 → 答案

  • 用预训练的词嵌入(如``word2vec``或``GloVe``)替换嵌入

  • 尝试使用更多的层、更多的隐藏单元和更多的句子。比较训练时间和结果。

  • 如果你使用一个翻译文件,其中的对是两个相同的短语(I am test \t I am test),你可以将其作为一个自动编码器。试试这个:

    • 训练作为一个自动编码器

    • 只保存编码器网络

    • 从这里训练一个新的解码器用于翻译

**脚本的总运行时间:**(0分钟0.000秒)

通过Sphinx-Gallery生成的图集

文档

访问 PyTorch 的详细开发者文档

查看文档

教程

获取针对初学者和高级开发人员的深入教程

查看教程

资源

查找开发资源并获得问题的解答

查看资源