Pytorch官方教程:用Seq2Seq和注意力机制做翻译

NLP FROM SCRATCH: TRANSLATION WITH A SEQUENCE TO SEQUENCE NETWORK AND ATTENTION


原文: https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html

原文实现了一个简单但是有效的基于sequence2sequence的神经网络,来做英语与法语之间的翻译工作。sequence2sequence模型又两个循环神经网络RNN构成,一个把输入句子压缩成一个语义向量,另一个解压缩。

img

为了优化这个模型,我们引入注意力机制,让这个解码器能够注意到一段范围的输入。

推荐阅读

sequence to sequence:

Requirements

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

训练数据

https://download.pytorch.org/tutorial/data.zip

我们还是使用独热编码(one-hot)来表示单词,由于数据中单词数量庞大,导致独热编码过于巨大,我们偷一点懒,只是用其中的几千个单词。我们需要给每一个单词配一个索引,以方便我们找到它们。使用一个辅助类Lang,其中有word2indexindex2wordword2count,我们只会使用其中出现频率较高的单词。

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 characters转化为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

请注意上面正则表达式的使用。

把从文件中读入的数据按照行分开,每一行有分成法语和英语,分别添加单词。

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

    # Split every line into pairs and normalize
    pairs = [[normalizeString(s) for s in l.split('	')] 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 10599 sentence pairs
Counting words...
Counted words:
fra 4345
eng 2803
['il commence a se sentir desespere .', 'he s starting to feel desperate .']

Seq2Seq 模型

RNN是一个在序列上运行的神经网络模型,用自己的输出作为子序列的输入。

Seq2Seq模型,是由两个叫编码器和解码器的RNN组成的,编码器输入一个序列,得到一个向量,解码器用向量得到序列。

不同于用一个简单的RNN模型做句子预测那样每一个输入都对应于一个输出,Seq2Seq把我们从句子长度和顺序中解放了出来,更适合完成句子翻译工作。

比如考虑句子“Je ne suis pas le chat noir”到“I am not the black cat”的映射,虽然大多数单词都有直接到另一个与语言的意思,但是句子的顺序却不能直接从另一个句子翻译过来。

在理想情况下,我们把句子用RNN变成一个(N)维语义向量。

编码器 Encoder

编码器是一个RNN,每一个输入句子里的单词都会输出一个output state和hidden state,hidden state还会作用于下一个输入单词。

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)

Decoder 解码器

decoder是另一个RNN,输入为向量,输出为一个序列,以此来完成翻译。

简单解码器

在最基础版本的seq2seq模型中,我们只要最后一次编码器的输出。这个最后的输出我们称之为Context Vector,因为它是整个句子的输出,可以用作解码器的第一次hidden state。

每一步解码时,解码器都会被给一个input token和一个hidden state,第一个input token是<SOS>,第一个hidden state是Context Vector

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)

鼓励你自己去训练这个模型并看一看效果,为了节省空间我们进入下一部,基于注意力机制的解码器。

基于注意力机制的解码器

如果只用一个Context Vector作为输入,那么它携带的负担就太重了。

注意力让解码器能够在自身的每一步输出时都关注于编码器输出的不同部分。首先我们计算一些注意力权重,然后再乘上编码器输出向量产生一个权重组合,这个结果(在代码中称为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)

训练

准备训练数据

我们需要的是输入张量和输出张量对,用<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)

训练模型

训练时,我们用输入句子作为编码器的输入,跟踪每一步的output和hidden state,然后解码器用<SOS>作第一个输入token,Context Vector作第一个hidden state。

Teacher Forcing概念,下一个单词的输入不是用解码器自己的预测输出,而是用正确的目标单词。Teacher Forcing可以让模型快读收敛,但是过拟合的话结果也可能很不稳定。

你可以观察到,teacher-forced网络输出符合语法规则,但是和要翻译的句子相差甚远。直观感觉上看,它学会了如何表达我们的语法并且通过前面的单词预测后面的单词,但是它没学会如何创造一个合理的句子。

我们可以用一个简单的if语句来选择是否使用teacher-force,设置一个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

还有几个辅助函数,帮助你计算epoch百分比与消耗时间。

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

整个训练进程如下:

  • 开启一个计时器
  • 初始化优化器和损失函数
  • 制造训练数据
  • 开始画losses图像

然后我们会训练很多次,偶尔输出训练组数和loss。

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)

画出结果

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

评估

评估和训练几乎一样,只是这里我们没有target了,所以直接用它自己的输入作为input token,每次输出预测单词后我们就把新的单词放到答案的句子里,直到输出<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('')

训练与评估

有了这些辅助函数,我们就可以开始初始化模型并进行训练了。

考虑到我们的训练数据是经过大幅度的过滤后的,已经变得很小了,hidden state的长度我们只设置了256个节点,用了一层GRU,经过40分钟的MacBook上的CPU训练,我们可以得到如下的结果。

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)

输出:

1m 51s (- 26m 7s) (5000 6%) 2.8285
3m 40s (- 23m 50s) (10000 13%) 2.2807
5m 28s (- 21m 53s) (15000 20%) 1.9705
7m 17s (- 20m 2s) (20000 26%) 1.7514
9m 6s (- 18m 13s) (25000 33%) 1.5510
10m 55s (- 16m 23s) (30000 40%) 1.3943
12m 45s (- 14m 35s) (35000 46%) 1.2251
14m 34s (- 12m 45s) (40000 53%) 1.1375
16m 24s (- 10m 56s) (45000 60%) 1.0022
18m 13s (- 9m 6s) (50000 66%) 0.9624
20m 3s (- 7m 17s) (55000 73%) 0.8545
21m 55s (- 5m 28s) (60000 80%) 0.7849
23m 48s (- 3m 39s) (65000 86%) 0.6981
25m 37s (- 1m 49s) (70000 93%) 0.6476
27m 27s (- 0m 0s) (75000 100%) 0.6001

注意力可视化

注意力机制的最有用的特性之一就是十分具象化,因为它是为编码器的输出序列标注权重的,所以我们可以直到每一步的时候模型在关注句子的哪一部分。

直接运行plt.matshow(attentions)可以看到用矩阵表示的注意力机制,行是每一步输入,列是每一步输出。

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

为了达到更很好的观察效果,我们添加label,用单词来代替step。

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

输出:

input = elle a cinq ans de moins que moi .
output = she s five years younger than i am . <EOS>
input = elle est trop petit .
output = she is too loud . <EOS>
input = je ne crains pas de mourir .
output = i m not scared to die . <EOS>
input = c est un jeune directeur plein de talent .
output = he s a talented young player . <EOS>
一个人没有梦想,和咸鱼有什么区别!
原文地址:https://www.cnblogs.com/TABball/p/12727144.html