原文: https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
作者: Sean Robertson
我們將構(gòu)建和訓(xùn)練基本的字符級 RNN 對單詞進(jìn)行分類。 本教程與以下兩個教程一起,展示了如何“從頭開始”進(jìn)行 NLP 建模的預(yù)處理數(shù)據(jù),特別是不使用 <cite>torchtext</cite> 的許多便利功能,因此您可以了解如何進(jìn)行 NLP 建模的預(yù)處理 在低水平上工作。
字符級 RNN 將單詞作為一系列字符讀取-在每個步驟輸出預(yù)測和“隱藏狀態(tài)”,將其先前的隱藏狀態(tài)輸入到每個下一步。 我們將最終的預(yù)測作為輸出,即單詞屬于哪個類別。
具體來說,我們將訓(xùn)練來自 18 種起源語言的數(shù)千種姓氏,并根據(jù)拼寫方式預(yù)測名稱的來源:
$ 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
推薦讀物:
我假設(shè)您至少已經(jīng)安裝了 PyTorch,了解 Python 和了解 Tensors:
了解 RNN 及其工作方式也將很有用:
注意:
從的下載數(shù)據(jù),并將其提取到當(dāng)前目錄。
data/names目錄中包含 18 個文本文件,名為“ [Language] .txt”。 每個文件包含一堆名稱,每行一個名稱,大多數(shù)都是羅馬化的(但我們?nèi)匀恍枰獜?Unicode 轉(zhuǎn)換為 ASCII)。
我們將得到一個字典,列出每種語言的名稱列表{language: [names ...]}
。 通用變量“類別”和“行”(在本例中為語言和名稱)用于以后的擴(kuò)展。
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)
得出:
['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
現(xiàn)在我們有了category_lines
,這是一個字典,將每個類別(語言)映射到行(名稱)列表。 我們還跟蹤了all_categories
(只是語言列表)和n_categories
,以供以后參考。
print(category_lines['Italian'][:5])
得出:
['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni']
現(xiàn)在我們已經(jīng)組織了所有名稱,我們需要將它們轉(zhuǎn)換為張量以使用它們。
為了表示單個字母,我們使用大小為<1 x n_letters>
;的“ one-hot vector”。 一個熱門向量用 0 填充,但當(dāng)前字母的索引處的數(shù)字為 1,例如 "b" = <0 1 0 0 0 ...>
。
為了制造一個單詞,我們將其中的一些連接成 2D 矩陣<line_length x 1 x n_letters>
。
額外的 1 維是因為 PyTorch 假設(shè)所有內(nèi)容都是批量的-我們在這里只使用 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 <line_length x 1 x n_letters>,
## 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())
得出:
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])
在進(jìn)行自動分級之前,在 Torch 中創(chuàng)建一個遞歸神經(jīng)網(wǎng)絡(luò)需要在多個時間步上克隆圖層的參數(shù)。 圖層保留了隱藏狀態(tài)和漸變,這些圖層現(xiàn)在完全由圖形本身處理。 這意味著您可以以非?!凹兇狻钡姆绞綄崿F(xiàn) RNN,作為常規(guī)的前饋層。
這個 RNN 模塊(主要從 PyTorch for Torch 用戶教程的復(fù)制)僅是 2 個線性層,它們在輸入和隱藏狀態(tài)下運行,輸出之后是 LogSoftmax 層。
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)
要運行此網(wǎng)絡(luò)的步驟,我們需要傳遞輸入(在本例中為當(dāng)前字母的張量)和先前的隱藏狀態(tài)(首先將其初始化為零)。 我們將返回輸出(每種語言的概率)和下一個隱藏狀態(tài)(我們將其保留用于下一步)。
input = letterToTensor('A')
hidden =torch.zeros(1, n_hidden)
output, next_hidden = rnn(input, hidden)
為了提高效率,我們不想為每個步驟創(chuàng)建一個新的 Tensor,因此我們將使用lineToTensor
而不是letterToTensor
并使用切片。 這可以通過預(yù)先計算一批張量來進(jìn)一步優(yōu)化。
input = lineToTensor('Albert')
hidden = torch.zeros(1, n_hidden)
output, next_hidden = rnn(input[0], hidden)
print(output)
得出:
tensor([[-2.9504, -2.8402, -2.9195, -2.9136, -2.9799, -2.8207, -2.8258, -2.8399,
-2.9098, -2.8815, -2.8313, -2.8628, -3.0440, -2.8689, -2.9391, -2.8381,
-2.9202, -2.8717]], grad_fn=<LogSoftmaxBackward>)
如您所見,輸出為<1 x n_categories>
張量,其中每個項目都是該類別的可能性(更高的可能性更大)。
在接受訓(xùn)練之前,我們應(yīng)該做一些輔助功能。 首先是解釋網(wǎng)絡(luò)的輸出,我們知道這是每個類別的可能性。 我們可以使用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))
得出:
('Chinese', 5)
我們還將需要一種快速的方法來獲取訓(xùn)練示例(名稱及其語言):
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)
得出:
category = Italian / line = Pastore
category = Arabic / line = Toma
category = Irish / line = Tracey
category = Portuguese / line = Lobo
category = Arabic / line = Sleiman
category = Polish / line = Sokolsky
category = English / line = Farr
category = Polish / line = Winogrodzki
category = Russian / line = Adoratsky
category = Dutch / line = Robert
現(xiàn)在,訓(xùn)練該網(wǎng)絡(luò)所需要做的就是向它展示大量示例,進(jìn)行猜測,并告訴它是否錯誤。
對于損失函數(shù),nn.NLLLoss
是適當(dāng)?shù)?,因?RNN 的最后一層是nn.LogSoftmax
。
criterion = nn.NLLLoss()
每個訓(xùn)練循環(huán)將:
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()
現(xiàn)在,我們只需要運行大量示例。 由于train
函數(shù)同時返回輸出和損失,因此我們可以打印其猜測并跟蹤繪制損失。 因為有 1000 個示例,所以我們僅打印每個print_every
示例,并對損失進(jìn)行平均。
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
得出:
5000 5% (0m 12s) 3.1806 Olguin / Irish ? (Spanish)
10000 10% (0m 21s) 2.1254 Dubnov / Russian ?
15000 15% (0m 29s) 3.1001 Quirke / Polish ? (Irish)
20000 20% (0m 38s) 0.9191 Jiang / Chinese ?
25000 25% (0m 46s) 2.3233 Marti / Italian ? (Spanish)
30000 30% (0m 54s) nan Amari / Russian ? (Arabic)
35000 35% (1m 3s) nan Gudojnik / Russian ?
40000 40% (1m 11s) nan Finn / Russian ? (Irish)
45000 45% (1m 20s) nan Napoliello / Russian ? (Italian)
50000 50% (1m 28s) nan Clark / Russian ? (Irish)
55000 55% (1m 37s) nan Roijakker / Russian ? (Dutch)
60000 60% (1m 46s) nan Kalb / Russian ? (Arabic)
65000 65% (1m 54s) nan Hanania / Russian ? (Arabic)
70000 70% (2m 3s) nan Theofilopoulos / Russian ? (Greek)
75000 75% (2m 11s) nan Pakulski / Russian ? (Polish)
80000 80% (2m 20s) nan Thistlethwaite / Russian ? (English)
85000 85% (2m 29s) nan Shadid / Russian ? (Arabic)
90000 90% (2m 37s) nan Finnegan / Russian ? (Irish)
95000 95% (2m 46s) nan Brannon / Russian ? (Irish)
100000 100% (2m 54s) nan Gomulka / Russian ? (Polish)
從all_losses
繪制歷史損失可顯示網(wǎng)絡(luò)學(xué)習(xí)情況:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.figure()
plt.plot(all_losses)
為了查看網(wǎng)絡(luò)在不同類別上的表現(xiàn)如何,我們將創(chuàng)建一個混淆矩陣,為每種實際語言(行)指示網(wǎng)絡(luò)猜測(列)哪種語言。 為了計算混淆矩陣,使用evaluate()
通過網(wǎng)絡(luò)運行一堆樣本,該樣本等于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()
您可以從主軸上挑出一些亮點,以顯示它猜錯了哪些語言,例如 中文(朝鮮語)和西班牙語(意大利語)。 它似乎與希臘語搭配得很好,與英語搭配得很差(可能是因為與其他語言重疊)。
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')
得出:
> Dovesky
(nan) Russian
(nan) Arabic
(nan) Korean
> Jackson
(nan) Russian
(nan) Arabic
(nan) Korean
> Satoshi
(nan) Russian
(nan) Arabic
(nan) Korean
實際 PyTorch 存儲庫中的腳本的最終版本將上述代碼分成幾個文件:
data.py
(加載文件)model.py
(定義 RNN)train.py
(進(jìn)行訓(xùn)練)predict.py
(使用命令行參數(shù)運行predict())server.py
(通過 bottle.py 將預(yù)測用作 JSON API)運行train.py
訓(xùn)練并保存網(wǎng)絡(luò)。
使用名稱運行predict.py
以查看預(yù)測:
$ python predict.py Hazaki
(-0.42) Japanese
(-1.39) Polish
(-3.51) Czech
nn.LSTM
和nn.GRU
層將多個這些 RNN 合并為更高級別的網(wǎng)絡(luò)腳本的總運行時間:(3 分 4.326 秒)
Download Python source code: char_rnn_classification_tutorial.py
Download Jupyter notebook: char_rnn_classification_tutorial.ipynb
由獅身人面像畫廊生成的畫廊
更多建議: