【PyTorch官方示例翻译&注释】从头开始NLP:使用字符级RNN对名称进行分类

NLP FROM SCRATCH: CLASSIFYING NAMES WITH A CHARACTER-LEVEL RNN

从头开始NLP:使用字符级RNN对名称进行分类

原文地址
https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html

作者:Sean Robertson

我们将建立和训练一个基本的字符级RNN来分类单词。字符级RNN将单词读取为一系列字符——在每一步输出一个预测和“隐藏状态”,并将之前的隐藏状态输入到下一步。我们将最终的预测作为输出,即单词属于哪个类。

具体来说,我们将训练来自18种语言的几千个姓氏,并根据拼写来预测一个名字来自哪种语言:

$ python predict.py Hinton
(-0.47) Scottish
(-1.52) English
(-3.57) Irish

$ python predict.py Schmidhuber
(-0.19) German
(-2.48) Czech
(-2.68) Dutch

推荐阅读:

我假设您至少安装了PyTorch,了解Python并理解张量:

  • https://pytorch.org/ 安装文档
  • Deep Learning with PyTorch: A 60 Minute Blitz 入门级的pytorch教材
  • Learning PyTorch with Examples 一个广泛和深入的概述
  • PyTorch for Former Torch Users 如果您是之前Lua Torch的用户

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

  • The Unreasonable Effectiveness of Recurrent Neural Networks shows a bunch of real life examples
  • Understanding LSTM Networks is about LSTMs specifically but also informative about RNNs in general

准备数据

注意

从此处下载数据并将其解压缩到当前目录

data/names目录中包含18个名为“[Language].txt”的文本文件。
每个文件包含一串名称,每行一个名称,大部分是罗马字母(但是我们仍然需要将Unicode转换为ASCII)。

最后,我们将得到每个语言的名称列表字典,{language: [names…]}。泛型变量“category”和“line”(在我们的例子中是语言和名称)用于以后的扩展。

from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os

def findFiles(path): return glob.glob(path)

print(findFiles('data/names/*.txt'))

import unicodedata
import string

all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)

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

print(unicodeToAscii('Ślusàrski'))

# Build the category_lines dictionary, a list of names per language
category_lines = {}
all_categories = []

# 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]

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)

Out:

['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']
Slusarski

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

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

Out:

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

把名字变成张量

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

为了表示单个字母,我们使用大小 <1 x n_letters>的独热向量(one-hot vector)。一个 one-hot vector 除了当前字母的索引为1外,其余都是0。"b" = <0 1 0 0 0 ...>.

为了生成一个单词,我们将这些元素加入到一个2D矩阵中 .

这个额外的1维是因为PyTorch假设所有东西都是成批的——这里我们使用的批大小是1。

import torch

# Find letter index from all_letters, e.g. "a" = 0
def letterToIndex(letter):
    return all_letters.find(letter)

# Just for demonstration, turn a letter into a <1 x n_letters> Tensor
def letterToTensor(letter):
    tensor = torch.zeros(1, n_letters)
    tensor[0][letterToIndex(letter)] = 1
    return tensor

# Turn a line into a ,
# or an array of one-hot letter vectors
def lineToTensor(line):
    tensor = torch.zeros(len(line), 1, n_letters)
    for li, letter in enumerate(line):
        tensor[li][0][letterToIndex(letter)] = 1
    return tensor

print(letterToTensor('J'))

print(lineToTensor('Jones').size())

Out:

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

创建一个网络

在autograd之前,在Torch中创建一个递归神经网络需要在几个时间步骤中克隆一个层的参数。图层包含隐藏状态和渐变,现在完全由图本身处理。这意味着您可以以一种非常“纯”的方式实现RNN,即常规的前馈层。

这个RNN模块(大部分复制自the PyTorch for Torch users tutorial)只有两个线性层,它们对输入和隐藏状态进行操作,输出之后是LogSoftmax层。

【PyTorch官方示例翻译&注释】从头开始NLP:使用字符级RNN对名称进行分类_第1张图片
https://i.imgur.com/Z2xbySO.png

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(input_size + hidden_size, hidden_size)
        self.i2o = nn.Linear(input_size + hidden_size, output_size)
        self.softmax = nn.LogSoftmax(dim=1)

    def forward(self, input, hidden):
        combined = torch.cat((input, hidden), 1)
        hidden = self.i2h(combined)
        output = self.i2o(combined)
        output = self.softmax(output)
        return output, hidden

    def initHidden(self):
        return torch.zeros(1, self.hidden_size)

n_hidden = 128
rnn = RNN(n_letters, n_hidden, n_categories)

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

input = letterToTensor('A')
hidden =torch.zeros(1, n_hidden)

output, next_hidden = rnn(input, hidden)

为了效率,我们不想每一步都创建一个新的张量,所以我们用线性张量(lineToTensor)代替字母张量(letterToTensor),用切片。这可以通过预计算张量批次来进一步优化。

input = lineToTensor('Albert')
hidden = torch.zeros(1, n_hidden)

output, next_hidden = rnn(input[0], hidden)
print(output)

Out:

tensor([[-2.9220, -2.9511, -2.9109, -2.9223, -2.9395, -2.9084, -2.9932, -2.9054,
         -2.8281, -2.7739, -2.8540, -2.8892, -2.8152, -2.7654, -2.9654, -2.9028,
         -2.9026, -2.9106]], grad_fn=)

可以看到输出是一个<1 x n_categories>张量,其中每一项都是该类别的可能性(越高越有可能)。

训练

预训练

在进行训练之前,我们应该做一些辅助方程。首先是解释神经网络的输出,我们知道这是每个类别的可能性。我们可以用张量 Tensor.topk得到最大值的索引:

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

print(categoryFromOutput(output))

Out:

('Arabic', 13)

我们也想要一个快速的方法来获得一个训练的例子(名字和它的语言):

import random

def randomChoice(l):
    return l[random.randint(0, len(l) - 1)]

def randomTrainingExample():
    category = randomChoice(all_categories)
    line = randomChoice(category_lines[category])
    category_tensor = torch.tensor([all_categories.index(category)], dtype=torch.long)
    line_tensor = lineToTensor(line)
    return category, line, category_tensor, line_tensor

for i in range(10):
    category, line, category_tensor, line_tensor = randomTrainingExample()
    print('category =', category, '/ line =', line)

Out:

category = Dutch / line = Tholberg
category = Irish / line = Murphy
category = Vietnamese / line = An
category = German / line = Von essen
category = Polish / line = Kijek
category = Scottish / line = Bell
category = Czech / line = Marik
category = Korean / line = Jeong
category = Korean / line = Choe
category = Portuguese / line = Alves

训练神经网络

现在,训练这个网络只需要给它看一堆例子,让它猜一猜,然后告诉它是不是错了。

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

criterion = nn.NLLLoss()

每一个训练循环将:

  • 创建输入和目标张量
  • 创建一个零初始隐藏层
  • 把每个文字读进去
    • 为下一个文字保留隐藏状态
  • 将最终输出与目标进行比较
  • 反向传播
  • 返回输出和损失
learning_rate = 0.005 # If you set this too high, it might explode. If too low, it might not learn

def train(category_tensor, line_tensor):
    hidden = rnn.initHidden()

    rnn.zero_grad()

    for i in range(line_tensor.size()[0]):
        output, hidden = rnn(line_tensor[i], hidden)

    loss = criterion(output, category_tensor)
    loss.backward()

    # Add parameters' gradients to their values, multiplied by learning rate
    for p in rnn.parameters():
        p.data.add_(-learning_rate, p.grad.data)

    return output, loss.item()

现在我们只需要用一些例子来运行它。由于train函数同时返回输出和损失,所以我们可以打印它的猜测值,并跟踪损失以便绘图。因为有1000个例子,所以我们只打印每个print_every例子,并取损失的平均值。

import time
import math

n_iters = 100000
print_every = 5000
plot_every = 1000



# Keep track of losses for plotting
current_loss = 0
all_losses = []

def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)

start = time.time()

for iter in range(1, n_iters + 1):
    category, line, category_tensor, line_tensor = randomTrainingExample()
    output, loss = train(category_tensor, line_tensor)
    current_loss += loss

    # Print iter number, loss, name and guess
    if iter % print_every == 0:
        guess, guess_i = categoryFromOutput(output)
        correct = '✓' if guess == category else '✗ (%s)' % category
        print('%d %d%% (%s) %.4f %s / %s %s' % (iter, iter / n_iters * 100, timeSince(start), loss, line, guess, correct))

    # Add current loss avg to list of losses
    if iter % plot_every == 0:
        all_losses.append(current_loss / plot_every)
        current_loss = 0

Out:

5000 5% (0m 8s) 2.7792 Verdon / Scottish ✗ (English)
10000 10% (0m 16s) 2.0748 Campos / Greek ✗ (Portuguese)
15000 15% (0m 25s) 2.0458 Kuang / Vietnamese ✗ (Chinese)
20000 20% (0m 33s) 1.1703 Nghiem / Vietnamese ✓
25000 25% (0m 42s) 2.6035 Boyle / English ✗ (Scottish)
30000 30% (0m 50s) 2.2823 Mozdzierz / Dutch ✗ (Polish)
35000 35% (0m 58s) nan Lagana / Irish ✗ (Italian)
40000 40% (1m 6s) nan Simonis / Irish ✗ (Dutch)
45000 45% (1m 14s) nan Nobunaga / Irish ✗ (Japanese)
50000 50% (1m 23s) nan Ingermann / Irish ✗ (English)
55000 55% (1m 31s) nan Govorin / Irish ✗ (Russian)
60000 60% (1m 39s) nan Janson / Irish ✗ (German)
65000 65% (1m 47s) nan Tsangaris / Irish ✗ (Greek)
70000 70% (1m 55s) nan Vlasenkov / Irish ✗ (Russian)
75000 75% (2m 3s) nan Needham / Irish ✗ (English)
80000 80% (2m 11s) nan Matsoukis / Irish ✗ (Greek)
85000 85% (2m 20s) nan Koo / Irish ✗ (Chinese)
90000 90% (2m 28s) nan Novotny / Irish ✗ (Czech)
95000 95% (2m 36s) nan Dubois / Irish ✗ (French)
100000 100% (2m 44s) nan Padovano / Irish ✗ (Italian)

绘制的结果

绘制all_loss的历史损失,显示网络学习:

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

plt.figure()
plt.plot(all_losses)

https://pytorch.org/tutorials/_images/sphx_glr_char_rnn_classification_tutorial_001.png

评估结果

要查看网络在不同类别上的表现如何,我们将创建一个混淆矩阵,表示网络猜测的每种实际语言(行)和列。为了计算混淆矩阵,我们在网络中运行了一组带有evaluate()的样本,它与减去backprop的train()相同。

# Keep track of correct guesses in a confusion matrix
confusion = torch.zeros(n_categories, n_categories)
n_confusion = 10000

# Just return an output given a line
def evaluate(line_tensor):
    hidden = rnn.initHidden()

    for i in range(line_tensor.size()[0]):
        output, hidden = rnn(line_tensor[i], hidden)

    return output

# Go through a bunch of examples and record which are correctly guessed
for i in range(n_confusion):
    category, line, category_tensor, line_tensor = randomTrainingExample()
    output = evaluate(line_tensor)
    guess, guess_i = categoryFromOutput(output)
    category_i = all_categories.index(category)
    confusion[category_i][guess_i] += 1

# Normalize by dividing every row by its sum
for i in range(n_categories):
    confusion[i] = confusion[i] / confusion[i].sum()

# Set up plot
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(confusion.numpy())
fig.colorbar(cax)

# Set up axes
ax.set_xticklabels([''] + all_categories, rotation=90)
ax.set_yticklabels([''] + all_categories)

# Force label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

# sphinx_gallery_thumbnail_number = 2
plt.show()

https://pytorch.org/tutorials/_images/sphx_glr_char_rnn_classification_tutorial_002.png

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

运行于用户输入

def predict(input_line, n_predictions=3):
    print('\n> %s' % input_line)
    with torch.no_grad():
        output = evaluate(lineToTensor(input_line))

        # Get top N categories
        topv, topi = output.topk(n_predictions, 1, True)
        predictions = []

        for i in range(n_predictions):
            value = topv[0][i].item()
            category_index = topi[0][i].item()
            print('(%.2f) %s' % (value, all_categories[category_index]))
            predictions.append([value, all_categories[category_index]])

predict('Dovesky')
predict('Jackson')
predict('Satoshi')

Out:

> Dovesky
(nan) English
(nan) Italian
(nan) Irish

> Jackson
(nan) English
(nan) Italian
(nan) Irish

> Satoshi
(nan) English
(nan) Italian
(nan) Irish

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

  • data.py (loads files)
  • model.py (defines the RNN)
  • train.py (runs training)
  • predict.py (runs predict() with command line arguments)
  • server.py (serve prediction as a JSON API with bottle.py)

Run train.py to train and save the network.

Run predict.py with a name to view predictions:

$ python predict.py Hazaki
(-0.42) Japanese
(-1.39) Polish
(-3.51) Czech

Run server.py and visit http://localhost:5533/Yourname to get JSON output of predictions.

练习Exercises

  • 尝试使用不同的数据集行->类别,例如:
    • 任何单词->语言
    • 姓名->性别
    • Character name -> writer
    • Page title -> blog or subreddit
  • 使用更大和/或形状更好的网络可以获得更好的结果
    • Add more linear layers(添加更多线性图层)
    • Try the nn.LSTM and nn.GRU layers
    • Combine multiple of these RNNs as a higher level network(将这些RNNs组合成一个更高级别的网络)

脚本总运行时间: ( 2 minutes 53.673 seconds)

你可能感兴趣的:(深度学习,NLP,PyTorch,deep,learning,RNN)