作者: Sean Robertson
這是我們關(guān)于“NLP From Scratch”的三個教程中的第二個。 在<cite>第一個教程< / intermediate / char_rnn_classification_tutorial ></cite> 中,我們使用了 RNN 將名稱分類為來源語言。 這次,我們將轉(zhuǎn)過來并使用語言生成名稱。
> python sample.py Russian RUS
Rovakov
Uantov
Shavakov
> python sample.py German GER
Gerren
Ereng
Rosher
> python sample.py Spanish SPA
Salla
Parer
Allan
> python sample.py Chinese CHI
Chan
Hang
Iun
我們?nèi)栽谑止ぶ谱鲙в幸恍┚€性層的小型 RNN。 最大的區(qū)別在于,我們無需輸入名稱中的所有字母即可預測類別,而是輸入類別并一次輸出一個字母。 反復預測字符以形成語言(這也可以用單詞或其他高階結(jié)構(gòu)來完成)通常稱為“語言模型”。
推薦讀物:
我假設(shè)您至少已經(jīng)安裝了 PyTorch,了解 Python 和了解 Tensors:
了解 RNN 及其工作方式也將很有用:
我還建議上一個教程從頭開始進行 NLP:使用字符級 RNN 對名稱進行分類
Note
從的下載數(shù)據(jù),并將其提取到當前目錄。
有關(guān)此過程的更多詳細信息,請參見上一教程。 簡而言之,有一堆純文本文件data/names/[Language].txt
,每行都有一個名稱。 我們將行分割成一個數(shù)組,將 Unicode 轉(zhuǎn)換為 ASCII,最后得到一個字典{language: [names ...]}
。
from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os
import unicodedata
import string
all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1 # Plus EOS marker
def findFiles(path): return glob.glob(path)
## 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
)
## 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]
## Build the category_lines dictionary, a list of lines per category
category_lines = {}
all_categories = []
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)
if n_categories == 0:
raise RuntimeError('Data not found. Make sure that you downloaded data '
'from https://download.pytorch.org/tutorial/data.zip and extract it to '
'the current directory.')
print('# categories:', n_categories, all_categories)
print(unicodeToAscii("O'Néàl"))
出:
## categories: 18 ['French', 'Czech', 'Dutch', 'Polish', 'Scottish', 'Chinese', 'English', 'Italian', 'Portuguese', 'Japanese', 'German', 'Russian', 'Korean', 'Arabic', 'Greek', 'Vietnamese', 'Spanish', 'Irish']
O'Neal
該網(wǎng)絡(luò)使用最后一個教程的 RNN 擴展了,并為類別張量附加了一個參數(shù),該參數(shù)與其他張量串聯(lián)在一起。 類別張量是一個熱向量,就像字母輸入一樣。
我們將輸出解釋為下一個字母的概率。 采樣時,最有可能的輸出字母用作下一個輸入字母。
我添加了第二個線性層o2o
(將隱藏和輸出結(jié)合在一起之后),以使它具有更多的肌肉可以使用。 還有一個輟學層,以給定的概率(此處為 0.1)將輸入的部分隨機歸零,通常用于模糊輸入以防止過擬合。 在這里,我們在網(wǎng)絡(luò)的末端使用它來故意添加一些混亂并增加采樣種類。
import torch
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(n_categories + input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
self.o2o = nn.Linear(hidden_size + output_size, output_size)
self.dropout = nn.Dropout(0.1)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, category, input, hidden):
input_combined = torch.cat((category, input, hidden), 1)
hidden = self.i2h(input_combined)
output = self.i2o(input_combined)
output_combined = torch.cat((hidden, output), 1)
output = self.o2o(output_combined)
output = self.dropout(output)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return torch.zeros(1, self.hidden_size)
首先,helper 函數(shù)獲取隨機對(類別,行):
import random
## Random item from a list
def randomChoice(l):
return l[random.randint(0, len(l) - 1)]
## Get a random category and random line from that category
def randomTrainingPair():
category = randomChoice(all_categories)
line = randomChoice(category_lines[category])
return category, line
對于每個時間步(即,對于訓練詞中的每個字母),網(wǎng)絡(luò)的輸入將為(category, current letter, hidden state)
,而輸出將為(next letter, next hidden state)
。 因此,對于每個訓練集,我們都需要類別,一組輸入字母和一組輸出/目標字母。
由于我們正在預測每個時間步中當前字母的下一個字母,因此字母對是該行中連續(xù)字母的組-例如 對于"ABCD<EOS>"
,我們將創(chuàng)建(“ A”,“ B”),(“ B”,“ C”),(“ C”,“ D”),(“ D”,“ EOS”)。
類別張量是大小為<1 x n_categories>
的一熱張量。 訓練時,我們會隨時隨地將其饋送到網(wǎng)絡(luò)中-這是一種設(shè)計選擇,它可能已被包含為初始隱藏狀態(tài)或某些其他策略的一部分。
## One-hot vector for category
def categoryTensor(category):
li = all_categories.index(category)
tensor = torch.zeros(1, n_categories)
tensor[0][li] = 1
return tensor
## One-hot matrix of first to last letters (not including EOS) for input
def inputTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li in range(len(line)):
letter = line[li]
tensor[li][0][all_letters.find(letter)] = 1
return tensor
## LongTensor of second letter to end (EOS) for target
def targetTensor(line):
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
letter_indexes.append(n_letters - 1) # EOS
return torch.LongTensor(letter_indexes)
為了方便訓練,我們將使用randomTrainingExample
函數(shù)來提取隨機(類別,行)對,并將其轉(zhuǎn)換為所需的(類別,輸入,目標)張量。
## Make category, input, and target tensors from a random category, line pair
def randomTrainingExample():
category, line = randomTrainingPair()
category_tensor = categoryTensor(category)
input_line_tensor = inputTensor(line)
target_line_tensor = targetTensor(line)
return category_tensor, input_line_tensor, target_line_tensor
與僅使用最后一個輸出的分類相反,我們在每個步驟進行預測,因此在每個步驟都計算損失。
autograd 的神奇之處在于,您可以簡單地將每一步的損失相加,然后在末尾調(diào)用。
criterion = nn.NLLLoss()
learning_rate = 0.0005
def train(category_tensor, input_line_tensor, target_line_tensor):
target_line_tensor.unsqueeze_(-1)
hidden = rnn.initHidden()
rnn.zero_grad()
loss = 0
for i in range(input_line_tensor.size(0)):
output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
l = criterion(output, target_line_tensor[i])
loss += l
loss.backward()
for p in rnn.parameters():
p.data.add_(-learning_rate, p.grad.data)
return output, loss.item() / input_line_tensor.size(0)
為了跟蹤訓練需要多長時間,我添加了一個timeSince(timestamp)
函數(shù),該函數(shù)返回人類可讀的字符串:
import time
import math
def timeSince(since):
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
訓練照常進行-召集訓練多次,等待幾分鐘,每print_every
個示例打印當前時間和損失,并在all_losses
中將每個plot_every
實例的平均損失存儲下來,以便以后進行繪圖。
rnn = RNN(n_letters, 128, n_letters)
n_iters = 100000
print_every = 5000
plot_every = 500
all_losses = []
total_loss = 0 # Reset every plot_every iters
start = time.time()
for iter in range(1, n_iters + 1):
output, loss = train(*randomTrainingExample())
total_loss += loss
if iter % print_every == 0:
print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))
if iter % plot_every == 0:
all_losses.append(total_loss / plot_every)
total_loss = 0
Out:
0m 21s (5000 5%) 2.7607
0m 41s (10000 10%) 2.8047
1m 0s (15000 15%) 3.8541
1m 19s (20000 20%) 2.1222
1m 39s (25000 25%) 3.7181
1m 58s (30000 30%) 2.6274
2m 17s (35000 35%) 2.4538
2m 37s (40000 40%) 1.3385
2m 56s (45000 45%) 2.1603
3m 15s (50000 50%) 2.2497
3m 35s (55000 55%) 2.7588
3m 54s (60000 60%) 2.3754
4m 13s (65000 65%) 2.2863
4m 33s (70000 70%) 2.3610
4m 52s (75000 75%) 3.1793
5m 11s (80000 80%) 2.3203
5m 31s (85000 85%) 2.5548
5m 50s (90000 90%) 2.7351
6m 9s (95000 95%) 2.7740
6m 29s (100000 100%) 2.9683
繪制 all_losses 的歷史損失可顯示網(wǎng)絡(luò)學習情況:
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.figure()
plt.plot(all_losses)
為了示例,我們給網(wǎng)絡(luò)一個字母,詢問下一個字母是什么,將其作為下一個字母輸入,并重復直到 EOS 令牌。
output_name
Note
不必給它起一個開始字母,另一種策略是在訓練中包括一個“字符串開始”令牌,并讓網(wǎng)絡(luò)選擇自己的開始字母。
max_length = 20
## Sample from a category and starting letter
def sample(category, start_letter='A'):
with torch.no_grad(): # no need to track history in sampling
category_tensor = categoryTensor(category)
input = inputTensor(start_letter)
hidden = rnn.initHidden()
output_name = start_letter
for i in range(max_length):
output, hidden = rnn(category_tensor, input[0], hidden)
topv, topi = output.topk(1)
topi = topi[0][0]
if topi == n_letters - 1:
break
else:
letter = all_letters[topi]
output_name += letter
input = inputTensor(letter)
return output_name
## Get multiple samples from one category and multiple starting letters
def samples(category, start_letters='ABC'):
for start_letter in start_letters:
print(sample(category, start_letter))
samples('Russian', 'RUS')
samples('German', 'GER')
samples('Spanish', 'SPA')
samples('Chinese', 'CHI')
Out:
Rovakovak
Uariki
Sakilok
Gare
Eren
Rour
Salla
Pare
Alla
Cha
Honggg
Iun
腳本的總運行時間:(6 分鐘 29.292 秒)
Download Python source code: char_rnn_generation_tutorial.py
Download Jupyter notebook: char_rnn_generation_tutorial.ipynb
更多建議: