N9 - seq2seq翻译实战使用Pytorch实现

部署运行你感兴趣的模型镜像

前期准备

1. 创建语言类

定义两个常量SOS_token和EOS_token,分别表示序列的开始与结束,然后创建语言类方便对语料库进行操作。

  • word2index 将单词映射到索引
  • word2count 记录单词出现的次数
  • index2word 将索引映射到单词
  • n_words 单词数量,初始值为2,因为序列的开始和结束单词已经被添加
  • addSentence方法: 用于向语言类对象添加句子,它会调用addWord方法将句子中的每个单词添加到语言类的对象中。
  • addWord方法: 将单词添加到word2index,word2count,index2word字典中,然后对n_words进行更新。如果单词已经存在于word2index中,则会将word2count对应的计数器+1
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 

    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

2. 编写文本处理函数

import re
import unicodedata
# 使用unicodedata模块,通过Normalize方法将字符串s转换为unicode规范化形式NFD
# 使用条件过滤语句过滤掉了uncodedata.category(c) 为'Mn'的字符
# 剩下的字符通过join组成了一个新的字符串
def unicodeToAscii(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')

# 将字符串转小写,并去除首尾空格,随后字符串输入unicodeToAscii函数
# 通过正则表达式替换,将句子中的标点符号前添加一个空格
# 将非字母替换为空格
# 最后返回处理后的字符串s
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

3. 文件读取函数

def readLangs(lang1, lang2, reverse=False):
	print('Reading lines...')
	# 以行为单位读取文件
	lines = open('data/%s-%s.txt' %(lang1, lang2), encoding='utf-8').read().strip().split('\n')
	# 每行放入一个列表中
	# 一个列表中有两个元素,lang1语言文本和lang2语言文本
	pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
	# 创建lang实例
	if reverse:
		pairs = [list(reversed(p)) for p in pairs]
		input_lang = Lang(long2)
		output_lang = Lang(lang1)
	else:
		input_lang = Lang(lang1)
		output_lang = Lang(lang2)
	return input_log, output_lang, pairs

读取 名称为lang1-lang2.txt的文件,然后将文本按行拆分。

编写过滤函数

MAX_LENGTH = 10
eng_prefix = (
    "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):
	# 只过滤留下长度不超MAX_LENGTH并且以eng_prefix中的元素开关的语料
	return [pair for pair in pairs if filterPair(pair)]

将Pairs过滤完,添加到lang对象中

import random
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模型

接下来就要用到pytorch了,先创建一个全局的设备对象

import torch
import torch.nn as nn
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

编码器

编码器用来将文本转换为向量

class EncoderRNN(nn.Module):
    def __init__(self, input_size, hidden_size):
        super().__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, inputs, hidden):
        embedded = self.embeddding(inputs).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)

解码器

用来将向量转译为文本

import torch.nn.functional as F
class DecoderRNN(nn.Module):
    def __init__(self, hidden_size, output_size):
        super().__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.Softmax(dim=1)

    def forward(self, inputs, hidden):
        output = self.embedding(inputs).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)

训练

数据预处理

# 将文本数字化为词汇的Index
def indexesFromSentence(lang, sentence):
    return [lang.word2index[word] for word in sentence.split(' ')]

# 将数字化的文本转换为tensor
def tensorFromSentence(lang, sentence):
    indexes = indexesFromSentence(lang, sentence)
    indexes.append(EOS_token)
    return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)

# 输入Pair文本,输出预处理好的数据
def tensorsFromPair(pair):
    input_tensor = tensorFromSentence(input_lang, pair[0])
    target_tensor = tensorFromSentence(output_lang, pair[1])
    return (input_tensor, target_tensor)

编写训练函数

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()
    # grad归零
    encoder_optimizer.zero_grad()
    decoder_optimizer.zero_grad()

    input_length = input_tensor.size(0)
    target_length = target_tensor.size(0)

    # 用于创建一个指定大小的全零张量tensor, 用作默认的编码器输出
    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:
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden)

            loss += criterion(decoder_output, target_tensor[di])
            decoder_output = target_tensor[di]
    else:
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input, decoder_hidden)
            
            topv, topi = decoder_output.topk(1)
            decoder_input = topi.squeeze().detach()

            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

序列生成任务中,解码器(decoder)的输入通常是由解码器自己生成的预测结果,即前一个时间步的输出。但是这种自回归的方式可能存在一个问题,即在训练过程中,解码器可能会产生累积误差,并导致输出与目标序列逐渐偏离。

为了解决这个问题,引入了一种称为"Teacher Forcing"的技术。在训练过程中,Teacher Forcing将目标序列的真实值作为解码器的输入,而不是使用解码器自己的预测结果。这样可以提供更准确的指导信号,帮助解码器更快地学习到正确的输出。

在上面的代码中,use_teacher_forcingTrue时,采用teacher_forcing策略,当为False时,不采用teacher_forcing策略。

关于Teacher Forcing: 在每个时间步(di循环中),解码器的输入都是目标序列的真实标签。这样做的好处是,解码器可以直接获得正确的输入信息,加快训练速度,并且在训练早期提供更准确的梯度信号,帮助解码器更好地学习。然而过度依赖目标序列可能会导致模型过于敏感,一旦目标序列中出现错误,可能会在解码器中产生累积的误差。不使用TeacherForcing的策略下,在每个时间步,解码器的输入是前一个时间步的预测输出。解码器需要依靠自身的预测能力来生成下一个输入,从而更好地适应真实应用场景中可能出现的输入变化。这种策略可以提高模型的稳定性,但可能会导致训练过程更加困难,特别是初始阶段。

总结来说,TeacherForcing在训练过程中可以帮助模型快速收敛,而Without TeacherForcing则更接近真实的应用场景。通过使用一定比例的TeacherForcing然后在训练的过程中逐渐减小这个比例,以便模型逐渐过渡到更自主的生成模式。

部分代码解释:

  • topv, topi = decoder_output.topk(1) 使用topk(1)函数从decoder_output中获取最大的元素及其对应的索引。
  • decoder_input = topi.squeeze().detach() 对topi做处理,以便作为下一个解码器的输入。squeeze()函数是为了去除张量中维度为1的维度,将topi进行压缩。然后detach()函数是为了将张量从计算图中分离出来,在后续的计算中不会对该张量进行梯度计算。最后将处理后的张量赋值给decoder_input,作为下一个解码器的输入。

编写计时函数

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

训练的迭代函数

from torch import optim

def trainIters(encoder, decoder, n_iters, print_every=100, plot_every=100, learning_rate=0.01):
    start = time.time()
    plot_losses = []
    print_loss_total = 0
    plot_loss_total = 0

    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 it in range(1, n_iters + 1):
        training_pair = training_pairs[it - 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 it % print_every == 0:
            print_loss_avg = print_loss_total / print_every
            print_loss_total = 0
            print('%s (%d %d%%) %.4f' % (timeSince(start, it / n_iters), 
                                         it, it / n_iters * 100, print_loss_avg))

        if it % plot_every == 0:
            plot_loss_avg = plot_loss_total / plot_every
            plot_losses.append(plot_loss_avg)
            plot_loss_total = 0
    return plot_losses

执行训练与评估

创建模型实例

hidden_size = 256
encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
decoder = DecoderRNN(hidden_size, output_lang.n_words).to(device)

plot_losses = trainIters(encoder, decoder, 20000, print_every=5000)

训练过程日志打印

可视化过程的损失

import matplotlib.pyplot as plt
import warnings
# 忽略警告
warnings.filterwarnings('ignore')

# 正常显示正负号
plt.rcParams['axes.unicode_minus'] = False
# 分辨率
plt.rcParams['figure.dpi'] = 100

epochs_range = range(len(plot_losses))

plt.figure(figsize=(8, 3))
plt.subplot(1, 1, 1)
plt.plot(epochs_range, plot_losses, label='Training Loss')
plt.legend(loc='upper right')
plt.title('Traning Loss')
plt.show()

可视化训练过程

心得体会

通过本次seq2seq的实验,我发现其实大部分任务的核心模型代码都比较少,更多的业务逻辑都是在整理数据。如何将数据转换为模型能够处理的格式,是把模型应用到实际任务中最重要的一个部分。

本节中的Encoder和Decoder并没有创建一个模型, 而是分别创建了两个模型对象。直观上打破了我对模型的一些印象,由于RNN模型是迭代的,并且Encoder的原始输入是数字化后的文本,Decoder的原始输入是一个语句开始标记,所以将它们直接分开实现起来更容易,逻辑上更清晰。

您可能感兴趣的与本文相关的镜像

PyTorch 2.8

PyTorch 2.8

PyTorch
Cuda

PyTorch 是一个开源的 Python 机器学习库,基于 Torch 库,底层由 C++ 实现,应用于人工智能领域,如计算机视觉和自然语言处理

### 使用 PyTorch 实现 Seq2Seq 翻译模型 #### 准备环境与数据集 为了构建一个有效的翻译模型,首先需要准备好必要的开发环境以及用于训练的数据集。这通常涉及到安装特定版本的PyTorch和其他依赖库,并下载并预处理目标语料库。 对于本案例中的英汉互译任务而言,加载预先定义好的映射表`en2id`和`zh2id`是非常重要的一步[^2]。这些字典帮助将单词转换成索引形式以便于神经网络处理。 #### 构建编码器 (Encoder) ```python import torch.nn as nn class Encoder(nn.Module): def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout): super().__init__() self.embedding = nn.Embedding(input_dim, emb_dim) self.rnn = nn.LSTM(emb_dim, hid_dim, num_layers=n_layers, bidirectional=True, batch_first=True) self.fc_out = nn.Linear(hid_dim * 2, hid_dim) # Bidirectional LSTM outputs are concatenated def forward(self, src): embedded = self.embedding(src) output, (hidden, cell) = self.rnn(embedded) hidden = torch.tanh(self.fc_out(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1))) return hidden, cell ``` 此部分实现了编码器的功能,它接收源语言句子作为输入并通过多层双向LSTM获取上下文信息。最终状态被传递给解码器以启动生成过程[^1]。 #### 设计带有注意力机制的解码器 (Attention Decoder) ```python class AttentionDecoder(nn.Module): def __init__(self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout, attention): super().__init__() self.attention = attention self.embedding = nn.Embedding(output_dim, emb_dim) self.rnn = nn.GRU(enc_hid_dim*2 + emb_dim, dec_hid_dim, batch_first=True) self.fc_out = nn.Linear(dec_hid_dim, output_dim) def forward(self, trg, encoder_outputs, hidden): attn_weights = self.attention(hidden.unsqueeze(0), encoder_outputs).unsqueeze(1) context_vector = torch.bmm(attn_weights, encoder_outputs) embedding_output = self.embedding(trg).unsqueeze(1) rnn_input = torch.cat([embedding_output, context_vector], dim=-1) output, hidden = self.rnn(rnn_input, hidden.unsqueeze(0)) prediction = self.fc_out(output.squeeze(1)) return prediction, hidden.squeeze(0), attn_weights ``` 这里引入了注意力机制来增强模型的表现力,在每一步解码过程中动态调整对不同位置的关注度,从而更好地捕捉长距离依赖关系[^4]。 #### 定义完整的Seq2Seq框架 ```python class Seq2Seq(nn.Module): def __init__(self, encoder, decoder, device): super().__init__() self.encoder = encoder self.decoder = decoder self.device = device def forward(self, src, trg, teacher_forcing_ratio=0.5): max_len = trg.shape[1] batch_size = trg.shape[0] vocab_size = self.decoder.output_dim outputs = torch.zeros(max_len, batch_size, vocab_size).to(self.device) encoder_hidden, encoder_cell = self.encoder(src) decoder_hidden = encoder_hidden.to(self.device) decoder_input = trg[:, 0].unsqueeze(-1).to(self.device) for t in range(1, max_len): output, decoder_hidden, _ = self.decoder( decoder_input, encoder_hidden.permute(1, 0, 2), decoder_hidden ) outputs[t] = output top1 = output.argmax(1) teacher_force = random.random() < teacher_forcing_ratio decoder_input = trg[:, t] if teacher_force else top1 return outputs ``` 上述代码片段展示了如何组合编码器和带注意力建模的解码器形成完整的Seq2Seq体系结构。通过迭代地应用教师强制策略(teacher forcing),可以在一定程度上加速收敛速度并提高性能表现[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值