PyTorch 入门指南
学习 PyTorch
图像和视频
音频
后端
强化学习
在生产环境中部署 PyTorch 模型
Profiling PyTorch
代码变换与FX
前端API
扩展 PyTorch
模型优化
并行和分布式训练
边缘端的 ExecuTorch
推荐系统
多模态

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

作者: Sean Robertson

这是“从零开始的自然语言处理”系列教程的最后一部分,我们将编写自己的类和函数来预处理数据以进行自然语言处理建模任务。希望你在完成本教程后能够继续学习torchtext如何在接下来的三个教程中为你简化这些预处理工作。

在这个项目中,我们将训练一个神经网络,用于将法语翻译成英语。
[KEY:>input,=target,<output]

>ilestentraindepeindreuntableau.
=heispaintingapicture.
<heispaintingapicture.

>pourquoinepasessayercevindelicieux?
=whynottrythatdeliciouswine?
<whynottrythatdeliciouswine?

>ellenestpaspoetemaisromanciere.
=sheisnotapoetbutanovelist.
<shenotnotapoetbutanovelist.

>vousetestropmaigre.
=youretooskinny.
<youreallalone.

……在不同程度上取得不同的成果。

这是通过序列到序列(Sequence to Sequence)网络的简单而强大的理念实现的,在这种网络中,两个循环神经网络协同工作以将一个序列转换为另一个序列。编码器网络将输入序列压缩成一个向量,解码器网络则将该向量展开为一个新的序列。

为了改进这个模型,我们将采用一个注意力机制,使解码器能够在输入序列的特定范围内进行聚焦学习。

推荐阅读:

假设你已经安装了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教程中使用的字符编码,我们将把每个单词表示为一个one-hot向量,即除了某个位置是1以外全是0的大型向量(该位置对应于单词的索引)。与语言中存在的几十个字符相比,词汇量要大得多,因此编码向量也会相应地更大。不过我们这里会稍微变通一下,将数据限制在每种语言使用几千个词。

我们将为每个单词创建一个唯一的索引,以便在后续操作中用作网络的输入和目标。为了管理这些信息,我们将使用一个名为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))
Reading lines...
Read 135842 sentence pairs
Trimmed to 11445 sentence pairs
Counting words...
Counted words:
fra 4601
eng 2991
['tu preches une convaincue', 'you re preaching to the choir']

序列到序列模型

循环神经网络(RNN)是一种处理序列数据的网络,它将自身的输出用作后续步骤的输入。

序列到序列网络(seq2seq 网络)或编码器-解码器网络是由两个 RNN 组成的模型,即编码器和解码器。编码器读取输入序列并输出一个单一向量,而解码器则读取该向量以生成输出序列。

与单个 RNN 的序列预测不同(其中每个输入都对应一个输出),seq2seq 模型让我们摆脱了序列长度和顺序的限制,因此非常适合用于两种语言之间的翻译。

考虑句子Je ne suis pas le chat noirI am not the black cat。输入句子中的大多数单词在输出句子中都有直接对应的翻译,但顺序稍有不同,例如chat noirblack 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,它接收编码器输出的向量,并生成一系列单词来创建翻译。

简单解码器

在最简单的序列到序列解码器中,我们仅使用编码器的最后一个输出。这个输出有时被称为上下文向量,因为它包含了整个序列的上下文信息。该上下文向量被用作解码器的初始隐藏状态。

在解码的每一步,解码器都会收到一个输入令牌和隐藏状态。初始输入令牌为字符串开始 <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等人在其论文《通过联合学习对齐和翻译实现神经机器翻译》(Neural Machine Translation by Jointly Learning to Align and Translate)中提出。这种注意力机制采用经过训练的对齐模型来计算编码器和解码器隐藏状态之间的注意力分数,并利用前馈神经网络来计算对齐分数。

然而,还有其他的注意力机制可供选择,例如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令牌添加到两个序列的末尾。

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> 令牌作为第一个输入,并将编码器的最后一个隐藏状态用作其初始隐藏状态。

“Teacher forcing” 是指使用真实的目标输出作为每个下一个输入,而不是使用解码器的猜测。虽然这种方法可以使模型更快地收敛,但当训练好的网络被实际应用时,可能会表现出不稳定

你可以观察到教师强制网络虽然具有连贯的语法,但其输出与正确翻译相差甚远。直观来看,该网络学会了表示输出语法,并且一旦老师给出了前几个单词作为提示,它就能“理解”意思。然而,它并没有真正学会如何从翻译开始创建句子。

得益于 PyTorch 自动微分的功能,我们可以用一个简单的 if 语句来随机决定是否使用教师强制(teacher forcing)。通过增大 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层的小型网络。经过约40分钟的MacBook CPU运行后,我们将获得一些合理的结果。

如果你运行这个笔记本,可以进行模型训练、中断内核、评估模型,并在之后继续训练。注释掉初始化编码器和解码器的代码行,然后重新运行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)
  • seq2seq translation tutorial
  • seq2seq translation tutorial
Reading lines...
Read 135842 sentence pairs
Trimmed to 11445 sentence pairs
Counting words...
Counted words:
fra 4601
eng 2991
0m 31s (- 7m 54s) (5 6%) 1.5304
1m 2s (- 7m 20s) (10 12%) 0.6776
1m 34s (- 6m 48s) (15 18%) 0.3528
2m 5s (- 6m 15s) (20 25%) 0.1948
2m 35s (- 5m 42s) (25 31%) 0.1203
3m 6s (- 5m 10s) (30 37%) 0.0834
3m 36s (- 4m 38s) (35 43%) 0.0637
4m 6s (- 4m 6s) (40 50%) 0.0521
4m 37s (- 3m 35s) (45 56%) 0.0452
5m 7s (- 3m 4s) (50 62%) 0.0404
5m 38s (- 2m 33s) (55 68%) 0.0374
6m 8s (- 2m 2s) (60 75%) 0.0346
6m 38s (- 1m 32s) (65 81%) 0.0326
7m 9s (- 1m 1s) (70 87%) 0.0314
7m 39s (- 0m 30s) (75 93%) 0.0299
8m 9s (- 0m 0s) (80 100%) 0.0291

将 dropout 层设置为 eval 模式

encoder.eval()
decoder.eval()
evaluateRandomly(encoder, decoder)
> il est si mignon !
= he s so cute
< he s so cute <EOS>

> je vais me baigner
= i m going to take a bath
< i m going to take a bath <EOS>

> c est un travailleur du batiment
= he s a construction worker
< he s a construction worker <EOS>

> je suis representant de commerce pour notre societe
= i m a salesman for our company
< i m a salesman for our company <EOS>

> vous etes grande
= you re big
< you are big <EOS>

> tu n es pas normale
= you re not normal
< you re not normal <EOS>

> je n en ai pas encore fini avec vous
= i m not done with you yet
< i m not done with you yet <EOS>

> je suis desole pour ce malentendu
= i m sorry about my mistake
< i m sorry about my mistake <EOS>

> nous ne sommes pas impressionnes
= we re not impressed
< we re not impressed <EOS>

> tu as la confiance de tous
= you are trusted by every one of us
< you are trusted by every one of us <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')
  • seq2seq translation tutorial
  • seq2seq translation tutorial
  • seq2seq translation tutorial
  • seq2seq translation tutorial
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:823: 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:825: 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:823: 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:825: 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:823: 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:825: 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 guys <EOS>
/var/lib/workspace/intermediate_source/seq2seq_translation_tutorial.py:823: 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:825: UserWarning:

set_ticklabels() should only be used with a fixed number of ticks, i.e. after set_ticks() or using a FixedLocator.

练习

  • 尝试使用其他数据集

    • 另一种语言组合

    • 人类 → 机器(例如 IoT 指令)

    • 聊天 → 回复

    • 问题 → 答案

  • 用预训练的词嵌入(如 word2vecGloVe)替换现有嵌入

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

  • 如果你使用了一个翻译文件,其中成对的短语是相同的(I am test\tI am test),你可以将它用作自动编码器。试试看:
    • 将模型作为自编码器进行训练

    • 仅保存Encoder网络

    • 从那里训练一个新解码器进行翻译

本页目录