- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
前期准备
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_forcing 为True时,采用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的原始输入是一个语句开始标记,所以将它们直接分开实现起来更容易,逻辑上更清晰。

2万+

被折叠的 条评论
为什么被折叠?



