当前位置:   article > 正文

PyTorch翻译官网教程-NLP FROM SCRATCH: CLASSIFYING NAMES WITH A CHARACTER-LEVEL RNN_pytorch官网的nlp

pytorch官网的nlp

官网链接

NLP From Scratch: Classifying Names with a Character-Level RNN — PyTorch Tutorials 2.0.1+cu117 documentation

使用CHARACTER-LEVEL RNN 对名字分类

我们将建立和训练一个基本的字符级递归神经网络(RNN)来分类单词。本教程以及另外两个“from scratch”的自然语言处理(NLP)教程 NLP From Scratch: Generating Names with a Character-Level RNN NLP From Scratch: Translation with a Sequence to Sequence Network and Attention,演示如何预处理数据以建立NLP模型。特别是,这些教程没有使用torchtext的许多便利功能,因此您可以看到如何简单使用预处理模型NLP。

字符级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编程语言和张量有基本的了解:

了解rnn及其工作原理也很有用:

准备数据

从这里下载数据并将其解压缩到当前目录。here

data/names”目录下包含18个文本文件,文件名为“[Language].txt”。每个文件包含一堆名称,每行一个名称,大多数是罗马化的(但我们仍然需要从Unicode转换为ASCII)。

我们最终会得到一个包含每种语言名称列表的字典,{language: [names ...]}。通用变量“category”和“line”(在本例中表示语言和名称)用于以后的可扩展性。

  1. from io import open
  2. import glob
  3. import os
  4. def findFiles(path): return glob.glob(path)
  5. print(findFiles('data/names/*.txt'))
  6. import unicodedata
  7. import string
  8. all_letters = string.ascii_letters + " .,;'"
  9. n_letters = len(all_letters)
  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. print(unicodeToAscii('Ślusàrski'))
  18. # Build the category_lines dictionary, a list of names per language
  19. category_lines = {}
  20. all_categories = []
  21. # Read a file and split into lines
  22. def readLines(filename):
  23. lines = open(filename, encoding='utf-8').read().strip().split('\n')
  24. return [unicodeToAscii(line) for line in lines]
  25. for filename in findFiles('data/names/*.txt'):
  26. category = os.path.splitext(os.path.basename(filename))[0]
  27. all_categories.append(category)
  28. lines = readLines(filename)
  29. category_lines[category] = lines
  30. n_categories = len(all_categories)

输出

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

现在我们有了category_lines,这是一个将每个类别(语言)映射到行(名称)列表的字典。我们还记录了all_categories(只是一个语言列表)和n_categories,以供以后参考。

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

输出

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

把名字变成张量

现在我们已经组织好了所有的名字,我们需要把它们变成张量来使用它们。

为了表示单个字母,我们使用大小为<1 x n_letters> 的 “one-hot vector”。一个独热向量被0填充,除了当前字母所以处是1。例如:"b" = <0 1 0 0 0 ...>.

为了组成一个单词,我们将一堆这样的单词连接到一个二维矩阵中<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])

创建网络

在autograd之前,在Torch中创建循环神经网络涉及到在几个时间步上克隆一层的参数。图层包含隐藏状态和梯度,现在完全由图形本身处理。这意味着你可以以一种非常“纯粹”的方式实现RNN,作为常规的前馈层。

这个RNN模块(主要是从the PyTorch for Torch users tutorial复制的)只有2个线性层,在输入和隐藏状态上操作,在输出之后有一个LogSoftmax层。

  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.h2o = nn.Linear(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.h2o(hidden)
  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)

为了提高效率,我们不想为每一步都创建一个新的张量,所以我们将使用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.9083, -2.9270, -2.9167, -2.9590, -2.9108, -2.8332, -2.8906, -2.8325,
  2. -2.8521, -2.9279, -2.8452, -2.8754, -2.8565, -2.9733, -2.9201, -2.8233,
  3. -2.9298, -2.8624]], grad_fn=<LogSoftmaxBackward0>)

正如您所看到的,输出是一个<1 x 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))

输出

('Scottish', 15)

我们还需要一种快速获取训练示例(名称及其语言)的方法:

  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, '/ line =', line)

输出

  1. category = Chinese / line = Hou
  2. category = Scottish / line = Mckay
  3. category = Arabic / line = Cham
  4. category = Russian / line = V'Yurkov
  5. category = Irish / line = O'Keeffe
  6. category = French / line = Belrose
  7. category = Spanish / line = Silva
  8. category = Japanese / line = Fuchida
  9. category = Greek / line = Tsahalis
  10. category = Korean / line = Chang

训练网络

现在训练这个网络所需要做的就是给它看一堆例子,让它猜测,然后告诉它是否错了。

对于损失函数nn.NLLLoss是合适的,因为RNN的最后一层是nn.LogSoftmax.

criterion = nn.NLLLoss()

每个训练循环将:

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

现在我们只需要用一堆例子来运行它。由于train函数返回输出和损失,我们可以打印它的猜测并跟踪损失以便绘制。由于有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 33s) 2.6379 Horigome / Japanese ✓
  2. 10000 10% (1m 5s) 2.0172 Miazga / Japanese ✗ (Polish)
  3. 15000 15% (1m 39s) 0.2680 Yukhvidov / Russian ✓
  4. 20000 20% (2m 12s) 1.8239 Mclaughlin / Irish ✗ (Scottish)
  5. 25000 25% (2m 45s) 0.6978 Banh / Vietnamese ✓
  6. 30000 30% (3m 18s) 1.7433 Machado / Japanese ✗ (Portuguese)
  7. 35000 35% (3m 51s) 0.0340 Fotopoulos / Greek ✓
  8. 40000 40% (4m 23s) 1.4637 Quirke / Irish ✓
  9. 45000 45% (4m 57s) 1.9018 Reier / French ✗ (German)
  10. 50000 50% (5m 30s) 0.9174 Hou / Chinese ✓
  11. 55000 55% (6m 2s) 1.0506 Duan / Vietnamese ✗ (Chinese)
  12. 60000 60% (6m 35s) 0.9617 Giang / Vietnamese ✓
  13. 65000 65% (7m 9s) 2.4557 Cober / German ✗ (Czech)
  14. 70000 70% (7m 42s) 0.8502 Mateus / Portuguese ✓
  15. 75000 75% (8m 14s) 0.2750 Hamilton / Scottish ✓
  16. 80000 80% (8m 47s) 0.7515 Maessen / Dutch ✓
  17. 85000 85% (9m 20s) 0.0912 Gan / Chinese ✓
  18. 90000 90% (9m 53s) 0.1190 Bellomi / Italian ✓
  19. 95000 95% (10m 26s) 0.0137 Vozgov / Russian ✓
  20. 100000 100% (10m 59s) 0.7808 Tong / Vietnamese ✓

绘制结果

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

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

输出

[<matplotlib.lines.Line2D object at 0x7f16606095a0>]

评估结果

为了了解网络在不同类别上的表现如何,我们将创建一个混淆矩阵,表示网络猜测(列)的每种语言(行)。为了计算混淆矩阵,使用evaluate(),在网络中运行一堆样本,这与 train() 去掉反向传播相同。

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

输出

  1. /var/lib/jenkins/workspace/intermediate_source/char_rnn_classification_tutorial.py:445: UserWarning:
  2. FixedFormatter should only be used together with FixedLocator
  3. /var/lib/jenkins/workspace/intermediate_source/char_rnn_classification_tutorial.py:446: UserWarning:
  4. FixedFormatter should only be used together with FixedLocator

你可以从主轴上挑出亮点,显示它猜错了哪些语言,例如中文猜错了韩语,西班牙语猜错了意大利语。它似乎在希腊语上表现得很好,而在英语上表现得很差(可能是因为与其他语言重叠)。

运行用户输入

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

输出

  1. > Dovesky
  2. (-0.57) Czech
  3. (-0.97) Russian
  4. (-3.43) English
  5. > Jackson
  6. (-1.02) Scottish
  7. (-1.49) Russian
  8. (-1.96) English
  9. > Satoshi
  10. (-0.42) Japanese
  11. (-1.70) Polish
  12. (-2.74) Italian

in the Practical PyTorch repo中脚本的最终版本将上述代码拆分为几个文件:

  • 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输出。

练习

尝试使用不同的数据集 -> 类别,例如:

  • 任何单词->语言
  • 名字->性别
  • 角色名称->作家
  • 页面标题 -> 博客或社交新闻网站子版块

使用一个更大的和/或更好的形状网络,可以获得更好的结果

  • 添加更多线性图层
  • 试试 nn.LSTM nn.GRU 网络层
  • 将这些RNNs组合成一个更高级的网络

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/438306
推荐阅读
相关标签
  

闽ICP备14008679号