注意
跳转至页面底部 下载完整示例代码。
NLP 从零开始:使用字符级 RNN 生成姓名#
创建于:2017 年 3 月 24 日 | 最后更新:2024 年 10 月 21 日 | 最后验证:2024 年 11 月 5 日
作者: Sean Robertson
本教程是三部曲系列的一部分
这是我们“NLP 从零开始”系列三篇教程中的第二篇。在第一篇教程中,我们使用 RNN 将姓名分类为它们的原始语言。这次我们将反其道而行之,根据语言生成姓名。
> python sample.py Russian RUS
Rovakov
Uantov
Shavakov
> python sample.py German GER
Gerren
Ereng
Rosher
> python sample.py Spanish SPA
Salla
Parer
Allan
> python sample.py Chinese CHI
Chan
Hang
Iun
我们仍然手工构建一个包含少量线性层的简单 RNN。最大的不同在于,我们不再是在读取完姓名的所有字母后预测类别,而是输入一个类别,然后一次输出一个字母。循环预测字符以构成语言(这也适用于单词或其他更高级的结构)通常被称为“语言模型”。
推荐阅读
我假设你至少已经安装了 PyTorch,熟悉 Python,并理解张量(Tensors)的概念。
https://pytorch.ac.cn/ 获取安装说明
PyTorch 深度学习:60 分钟闪电战,用于快速入门 PyTorch。
通过实例学习PyTorch,进行广泛而深入的概览
为前Torch用户准备的PyTorch教程,如果您是前Lua Torch用户
了解 RNN 及其工作原理也会有所帮助。
循环神经网络的不可思议的效果,展示了许多现实生活中的例子。
理解 LSTM 网络,专门介绍 LSTM,但对理解通用 RNN 也很有启发。
我还建议参考上一篇教程,NLP 从零开始:使用字符级 RNN 进行姓名分类
准备数据#
注意
从此处下载数据并解压到当前目录。
有关此过程的更多详细信息,请参阅上一篇教程。简而言之,有一堆纯文本文件 data/names/[Language].txt,每行一个姓名。我们将行拆分为数组,将 Unicode 转换为 ASCII,最终得到一个字典 {language: [names ...]}。
from io import open
import glob
import os
import unicodedata
import string
all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1 # Plus EOS marker
def findFiles(path): return glob.glob(path)
# 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'
and c in all_letters
)
# Read a file and split into lines
def readLines(filename):
with open(filename, encoding='utf-8') as some_file:
return [unicodeToAscii(line.strip()) for line in some_file]
# Build the category_lines dictionary, a list of lines per category
category_lines = {}
all_categories = []
for filename in findFiles('data/names/*.txt'):
category = os.path.splitext(os.path.basename(filename))[0]
all_categories.append(category)
lines = readLines(filename)
category_lines[category] = lines
n_categories = len(all_categories)
if n_categories == 0:
raise RuntimeError('Data not found. Make sure that you downloaded data '
'from https://download.pytorch.org/tutorial/data.zip and extract it to '
'the current directory.')
print('# categories:', n_categories, all_categories)
print(unicodeToAscii("O'Néàl"))
# categories: 18 ['Arabic', 'Chinese', 'Czech', 'Dutch', 'English', 'French', 'German', 'Greek', 'Irish', 'Italian', 'Japanese', 'Korean', 'Polish', 'Portuguese', 'Russian', 'Scottish', 'Spanish', 'Vietnamese']
O'Neal
创建网络#
该网络扩展了上一个教程的 RNN,并为类别张量增加了一个额外的参数,该参数与其它输入拼接在一起。类别张量就像字母输入一样,是一个独热(one-hot)向量。
我们将输出解释为下一个字母的概率。在采样时,可能性最高的输出字母将被用作下一个输入字母。
我添加了第二个线性层 o2o(在结合了隐藏层和输出层之后),以增强其处理能力。此外还有一个 dropout 层,它会以给定的概率(这里为 0.1)随机将输入的一部分置零,通常用于模糊输入以防止过拟合。在这里,我们将其用于网络末端,以刻意增加一些混乱并提高采样的多样性。
import torch
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
self.o2o = nn.Linear(hidden_size + output_size, output_size)
self.dropout = nn.Dropout(0.1)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, category, input, hidden):
input_combined = torch.cat((category, input, hidden), 1)
hidden = self.i2h(input_combined)
output = self.i2o(input_combined)
output_combined = torch.cat((hidden, output), 1)
output = self.o2o(output_combined)
output = self.dropout(output)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return torch.zeros(1, self.hidden_size)
训练#
准备训练#
首先,编写辅助函数来获取(类别,行)的随机对。
import random
# Random item from a list
def randomChoice(l):
return l[random.randint(0, len(l) - 1)]
# Get a random category and random line from that category
def randomTrainingPair():
category = randomChoice(all_categories)
line = randomChoice(category_lines[category])
return category, line
对于每个时间步(即训练单词中的每个字母),网络的输入将是 (类别, 当前字母, 隐藏状态),输出将是 (下一个字母, 下一个隐藏状态)。因此,对于每个训练集,我们需要类别、一组输入字母和一组输出/目标字母。
由于我们在每个时间步根据当前字母预测下一个字母,字母对即为行中连续字母的组合——例如,对于 "ABCD<EOS>",我们将创建 (“A”, “B”), (“B”, “C”), (“C”, “D”), (“D”, “EOS”)。
类别张量是一个大小为 <1 x n_categories> 的独热(one-hot)张量。在训练时,我们在每个时间步将其馈送到网络中——这是一种设计选择,它本可以作为初始隐藏状态的一部分或其他策略包含在内。
# One-hot vector for category
def categoryTensor(category):
li = all_categories.index(category)
tensor = torch.zeros(1, n_categories)
tensor[0][li] = 1
return tensor
# One-hot matrix of first to last letters (not including EOS) for input
def inputTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li in range(len(line)):
letter = line[li]
tensor[li][0][all_letters.find(letter)] = 1
return tensor
# ``LongTensor`` of second letter to end (EOS) for target
def targetTensor(line):
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
letter_indexes.append(n_letters - 1) # EOS
return torch.LongTensor(letter_indexes)
为了方便训练,我们将创建一个 randomTrainingExample 函数,它获取一个随机的(类别,行)对,并将它们转换为所需的(类别,输入,目标)张量。
# Make category, input, and target tensors from a random category, line pair
def randomTrainingExample():
category, line = randomTrainingPair()
category_tensor = categoryTensor(category)
input_line_tensor = inputTensor(line)
target_line_tensor = targetTensor(line)
return category_tensor, input_line_tensor, target_line_tensor
训练网络#
与仅使用最后输出的分类任务不同,我们在每一步都进行预测,因此我们在每一步都计算损失。
Autograd 的神奇之处在于,你可以简单地将每一步的损失相加,并在最后调用 backward。
criterion = nn.NLLLoss()
learning_rate = 0.0005
def train(category_tensor, input_line_tensor, target_line_tensor):
target_line_tensor.unsqueeze_(-1)
hidden = rnn.initHidden()
rnn.zero_grad()
loss = torch.Tensor([0]) # you can also just simply use ``loss = 0``
for i in range(input_line_tensor.size(0)):
output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
l = criterion(output, target_line_tensor[i])
loss += l
loss.backward()
for p in rnn.parameters():
p.data.add_(p.grad.data, alpha=-learning_rate)
return output, loss.item() / input_line_tensor.size(0)
为了跟踪训练时长,我添加了一个 timeSince(timestamp) 函数,它返回一个易于阅读的时间字符串。
import time
import math
def timeSince(since):
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
训练过程如常——多次调用训练函数并等待几分钟,每隔 print_every 个示例打印当前时间和损失,并将每 plot_every 个示例的平均损失记录在 all_losses 中,以便稍后绘图。
rnn = RNN(n_letters, 128, n_letters)
n_iters = 100000
print_every = 5000
plot_every = 500
all_losses = []
total_loss = 0 # Reset every ``plot_every`` ``iters``
start = time.time()
for iter in range(1, n_iters + 1):
output, loss = train(*randomTrainingExample())
total_loss += loss
if iter % print_every == 0:
print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))
if iter % plot_every == 0:
all_losses.append(total_loss / plot_every)
total_loss = 0
0m 10s (5000 5%) 2.6248
0m 19s (10000 10%) 2.3207
0m 29s (15000 15%) 2.7309
0m 39s (20000 20%) 2.8301
0m 49s (25000 25%) 2.7825
0m 59s (30000 30%) 2.8494
1m 9s (35000 35%) 2.9329
1m 19s (40000 40%) 2.2834
1m 29s (45000 45%) 2.4939
1m 39s (50000 50%) 2.6489
1m 49s (55000 55%) 1.2498
1m 59s (60000 60%) 3.5055
2m 9s (65000 65%) 1.9878
2m 19s (70000 70%) 2.8272
2m 29s (75000 75%) 1.9190
2m 39s (80000 80%) 2.3218
2m 49s (85000 85%) 2.4105
2m 58s (90000 90%) 2.3316
3m 8s (95000 95%) 1.1670
3m 18s (100000 100%) 2.6873
绘制损失曲线#
从 all_losses 绘制的历史损失曲线显示了网络的学习过程。
import matplotlib.pyplot as plt
plt.figure()
plt.plot(all_losses)

[<matplotlib.lines.Line2D object at 0x7fbae11e22f0>]
网络采样#
为了采样,我们给网络一个字母并询问下一个字母是什么,将输出作为下一个输入字母输入,并重复此过程,直到遇到 EOS 标记。
为输入类别、起始字母和空的隐藏状态创建张量。
创建一个带有起始字母的字符串
output_name。在最大输出长度范围内,
将当前字母馈送到网络。
从最高输出获取下一个字母和下一个隐藏状态。
如果字母是 EOS,则在此停止。
如果是普通字母,则将其添加到
output_name并继续。
返回最终姓名。
注意
除了必须指定起始字母之外,另一种策略是在训练中包含一个“字符串开始”(start of string)标记,并让网络自己选择起始字母。
max_length = 20
# Sample from a category and starting letter
def sample(category, start_letter='A'):
with torch.no_grad(): # no need to track history in sampling
category_tensor = categoryTensor(category)
input = inputTensor(start_letter)
hidden = rnn.initHidden()
output_name = start_letter
for i in range(max_length):
output, hidden = rnn(category_tensor, input[0], hidden)
topv, topi = output.topk(1)
topi = topi[0][0]
if topi == n_letters - 1:
break
else:
letter = all_letters[topi]
output_name += letter
input = inputTensor(letter)
return output_name
# Get multiple samples from one category and multiple starting letters
def samples(category, start_letters='ABC'):
for start_letter in start_letters:
print(sample(category, start_letter))
samples('Russian', 'RUS')
samples('German', 'GER')
samples('Spanish', 'SPA')
samples('Chinese', 'CHI')
Roverovev
Uoverov
Sakovan
Gerre
Eerter
Rere
Salla
Panelas
Allan
Cha
Han
Iun
练习#
尝试使用不同的(类别 -> 行)数据集,例如:
虚构系列 -> 角色名称
词性 -> 单词
国家 -> 城市
使用“句子开始”标记,以便无需选择起始字母即可进行采样。
使用更大和/或结构更好的网络获得更好的结果。
尝试
nn.LSTM和nn.GRU层。将多个这样的 RNN 组合为更高级别的网络。
脚本总运行时间: (3 分 18.929 秒)