• 教程 >
  • 从零开始 NLP:使用字符级 RNN 生成名字
Shortcuts

从零开始 NLP:使用字符级 RNN 生成名字

作者Sean Robertson

这是我们关于"从零开始NLP"的三个教程中的第二个。 第一个教程 </intermediate/char_rnn_classification_tutorial> 中,我们使用 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:

了解 RNN 及其工作方式也很有用:

我还建议前面的教程NLP From Scratch: Classifying Names with a Character-Level RNN

准备数据|

注意

此处下载数据并将其提取到当前目录。

有关此过程的更多详细信息,请参阅上一教程。 简而言之,有一堆纯文本文件data/names/[Language].txt每行都有一个名称。 我们将行拆分为数组,将 Unicode 转换为 ASCII,最后使用字典 *语言: *名称 ...]}.

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

输出:

# categories: 18 ['Czech', 'Vietnamese', 'Arabic', 'Irish', 'Chinese', 'German', 'Korean', 'Polish', 'Scottish', 'Greek', 'English', 'Spanish', 'Portuguese', 'French', 'Japanese', 'Dutch', 'Russian', 'Italian']
O'Neal

创建网络|

此网络扩展了最后一个教程的 RNN,为类别张带提供了额外的参数,该参数与其他对象一起串联。 类别张量是一个一热矢量,就像字母输入一样。

我们将输出解释为下一个字母的概率。 采样时,最有可能的输出字母用作下一个输入字母。

我添加了第二个线性层o2o在合并隐藏和输出后),以给它更多的肌肉工作。 还有一个辍学层,它随机将部分输入与给定的概率(此处为 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

对于每个时间步长(即训练词中的每个字母),网络的输入将是(类别、当前字母、隐藏状态),输出将为(下一个字母下一个隐藏状态)。 因此,对于每个训练集,我们需要类别、一组输入字母和一组输出/目标字母。

Since we are predicting the next letter from the current letter for each timestep, the letter pairs are groups of consecutive letters from the line - e.g. for "ABCD<EOS>" we would create (“A”, “B”), (“B”, “C”), (“C”, “D”), (“D”, “EOS”).

类别张量是一个一热的张量大小 <1 x n_categories> . 训练时,我们在每个时间都将其馈送到网络 - 这是一个设计选择,它可以作为初始隐藏状态的一部分或某种其他策略包含在内。

# 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 的魔力允许您在每一步中简单地求和这些损失,并在结束时向后调用。

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(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 28s (5000 5%) 3.1620
0m 56s (10000 10%) 1.8557
1m 25s (15000 15%) 2.5957
1m 53s (20000 20%) 2.6868
2m 21s (25000 25%) 2.1645
2m 50s (30000 30%) 3.9349
3m 19s (35000 35%) 2.6591
3m 48s (40000 40%) 2.4535
4m 16s (45000 45%) 2.2958
4m 46s (50000 50%) 2.5135
5m 14s (55000 55%) 1.9183
5m 42s (60000 60%) 1.9529
6m 11s (65000 65%) 2.2531
6m 40s (70000 70%) 2.3864
7m 8s (75000 75%) 2.9506
7m 37s (80000 80%) 1.5149
8m 5s (85000 85%) 2.0673
8m 33s (90000 90%) 3.0599
9m 1s (95000 95%) 2.3946
9m 29s (100000 100%) 2.8535

绘制损失|

绘制all_losses的历史损失显示了网络学习:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)
../_images/sphx_glr_char_rnn_generation_tutorial_001.png

采样网络|

为了进行采样,我们给网络一个字母,并询问下一个字母是什么,在中作为下一个字母提供,然后重复直到 EOS 令牌。

  • 为输入类别、起始字母和空隐藏状态创建张量

  • 使用起始字母output_name创建字符串

  • 最大输出长度,

    • 将当前字母馈送到网络

    • 从最高输出获取下一个字母,以及下一个隐藏状态

    • 如果字母是 EOS,则停止此处

    • 如果是普通字母,则添加output_name并继续

  • 返回最终名称

注意

另一种策略是在训练中加入"字符串开始"令牌,让网络选择自己的起始字母,而不是给它一个起始字母。

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

输出:

Rakovak
Uakovev
Shanton
Ganter
Eres
Ronger
Santa
Poure
Arana
Chan
Han
Iun

练习|

  • 请尝试使用类别 -* 行的不同数据集,例如:

    • 虚构系列 -* 角色名称

    • 语音的一部分 -* 单词

    • 国家 /* 城市

  • 使用"句子开头"标记,以便在不选择起始字母的情况下进行采样

  • 使用更大和/或形状更好的网络获得更好的结果

    • 试试nn.LSTM 和 nn.GRU 图层

    • 将这些 RN 的多个 RN 结合为更高级别的网络

脚本总运行时间: (9分30.241秒)

由狮身人面像库生成的画廊