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

原文:https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html

作者Sean Robertson

这是我们关于“从零开始的 NLP”的三个教程中的第二个。 在第一个教程/intermediate/char_rnn_classification_tutorial中,我们使用了 RNN 将名称分类为源语言。 这次,我们将转过来并使用语言生成名称。

  1. > python sample.py Russian RUS
  2. Rovakov
  3. Uantov
  4. Shavakov
  5. > python sample.py German GER
  6. Gerren
  7. Ereng
  8. Rosher
  9. > python sample.py Spanish SPA
  10. Salla
  11. Parer
  12. Allan
  13. > python sample.py Chinese CHI
  14. Chan
  15. Hang
  16. Iun

我们仍在手工制作带有一些线性层的小型 RNN。 最大的区别在于,我们无需输入名称中的所有字母即可预测类别,而是输入类别并一次输出一个字母。 反复预测字符以形成语言(这也可以用单词或其他高阶结构来完成)通常称为“语言模型”。

推荐读物

我假设您至少已经安装了 PyTorch,Python 和张量:

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

我还建议上一教程《从零开始的 NLP:使用字符级 RNN 对名称进行分类》

准备数据

注意

从的下载数据,并将其提取到当前目录。

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

  1. from __future__ import unicode_literals, print_function, division
  2. from io import open
  3. import glob
  4. import os
  5. import unicodedata
  6. import string
  7. all_letters = string.ascii_letters + " .,;'-"
  8. n_letters = len(all_letters) + 1 # Plus EOS marker
  9. def findFiles(path): return glob.glob(path)
  10. # Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
  11. def unicodeToAscii(s):
  12. return ''.join(
  13. c for c in unicodedata.normalize('NFD', s)
  14. if unicodedata.category(c) != 'Mn'
  15. and c in all_letters
  16. )
  17. # Read a file and split into lines
  18. def readLines(filename):
  19. lines = open(filename, encoding='utf-8').read().strip().split('\n')
  20. return [unicodeToAscii(line) for line in lines]
  21. # Build the category_lines dictionary, a list of lines per category
  22. category_lines = {}
  23. all_categories = []
  24. for filename in findFiles('data/names/*.txt'):
  25. category = os.path.splitext(os.path.basename(filename))[0]
  26. all_categories.append(category)
  27. lines = readLines(filename)
  28. category_lines[category] = lines
  29. n_categories = len(all_categories)
  30. if n_categories == 0:
  31. raise RuntimeError('Data not found. Make sure that you downloaded data '
  32. 'from https://download.pytorch.org/tutorial/data.zip and extract it to '
  33. 'the current directory.')
  34. print('# categories:', n_categories, all_categories)
  35. print(unicodeToAscii("O'Néàl"))

出:

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

创建网络

该网络扩展最后一个教程的 RNN,并为类别张量附加了一个参数,该参数与其他张量连接在一起。 类别张量就像字母输入一样是一个单向向量。

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

我添加了第二个线性层o2o(在合并了隐藏和输出之后),以使其有更多的肌肉可以使用。 还有一个丢弃层,以给定的概率(此处为 0.1)将输入的部分随机归零,通常用于模糊输入以防止过拟合。 在这里,我们在网络的末端使用它来故意添加一些混乱并增加采样种类。

从零开始的 NLP:使用字符级 RNN 生成名称 - 图1

  1. import torch
  2. import torch.nn as nn
  3. class RNN(nn.Module):
  4. def __init__(self, input_size, hidden_size, output_size):
  5. super(RNN, self).__init__()
  6. self.hidden_size = hidden_size
  7. self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
  8. self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
  9. self.o2o = nn.Linear(hidden_size + output_size, output_size)
  10. self.dropout = nn.Dropout(0.1)
  11. self.softmax = nn.LogSoftmax(dim=1)
  12. def forward(self, category, input, hidden):
  13. input_combined = torch.cat((category, input, hidden), 1)
  14. hidden = self.i2h(input_combined)
  15. output = self.i2o(input_combined)
  16. output_combined = torch.cat((hidden, output), 1)
  17. output = self.o2o(output_combined)
  18. output = self.dropout(output)
  19. output = self.softmax(output)
  20. return output, hidden
  21. def initHidden(self):
  22. return torch.zeros(1, self.hidden_size)

训练

准备训练

首先,辅助函数获取随机对(类别,行):

  1. import random
  2. # Random item from a list
  3. def randomChoice(l):
  4. return l[random.randint(0, len(l) - 1)]
  5. # Get a random category and random line from that category
  6. def randomTrainingPair():
  7. category = randomChoice(all_categories)
  8. line = randomChoice(category_lines[category])
  9. return category, line

对于每个时间步(即,对于训练词中的每个字母),网络的输入将为(category, current letter, hidden state),而输出将为(next letter, next hidden state)。 因此,对于每个训练集,我们都需要类别,一组输入字母和一组输出/目标字母。

由于我们正在预测每个时间步中当前字母的下一个字母,因此字母对是该行中连续字母的组-例如对于"ABCD<EOS>",我们将创建('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'EOS')

从零开始的 NLP:使用字符级 RNN 生成名称 - 图2

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

  1. # One-hot vector for category
  2. def categoryTensor(category):
  3. li = all_categories.index(category)
  4. tensor = torch.zeros(1, n_categories)
  5. tensor[0][li] = 1
  6. return tensor
  7. # One-hot matrix of first to last letters (not including EOS) for input
  8. def inputTensor(line):
  9. tensor = torch.zeros(len(line), 1, n_letters)
  10. for li in range(len(line)):
  11. letter = line[li]
  12. tensor[li][0][all_letters.find(letter)] = 1
  13. return tensor
  14. # LongTensor of second letter to end (EOS) for target
  15. def targetTensor(line):
  16. letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
  17. letter_indexes.append(n_letters - 1) # EOS
  18. return torch.LongTensor(letter_indexes)

为了方便训练,我们将使用randomTrainingExample函数来获取随机(类别,行)对,并将其转换为所需的(类别,输入,目标)张量。

  1. # Make category, input, and target tensors from a random category, line pair
  2. def randomTrainingExample():
  3. category, line = randomTrainingPair()
  4. category_tensor = categoryTensor(category)
  5. input_line_tensor = inputTensor(line)
  6. target_line_tensor = targetTensor(line)
  7. return category_tensor, input_line_tensor, target_line_tensor

训练网络

与仅使用最后一个输出的分类相反,我们在每个步骤进行预测,因此在每个步骤都计算损失。

Autograd 的神奇之处在于,您可以简单地在每个步骤中对这些损失进行求和,然后在末尾调用。

  1. criterion = nn.NLLLoss()
  2. learning_rate = 0.0005
  3. def train(category_tensor, input_line_tensor, target_line_tensor):
  4. target_line_tensor.unsqueeze_(-1)
  5. hidden = rnn.initHidden()
  6. rnn.zero_grad()
  7. loss = 0
  8. for i in range(input_line_tensor.size(0)):
  9. output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
  10. l = criterion(output, target_line_tensor[i])
  11. loss += l
  12. loss.backward()
  13. for p in rnn.parameters():
  14. p.data.add_(p.grad.data, alpha=-learning_rate)
  15. return output, loss.item() / input_line_tensor.size(0)

为了跟踪训练需要多长时间,我添加了一个timeSince(timestamp)函数,该函数返回人类可读的字符串:

  1. import time
  2. import math
  3. def timeSince(since):
  4. now = time.time()
  5. s = now - since
  6. m = math.floor(s / 60)
  7. s -= m * 60
  8. return '%dm %ds' % (m, s)

训练照常进行-召集训练多次并等待几分钟,每print_every个示例打印当前时间和损失,并在all_losses中保存每个plot_every实例的平均损失以供以后绘制。

  1. rnn = RNN(n_letters, 128, n_letters)
  2. n_iters = 100000
  3. print_every = 5000
  4. plot_every = 500
  5. all_losses = []
  6. total_loss = 0 # Reset every plot_every iters
  7. start = time.time()
  8. for iter in range(1, n_iters + 1):
  9. output, loss = train(*randomTrainingExample())
  10. total_loss += loss
  11. if iter % print_every == 0:
  12. print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))
  13. if iter % plot_every == 0:
  14. all_losses.append(total_loss / plot_every)
  15. total_loss = 0

出:

  1. 0m 26s (5000 5%) 3.2265
  2. 0m 51s (10000 10%) 3.0171
  3. 1m 16s (15000 15%) 2.1535
  4. 1m 41s (20000 20%) 2.0806
  5. 2m 7s (25000 25%) 2.3842
  6. 2m 32s (30000 30%) 2.5014
  7. 2m 57s (35000 35%) 2.2441
  8. 3m 22s (40000 40%) 2.2113
  9. 3m 47s (45000 45%) 2.1184
  10. 4m 13s (50000 50%) 1.3983
  11. 4m 38s (55000 55%) 2.5881
  12. 5m 3s (60000 60%) 1.8033
  13. 5m 29s (65000 65%) 2.4285
  14. 5m 54s (70000 70%) 2.4198
  15. 6m 20s (75000 75%) 2.9660
  16. 6m 45s (80000 80%) 1.9752
  17. 7m 11s (85000 85%) 3.7507
  18. 7m 36s (90000 90%) 2.2044
  19. 8m 2s (95000 95%) 2.8938
  20. 8m 27s (100000 100%) 2.2471

绘制损失图

绘制all_loss的历史损失可显示网络学习情况:

  1. import matplotlib.pyplot as plt
  2. import matplotlib.ticker as ticker
  3. plt.figure()
  4. plt.plot(all_losses)

../_img/sphx_glr_char_rnn_generation_tutorial_001.png

网络采样

为了示例,我们给网络一个字母,询问下一个字母是什么,将其作为下一个字母输入,并重复直到 EOS 标记。

  • 为输入类别,起始字母和空隐藏状态创建张量
  • 用起始字母创建一个字符串output_name
  • 直到最大输出长度,
    • 将当前字母输入网络
    • 从最高输出中获取下一个字母,以及下一个隐藏状态
    • 如果字母是EOS,请在此处停止
    • 如果是普通字母,请添加到output_name并继续
  • 返回姓氏

注意

不必给它起一个开始字母,另一种策略是在训练中包括一个“字符串开始”标记,并让网络选择自己的开始字母。

  1. max_length = 20
  2. # Sample from a category and starting letter
  3. def sample(category, start_letter='A'):
  4. with torch.no_grad(): # no need to track history in sampling
  5. category_tensor = categoryTensor(category)
  6. input = inputTensor(start_letter)
  7. hidden = rnn.initHidden()
  8. output_name = start_letter
  9. for i in range(max_length):
  10. output, hidden = rnn(category_tensor, input[0], hidden)
  11. topv, topi = output.topk(1)
  12. topi = topi[0][0]
  13. if topi == n_letters - 1:
  14. break
  15. else:
  16. letter = all_letters[topi]
  17. output_name += letter
  18. input = inputTensor(letter)
  19. return output_name
  20. # Get multiple samples from one category and multiple starting letters
  21. def samples(category, start_letters='ABC'):
  22. for start_letter in start_letters:
  23. print(sample(category, start_letter))
  24. samples('Russian', 'RUS')
  25. samples('German', 'GER')
  26. samples('Spanish', 'SPA')
  27. samples('Chinese', 'CHI')

出:

  1. Rovanov
  2. Uarinov
  3. Santovov
  4. Gangerten
  5. Erer
  6. Roure
  7. Salla
  8. Parera
  9. Allan
  10. Chin
  11. Han
  12. Iun

练习

  • 尝试使用类别 -> 行的其他数据集,例如:
    • 虚构序列 -> 角色名称
    • 词性 -> 词
    • 国家 -> 城市
  • 使用“句子开头”标记,以便无需选择开始字母即可进行采样
  • 通过更大和/或形状更好的网络获得更好的结果
    • 尝试nn.LSTMnn.GRU
    • 将多个这些 RNN 合并为更高级别的网络

脚本的总运行时间:(8 分钟 27.431 秒)

下载 Python 源码:char_rnn_generation_tutorial.py

下载 Jupyter 笔记本:char_rnn_generation_tutorial.ipynb

由 Sphinx 画廊生成的画廊