NLP From Scratch:使用char-RNN对姓氏进行分类

作者:Sean Robertson

译者:松鼠

校验:松鼠Aidol

我们将构建和训练基本的char-RNN来对单词进行分类。本教程以及以下两个教程展示了如何“从头开始”为NLP建模进行预处理数据,尤其是不使用Torchtext的许多便利功能,因此您可以了解NLP建模的预处理是如何从低层次进行的。

char-RNN将单词作为一系列字符读取,在每个步骤输出预测和“隐藏状态”,将其先前的隐藏状态输入到每个下一步。我们将最终的预测作为输出,即单词属于哪个类别。

具体来说,我们将训练起源于18种语言的数千种姓氏,并根据拼写来预测姓氏来自哪种语言:

  1. $ python predict.py Hinton
  2. (-0.47) Scottish
  3. (-1.52) English
  4. (-3.57) Irish
  5. $ python predict.py Schmidhuber
  6. (-0.19) German
  7. (-2.48) Czech
  8. (-2.68) Dutch

建议:

假设你已经至少安装PyTorch,知道Python和理解张量:

下面这些是了解RNNs以及它们如何工作的相关联接:

准备数据

  • Note 从此处下载数据,并将其解压到当前目录。

包含了在data/names目录被命名为[Language] .txt 的18个文本文件。每个文件都包含了一堆姓氏,每行一个名字,大多都已经罗马字母化了(但我们仍然需要从Unicode转换到到ASCII)。

我们将得到一个字典,列出每种语言的名称列表 。通用变量categoryline(在本例中为语言和名称)用于以后的扩展。{language: [names ...]}

  1. from __future__ import unicode_literals, print_function, division
  2. from io import open
  3. import glob
  4. import os
  5. def findFiles(path): return glob.glob(path)
  6. print(findFiles('data/names/*.txt'))
  7. import unicodedata
  8. import string
  9. all_letters = string.ascii_letters + " .,;'"
  10. n_letters = len(all_letters)
  11. # Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
  12. # 作用就是把Unicode转换为ASCII
  13. def unicodeToAscii(s):
  14. return ''.join(
  15. # NFD表示字符应该分解为多个组合字符表示
  16. c for c in unicodedata.normalize('NFD', s)
  17. if unicodedata.category(c) != 'Mn'
  18. and c in all_letters
  19. )
  20. print(unicodeToAscii('Ślusàrski'))
  21. # Build the category_lines dictionary, a list of names per language
  22. category_lines = {}
  23. all_categories = []
  24. # Read a file and split into lines
  25. def readLines(filename):
  26. lines = open(filename, encoding='utf-8').read().strip().split('\n')
  27. return [unicodeToAscii(line) for line in lines]
  28. for filename in findFiles('data/names/*.txt'):
  29. category = os.path.splitext(os.path.basename(filename))[0]
  30. all_categories.append(category)
  31. lines = readLines(filename)
  32. category_lines[category] = lines
  33. n_categories = len(all_categories)

输出:

  1. ['data/names/French.txt', 'data/names/Czech.txt', 'data/names/Dutch.txt', 'data/names/Polish.txt', 'data/names/Scottish.txt', 'data/names/Chinese.txt', 'data/names/English.txt', 'data/names/Italian.txt', 'data/names/Portuguese.txt', 'data/names/Japanese.txt', 'data/names/German.txt', 'data/names/Russian.txt', 'data/names/Korean.txt', 'data/names/Arabic.txt', 'data/names/Greek.txt', 'data/names/Vietnamese.txt', 'data/names/Spanish.txt', 'data/names/Irish.txt']
  2. Slusarski

现在,我们有了category_lines字典,将每个类别(语言)映射到行(姓氏)列表。我们还保持all_categories(只是一种语言列表)和n_categories为可追加状态,供后续的调用。

  1. print(category_lines['Italian'][:5])

输出:

  1. ['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni']

将姓氏转化为张量

我们已经处理好了所有的姓氏,现在我们需要将它们转换为张量以使用它们。

为了表示单个字母,我们使用大小为<1 x n letters>的“独热向量” 。一个独热向量就是在字母索引处填充1,其他都填充为0,例,"b" = <0 1 0 0 0 ...>

为了表达一个单词,我们将一堆字母合并成2D矩阵,其中矩阵的大小为<line_length x 1 x n_letters>

额外的1维是因为PyTorch假设所有东西都是成批的-我们在这里只使用1的批处理大小。

  1. import torch
  2. # Find letter index from all_letters, e.g. "a" = 0
  3. def letterToIndex(letter):
  4. return all_letters.find(letter)
  5. # Just for demonstration, turn a letter into a <1 x n_letters> Tensor
  6. def letterToTensor(letter):
  7. tensor = torch.zeros(1, n_letters)
  8. tensor[0][letterToIndex(letter)] = 1
  9. return tensor
  10. # Turn a line into a <line_length x 1 x n_letters>,
  11. # or an array of one-hot letter vectors
  12. def lineToTensor(line):
  13. tensor = torch.zeros(len(line), 1, n_letters)
  14. for li, letter in enumerate(line):
  15. tensor[li][0][letterToIndex(letter)] = 1
  16. return tensor
  17. print(letterToTensor('J'))
  18. print(lineToTensor('Jones').size())

输出:

  1. tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
  2. 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
  3. 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
  4. 0., 0., 0.]])
  5. torch.Size([5, 1, 57])

创建网络

在进行自动求导之前,在Torch中创建一个递归神经网络需要在多个时间状态上克隆图的参数。图保留了隐藏状态和梯度,这些状态和梯度现在完全由图本身处理。这意味着您可以以非常“单纯”的方式将RNN作为常规的前馈网络来实现。

这个RNN模块(大部分是从PyTorch for Torch用户教程中复制的)只有2个线性层,它们在输入和隐藏状态下运行,输出之后是LogSoftmax层。

RNN.jpg

  1. import torch.nn as nn
  2. class RNN(nn.Module):
  3. def __init__(self, input_size, hidden_size, output_size):
  4. super(RNN, self).__init__()
  5. self.hidden_size = hidden_size
  6. self.i2h = nn.Linear(input_size + hidden_size, hidden_size)
  7. self.i2o = nn.Linear(input_size + hidden_size, output_size)
  8. self.softmax = nn.LogSoftmax(dim=1)
  9. def forward(self, input, hidden):
  10. combined = torch.cat((input, hidden), 1)
  11. hidden = self.i2h(combined)
  12. output = self.i2o(combined)
  13. output = self.softmax(output)
  14. return output, hidden
  15. def initHidden(self):
  16. return torch.zeros(1, self.hidden_size)
  17. n_hidden = 128
  18. rnn = RNN(n_letters, n_hidden, n_categories)

运行网络的步骤是,首先我们需要输入(在本例中为当前字母的张量)和先前的隐藏状态(首先将其初始化为零)。我们将返回输出(每种语言的概率)和下一个隐藏状态(我们将其保留用于下一步)。

  1. input = letterToTensor('A')
  2. hidden =torch.zeros(1, n_hidden)
  3. output, next_hidden = rnn(input, hidden)

为了提高效率,我们不想为每个步骤都创建一个新的Tensor,因此我们将使用lineToTensor加切片的方式来代替letterToTensor。这可以通过预先计算一批张量来进一步优化。

  1. input = lineToTensor('Albert')
  2. hidden = torch.zeros(1, n_hidden)
  3. output, next_hidden = rnn(input[0], hidden)
  4. print(output)

输出:

  1. tensor([[-2.8636, -2.8199, -2.8899, -2.9073, -2.9117, -2.8644, -2.9027, -2.9334,
  2. -2.8705, -2.8383, -2.8892, -2.9161, -2.8215, -2.9996, -2.9423, -2.9116,
  3. -2.8750, -2.8862]], grad_fn=<LogSoftmaxBackward>)

正如你看到的输出为<1 * n_categories>的张量,其中每一个值都是该类别的可能性(数值越大可能性越高)。

训练

准备训练

在训练之前,我们需要做一些辅助函数。首先是解释网络的输出,我们知道这是每个类别的可能性。我们可以用Tensor.topk来获取最大值对应的索引:

  1. def categoryFromOutput(output):
  2. top_n, top_i = output.topk(1)
  3. category_i = top_i[0].item()
  4. return all_categories[category_i], category_i
  5. print(categoryFromOutput(output))

输出:

  1. ('Czech', 1)

我们也将需要一个快速的方法来获得一个训练例子(姓氏和其所属语言):

  1. import random
  2. def randomChoice(l):
  3. return l[random.randint(0, len(l) - 1)]
  4. def randomTrainingExample():
  5. category = randomChoice(all_categories)
  6. line = randomChoice(category_lines[category])
  7. category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long)
  8. line_tensor = lineToTensor(line)
  9. return category, line, category_tensor, line_tensor
  10. for i in range(10):
  11. category, line, category_tensor, line_tensor = randomTrainingExample()
  12. print('category =', category, '\t // \t line =', line)

输出:

  1. category = Dutch // line = Ryskamp
  2. category = Spanish // line = Iniguez
  3. category = Vietnamese // line = Thuy
  4. category = Italian // line = Nacar
  5. category = Vietnamese // line = Le
  6. category = French // line = Tremblay
  7. category = Russian // line = Bakhchivandzhi
  8. category = Irish // line = Kavanagh
  9. category = Irish // line = O'Shea
  10. category = Spanish // line = Losa

网络训练

现在,训练该网络所需要做的就是向它喂入大量训练样例,进行预测,并告诉它预测的是否正确。

最后因为RNN的最后一层是nn.LogSoftmax,所以我们选择损失函数nn.NLLLoss比较合适。

  1. criterion = nn.NLLLoss()

每个循环的训练将:

  • 创建输入和目标张量
  • 创建一个零初始隐藏状态
  • 读取每个字母
    • 保持隐藏状态到下一个字母
  • 比较最后输出和目标
  • 进行反向传播
  • 返回输出值和损失函数的值
  1. learning_rate = 0.005
  2. # If you set this too high, it might explode. If too low, it might not learn
  3. def train(category_tensor, line_tensor):
  4. hidden = rnn.initHidden()
  5. rnn.zero_grad()
  6. for i in range(line_tensor.size()[0]):
  7. output, hidden = rnn(line_tensor[i], hidden)
  8. loss = criterion(output, category_tensor)
  9. loss.backward()
  10. # Add parameters' gradients to their values, multiplied by learning rate
  11. for p in rnn.parameters():
  12. # 下面一行代码的作用效果为 p.data = p.data -learning_rate*p.grad.data,更新权重
  13. p.data.add_(-learning_rate, p.grad.data)
  14. return output, loss.item()

现在,我们只需要运行大量样例。由于train函数同时返回outputloss,因此我们可以打印其猜测并跟踪绘制损失。由于有1000个样例,因此我们仅打印每个print_every样例,并对损失进行平均。

  1. import time
  2. import math
  3. n_iters = 100000
  4. print_every = 5000
  5. plot_every = 1000
  6. # Keep track of losses for plotting
  7. current_loss = 0
  8. all_losses = []
  9. def timeSince(since):
  10. now = time.time()
  11. s = now - since
  12. m = math.floor(s / 60)
  13. s -= m * 60
  14. return '%dm %ds' % (m, s)
  15. start = time.time()
  16. for iter in range(1, n_iters + 1):
  17. category, line, category_tensor, line_tensor = randomTrainingExample()
  18. output, loss = train(category_tensor, line_tensor)
  19. current_loss += loss
  20. # Print iter number, loss, name and guess
  21. if iter % print_every == 0:
  22. guess, guess_i = categoryFromOutput(output)
  23. correct = '✓' if guess == category else '✗ (%s)' % category
  24. print('%d %d%% (%s) %.4f %s / %s %s' % (iter, iter / n_iters * 100, timeSince(start), loss, line, guess, correct))
  25. # Add current loss avg to list of losses
  26. if iter % plot_every == 0:
  27. all_losses.append(current_loss / plot_every)
  28. current_loss = 0

输出:

  1. 5000 5% (0m 7s) 2.7482 Silje / French (Dutch)
  2. 10000 10% (0m 15s) 1.5569 Lillis / Greek
  3. 15000 15% (0m 22s) 2.7729 Burt / Korean (English)
  4. 20000 20% (0m 30s) 1.1036 Zhong / Chinese
  5. 25000 25% (0m 38s) 1.7088 Sarraf / Portuguese (Arabic)
  6. 30000 30% (0m 45s) 0.7595 Benivieni / Italian
  7. 35000 35% (0m 53s) 1.2900 Arreola / Italian (Spanish)
  8. 40000 40% (1m 0s) 2.3171 Gass / Arabic (German)
  9. 45000 45% (1m 8s) 3.1630 Stoppelbein / Dutch (German)
  10. 50000 50% (1m 15s) 1.7478 Berger / German (French)
  11. 55000 55% (1m 23s) 1.3516 Almeida / Spanish (Portuguese)
  12. 60000 60% (1m 31s) 1.8843 Hellewege / Dutch (German)
  13. 65000 65% (1m 38s) 1.7374 Moreau / French
  14. 70000 70% (1m 46s) 0.5718 Naifeh / Arabic
  15. 75000 75% (1m 53s) 0.6268 Zhui / Chinese
  16. 80000 80% (2m 1s) 2.2226 Dasios / Portuguese (Greek)
  17. 85000 85% (2m 9s) 1.3690 Walter / Scottish (German)
  18. 90000 90% (2m 16s) 0.5329 Zhang / Chinese
  19. 95000 95% (2m 24s) 3.4474 Skala / Czech (Polish)
  20. 100000 100% (2m 31s) 1.4720 Chi / Korean (Chinese)

绘制结果

从绘制all_losses的历史损失图可以看出网络的学习:

  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_classification_tutorial_001.png

评价结果

为了了解网络在不同类别上的表现如何,我们将创建一个混淆矩阵,包含姓氏属于的实际语言(行)和网络猜测的是哪种语言(列)。要计算混淆矩阵,将使用evaluate()通过网络来评测一些样本。

  1. # Keep track of correct guesses in a confusion matrix
  2. confusion = torch.zeros(n_categories, n_categories)
  3. n_confusion = 10000
  4. # Just return an output given a line
  5. def evaluate(line_tensor):
  6. hidden = rnn.initHidden()
  7. for i in range(line_tensor.size()[0]):
  8. output, hidden = rnn(line_tensor[i], hidden)
  9. return output
  10. # Go through a bunch of examples and record which are correctly guessed
  11. for i in range(n_confusion):
  12. category, line, category_tensor, line_tensor = randomTrainingExample()
  13. output = evaluate(line_tensor)
  14. guess, guess_i = categoryFromOutput(output)
  15. category_i = all_categories.index(category)
  16. confusion[category_i][guess_i] += 1
  17. # Normalize by dividing every row by its sum
  18. for i in range(n_categories):
  19. confusion[i] = confusion[i] / confusion[i].sum()
  20. # Set up plot
  21. fig = plt.figure()
  22. ax = fig.add_subplot(111)
  23. cax = ax.matshow(confusion.numpy())
  24. fig.colorbar(cax)
  25. # Set up axes
  26. ax.set_xticklabels([''] + all_categories, rotation=90)
  27. ax.set_yticklabels([''] + all_categories)
  28. # Force label at every tick
  29. ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
  30. ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
  31. # sphinx_gallery_thumbnail_number = 2
  32. plt.show()

img/sphx_glr_char_rnn_classification_tutorial_002.png

您可以从主轴上挑出一些亮点,以显示错误猜测的语言,例如,中文(朝鲜语)和西班牙语(意大利语)。它似乎与希腊语搭预测得很好,而英语预测的很差(可能是因为与其他语言重叠)。

运行用户输入

  1. def predict(input_line, n_predictions=3):
  2. print('\n> %s' % input_line)
  3. with torch.no_grad():
  4. output = evaluate(lineToTensor(input_line))
  5. # Get top N categories
  6. topv, topi = output.topk(n_predictions, 1, True)
  7. predictions = []
  8. for i in range(n_predictions):
  9. value = topv[0][i].item()
  10. category_index = topi[0][i].item()
  11. print('(%.2f) %s' % (value, all_categories[category_index]))
  12. predictions.append([value, all_categories[category_index]])
  13. predict('Dovesky')
  14. predict('Jackson')
  15. predict('Satoshi')

Out:

  1. > Dovesky
  2. (-0.47) Russian
  3. (-1.30) Czech
  4. (-2.90) Polish
  5. > Jackson
  6. (-1.04) Scottish
  7. (-1.72) English
  8. (-1.74) Russian
  9. > Satoshi
  10. (-0.32) Japanese
  11. (-2.63) Polish
  12. (-2.71) Italian

实际PyTorch存储库中的脚本的最终版本将上述代码分成几个文件:

  • data.py(加载文件)
  • model.py(定义RNN)
  • train.py(训练)
  • predict.py(predict()与命令行参数一起运行)
  • server.py(通过bottle.py将预测用作JSON API)

运行train.py训练并保存网络。

predict.py脚本并加上姓氏运行以查看预测:

  1. $ python predict.py Hazaki
  2. (-0.42) Japanese
  3. (-1.39) Polish
  4. (-3.51) Czech

运行server.py,查看http://localhost:5533/Yourname 获得预测的JSON输出。

练习

  • 尝试使用line-> category的其他数据集,例如:
    • 任何单词->语言
    • 名->性别
    • 角色名称->作家
    • 页面标题-> Blog或subreddit
  • 通过更大和/或结构更好的网络获得更好的结果
    • 添加更多线性层
    • 尝试nn.LSTM和nn.GRU图层
    • 将多个这些RNN合并为更高级别的网络

脚本的总运行时间: (2分钟42.458秒)