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

2025-06-18 17:15 更新

在自然语言处理(NLP)领域,字符级循环神经网络(char-RNN)是一种强大的工具,可以用于对文本数据进行建模和分类。本教程教你如何从头开始构建和训练一个字符级 RNN 模型,用于对姓氏进行分类。

一、准备数据

我们将使用包含来自 18 种不同语言的姓氏的数据集。这些数据存储在多个文本文件中,每个文件对应一种语言。我们需要将这些数据加载到内存中,并进行预处理。

1. 加载数据文件

  1. from io import open
  2. import glob
  3. import os
  4. def findFiles(path):
  5. return glob.glob(path)
  6. print(findFiles('data/names/*.txt')) # 查找所有数据文件

2. 将 Unicode 转换为 ASCII

  1. import unicodedata
  2. import string
  3. all_letters = string.ascii_letters + " .,;'"
  4. n_letters = len(all_letters)
  5. def unicodeToAscii(s):
  6. return ''.join(
  7. c for c in unicodedata.normalize('NFD', s)
  8. if unicodedata.category(c) != 'Mn' and c in all_letters
  9. )
  10. print(unicodeToAscii('Ślusàrski')) # 测试转换功能

3. 构建类别行字典

  1. category_lines = {}
  2. all_categories = []
  3. def readLines(filename):
  4. lines = open(filename, encoding='utf-8').read().strip().split('\n')
  5. return [unicodeToAscii(line) for line in lines]
  6. for filename in findFiles('data/names/*.txt'):
  7. category = os.path.splitext(os.path.basename(filename))[0]
  8. all_categories.append(category)
  9. lines = readLines(filename)
  10. category_lines[category] = lines
  11. n_categories = len(all_categories)
  12. print(category_lines['Italian'][:5]) # 查看意大利姓氏的前 5 个示例

二、将名称转换为张量

为了将名称输入到神经网络中,我们需要将字符转换为张量。我们使用 one-hot 编码来表示每个字符。

  1. import torch
  2. def letterToIndex(letter):
  3. return all_letters.find(letter)
  4. def letterToTensor(letter):
  5. tensor = torch.zeros(1, n_letters)
  6. tensor[0][letterToIndex(letter)] = 1
  7. return tensor
  8. def lineToTensor(line):
  9. tensor = torch.zeros(len(line), 1, n_letters)
  10. for li, letter in enumerate(line):
  11. tensor[li][0][letterToIndex(letter)] = 1
  12. return tensor
  13. print(letterToTensor('J')) # 测试单个字符转换
  14. print(lineToTensor('Jones').size()) # 测试整个名称转换

三、构建字符级 RNN 模型

我们将构建一个字符级 RNN 模型,用于根据姓氏的拼写预测其来源。

  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. 准备训练数据

  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)

2. 定义训练函数

  1. criterion = nn.NLLLoss()
  2. learning_rate = 0.005
  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. for p in rnn.parameters():
  11. p.data.add_(-learning_rate, p.grad.data)
  12. return output, loss.item()

3. 进行训练

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

五、评估模型

1. 绘制训练损失曲线

  1. import matplotlib.pyplot as plt
  2. plt.figure()
  3. plt.plot(all_losses)
  4. plt.title("Training Loss Curve")
  5. plt.xlabel("Iteration")
  6. plt.ylabel("Loss")
  7. plt.show()

2. 构建混淆矩阵

  1. confusion = torch.zeros(n_categories, n_categories)
  2. n_confusion = 10000
  3. def evaluate(line_tensor):
  4. hidden = rnn.initHidden()
  5. for i in range(line_tensor.size()[0]):
  6. output, hidden = rnn(line_tensor[i], hidden)
  7. return output
  8. for i in range(n_confusion):
  9. category, line, category_tensor, line_tensor = randomTrainingExample()
  10. output = evaluate(line_tensor)
  11. guess, guess_i = categoryFromOutput(output)
  12. category_i = all_categories.index(category)
  13. confusion[category_i][guess_i] += 1
  14. for i in range(n_categories):
  15. confusion[i] = confusion[i] / confusion[i].sum()
  16. fig = plt.figure()
  17. ax = fig.add_subplot(111)
  18. cax = ax.matshow(confusion.numpy())
  19. fig.colorbar(cax)
  20. ax.set_xticklabels([''] + all_categories, rotation=90)
  21. ax.set_yticklabels([''] + all_categories)
  22. ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
  23. ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
  24. plt.show()

六、实际应用

现在,我们可以使用训练好的模型对新的姓氏进行分类。

  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. topv, topi = output.topk(n_predictions, 1, True)
  6. predictions = []
  7. for i in range(n_predictions):
  8. value = topv[0][i].item()
  9. category_index = topi[0][i].item()
  10. print('(%.2f) %s' % (value, all_categories[category_index]))
  11. predictions.append([value, all_categories[category_index]])
  12. predict('Dovesky')
  13. predict('Jackson')
  14. predict('Satoshi')

通过本教程,你学会了如何使用 PyTorch 构建和训练字符级 RNN 模型,用于对姓氏进行分类。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号