torch官网seq2seq教程翻译

前言

这是对torch官网seq2seq教程的翻译和笔记,记录下来方便以后查看。

正文

这是关于“从头开始处理NLP”的第三个也是最后一个教程,其中我们编写了自己的类和函数来预处理数据,以完成我们的NLP建模任务。我们希望在您完成本教程之后,您能在紧随本教程之后的三个教程中继续学习torchtext如何处理大部分的预处理。

在这个项目中,我们将教一个神经网络从法语翻译成英语。

[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 .

这是由简单但强大的序列到序列网络的思想实现的,两个递归神经网络一起工作,将一个序列转换为另一个序列。编码器网络将输入序列压缩成矢量,解码网络将矢量展开成新的序列。

在这个项目中,我们将教一个神经网络从法语翻译成英语。
在这里插入图片描述
为了改进这个模型,我们将使用一种注意机制,它让译码器学会在输入序列的特定范围内集中注意力。

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

这里有些其实没必要,比如第一行,另外本文没有if __name__ == '__main__':作为程序入口,因此代码还可能组织的更好。

Loading data files

这里主要是介绍数据,这对后面自己调整模型做其他任务有很大帮助,因为输入的格式也比较重要。

这个项目的数据是一套成千上万的英法翻译对。
Open Data Stack Exchange上的这个问题指引我打开翻译网站https://tatoeba.org/,可以在https://tatoeba.org/eng/downloads下载,更好的是,有人做了额外工作——将语言对分离进单个文本文件:https://www.manythings.org/anki/

英语到法语的对太大,无法包括在repo里,所以在继续之前先下载。该文件是一个以制表符分隔的翻译对列表:data/eng-fra.txt
I am cold. J'ai froid.

与字符级RNN教程中使用的字符编码类似,我们将把一种语言中的每个单词表示为独热编码,换种方式说是除单个1(在单词的索引处)之外的一个0的巨大向量。与一种语言中可能存在的几十个字符相比,其中的单词要多得多,因此编码向量要大得多。然而,我们将稍微作弊一下,将数据修剪为每种语言只使用几千个单词。
在这里插入图片描述
我们需要为每个单词建立一个唯一的索引,以便以后作为网络的输入和目标。为了跟踪所有这些,我们将使用一个助手类,它有word→index()和index→word()字典,以及用于以后替换稀有单词的每个单词的计数。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

为了读取数据文件,我们将文件分割成行,然后将行分割成对。所有的文件都是英语→其他语言,所以如果我们想从其他语言转换为英语,我添加了标志来反转对

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 am”或“He is”等形式的句子(考虑到之前替换的撇号)。

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
['j en suis contente .', 'i m happy with that .']

可以看到 pair 其实是一个list。

The Seq2Seq Model

递归神经网络(RNN)是一种对序列进行操作并将其自身的输出作为后续步骤的输入的网络。

序列到序列网络,或seq2seq网络,或编码器解码器网络,是由两个称为编码器和解码器的RNNs组成的模型。编码器读取输入序列并输出单个向量,译码器读取该向量以产生输出序列。
在这里插入图片描述
与单个RNN的序列预测不同,seq2seq模型将我们从序列长度和顺序中解放出来,这使得它非常适合在两种语言之间进行转换。

想想这句话“Je ne suis pas le chat noir”(我不是黑猫)。输入句中的大部分词直接翻译到输出句中,但顺序略有不同,如“chat noir”和“black cat”。由于“ne/pas”结构(法语结构),输入句中也多了一个单词。直接从输入的单词序列中产生正确的翻译是很困难的。

使用seq2seq模型,编码器创建一个单个向量,在理想情况下,它将输入序列的“含义”编码为单个向量——句子的某个N维空间中的一个点。

The Encoder

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)

The Decoder

解码器是另一个RNN,它接受编码器的输出向量并输出一系列单词来创建翻译

Simple Decoder

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)

我鼓励你训练并观察这个模型的结果,但为了节省空间,我们将直接走向金牌并引入注意机制。

Attention Decoder

如果只有上下文context向量在编码器和解码器之间传递,那么这个向量就承担了对整个句子进行编码的负担。

注意力允许解码器网络“聚焦”于编码器输出的不同部分,以处理解码器自己输出的每一步。首先,我们计算一组注意力权重。这些将与编码器输出向量相乘,以创建一个加权组合。结果(在代码中调用)应该包含有关输入序列的特定部分的信息,从而帮助解码器选择正确的输出单词.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)

Training

Preparing Training Data

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

Training the Model

为了训练,我们通过编码器运行输入语句,并跟踪每一个输出和最新的隐藏状态。然后将作为解码器的第一个输入,将编码器的最后一个隐藏状态作为其第一个隐藏状态。

“教师强迫”的概念是使用真正的目标输出作为下一个输入,而不是使用解码器的猜测作为下一个输入。使用教师强迫使其收敛更快,但当训练好的网络被利用时,可能会表现出不稳定性。

你可以观察到教师强迫网络的输出与连贯阅读语法但偏离正确的翻译——直觉它已经学会表征输出语法和一旦老师告诉它最初几个字可以理解含义,但却没有很好地学习了如何创建这个句子的翻译。

因为PyTorch的autograd给了我们自由,我们可以用一个简单的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 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

这是一个辅助函数,给定当前时间和进度%,用于打印经过的时间和估计剩余时间。

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

整个培训过程是这样的:

  • 启动一个计时器
  • 初始化优化器和标准
  • 创建一组训练对
  • 开始绘制空损失数组

然后多次调用,偶尔打印进度(示例的百分比、目前的时间、估计时间)和平均损失

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)

Plotting results

使用训练时保存的损失值数组matplotlib进行绘图。plot_loss

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)

Evaluation

评估基本上和训练是一样的,但是没有目标,所以我们只是在每一步把解码器的预测反馈给它自己。每当它预测到一个单词时,我们就把它添加到输出字符串中,如果它预测到了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('')

Training and Evaluating

有了所有这些辅助函数(看起来是额外的工作,但它使运行多个实验变得更容易),我们实际上可以初始化一个网络并开始训练。

记住,输入的句子是经过严格过滤的。对于这个小数据集,我们可以使用相对较小的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)

Visualizing Attention

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值