作者: Sean Robertson
在上一篇教程,我们使用RNN将名称分类为它们的原始语言。这次我们将回过头来,从语言中生成名称。
(上一篇的翻译[https://blog.youkuaiyun.com/shuzip/article/details/101716625])
> 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
推荐阅读:
我假设您至少安装了PyTorch,了解Python并理解张量:
- https://pytorch.org/ 安装文档
- Deep Learning with PyTorch: A 60 Minute Blitz 入门级的pytorch教材
- Learning PyTorch with Examples 一个广泛和深入的概述
- PyTorch for Former Torch Users 如果您是之前Lua Torch的用户
了解RNNs及其工作原理也很有用:
- The Unreasonable Effectiveness of Recurrent Neural Networks shows a bunch of real life examples
- Understanding LSTM Networks is about LSTMs specifically but also informative about RNNs in general
我还建议使用前面的教程使用字符级RNN对名称进行分类]
准备数据
注意
从此处下载数据并将其解压缩到当前目录
有关此过程的详细信息,请参阅上一教程。简而言之,有一堆纯文本文件data/names/[Language].txt,每行有一个名称。我们将行分割成一个数组,将Unicode转换为ASCII,最后得到一个字典{language: [names…]}。
from __future__ import unicode_literals, print_function, division
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):
lines = open(filename, encoding='utf-8').read().strip().split('\n')
return [unicodeToAscii(line) for line in lines]
# 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"))
Out:
# categories: 18 ['French', 'Czech', 'Dutch', 'Polish', 'Scottish', 'Chinese', 'English', 'Italian', 'Portuguese', 'Japanese', 'German', 'Russian', 'Korean', 'Arabic', 'Greek', 'Vietnamese', 'Spanish', 'Irish']
O'Neal
创建网络
这个网络扩展了[上一节教程的RNN](https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html# create -the- the- network),并为类别张量添加了一个额外的参数,这个参数与其他张量连接在一起。类别张量是一个热向量,就像字母输入一样。
我们将把输出解释为下一个字母的概率。采样时,最有可能的输出字母用作下一个输入字母。
我添加了第二个线性层“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)
Training
Preparing for Training
First of all, helper functions to get random pairs of (category, line):
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
对于每个时间步(即训练词中的每个字母),网络的输入将是(类别(category)、当前文字、隐藏状态),输出将是(下一个文字、下一个隐藏状态)。因此,对于每个训练集,我们都需要类别、一组输入文字和一组输出/目标文字。
因为我们为每个时间步从当前字母预测下一个字母,所以字母对是行中连续的字母组——例如,对于"ABCD",我们将创建(“A”、“B”)、(“B”、“C”)、(“C”、“D”)、(“D”、“EOS”)。
类别张量是一个 one-hot tensor 大小为 <1 x n_categories>
.当训练时,我们在每一时间步都将它喂给给神经网络——这是一种设计选择,它可以作为初始隐藏状态或其他策略的一部分。
# One-hot vector for category(one-hot 类别的向量)
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
#One-hot矩阵的首字母到尾字母(不包括EOS)的输入
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
#目标的第二个结束字母(EOS)的长张量
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的神奇之处在于,您可以简单地在每一步计算这些损失并在最后回调。
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 = 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_(-learning_rate, p.grad.data)
return output, loss.item() / input_line_tensor.size(0)
为了跟踪训练需要多长时间,我添加了一个timeSince(时间戳)函数,它返回一个人类可读的字符串:
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示例的损失,并在all_loss中保存每个plot_every示例的平均损失,以便稍后绘图。
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
Out:
0m 23s (5000 5%) 3.0430
0m 42s (10000 10%) 2.8743
1m 2s (15000 15%) 3.3478
1m 21s (20000 20%) 3.8855
1m 41s (25000 25%) 2.1568
2m 0s (30000 30%) 2.2939
2m 19s (35000 35%) 2.0112
2m 38s (40000 40%) 1.9252
2m 58s (45000 45%) 2.6446
3m 17s (50000 50%) 1.7296
3m 36s (55000 55%) 2.9077
3m 55s (60000 60%) 2.2661
4m 15s (65000 65%) 2.7242
4m 34s (70000 70%) 2.0032
4m 53s (75000 75%) 2.0722
5m 13s (80000 80%) 3.6096
5m 32s (85000 85%) 3.3348
5m 51s (90000 90%) 2.5201
6m 10s (95000 95%) 2.0522
6m 29s (100000 100%) 2.2390
绘制损失
绘制all_loss的历史损失,显示网络学习:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.figure()
plt.plot(all_losses)
对网络进行采样
为了进行示例,我们给网络一个文字并询问下一个文字是什么,将其作为下一个文字输入,然后重复,直到EOS令牌。
- 为输入类别、起始字母和空隐藏状态创建张量
- 创建一个以字母开头的字符串output_name
- 直到最大输出长度,
- 将当前文字输入网络
- 从最高输出获取下一个字母,以及下一个隐藏状态
- 如果这文字是EOS,请在这里停下来
- 如果是普通字母,则将其添加到output_name并继续
- 返回最终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')
Out:
Rakinok
Uakovav
Shavakov
Gereng
Erenger
Romane
Sanera
Pares
Allana
Cho
Han
Iua
练习Exercises
- Try with a different dataset of category -> line, for example:(尝试使用不同的数据集类别->行,例如:)
- Fictional series -> Character name(虚构系列->人物名称)
- Part of speech -> Word(词性部分->单词)
- Country -> City(国家- >城市)
- Use a “start of sentence” token so that sampling can be done without choosing a start letter(使用“句子开头”标记,这样就可以在不选择开头字母的情况下进行抽样)
- Get better results with a bigger and/or better shaped network(使用更大和/或形状更好的网络可以获得更好的结果)
- Try the nn.LSTM and nn.GRU layers
- Combine multiple of these RNNs as a higher level network(将这些RNNs组合成一个更高级别的网络)
**脚本的总运行时间:(6分30.036秒)