注意
按一下此處以下載完整的範例程式碼
從頭開始的 NLP:使用字元級 RNN 產生名稱¶
建立於:2017 年 3 月 24 日 | 最後更新:2024 年 10 月 21 日 | 最後驗證:2024 年 11 月 05 日
本教學是三部分系列的一部分
這是我們關於「從頭開始的 NLP」的三個教學中的第二個。在第一個教學中,我們使用 RNN 將名稱分類到其原始語言。這次我們將反過來從語言中產生名稱。
> 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
我們仍然手動製作一個具有幾個線性層的小型 RNN。最大的不同在於,我們不是在讀取名稱的所有字母後預測類別,而是輸入一個類別並一次輸出一個字母。遞迴地預測字元以形成語言(這也可以用單詞或其他更高階的結構來完成)通常被稱為「語言模型」。
建議閱讀
我假設您至少已安裝 PyTorch,了解 Python,並了解張量
https://pytorch.dev.org.tw/ 適用於安裝說明
使用 PyTorch 進行深度學習:60 分鐘速成課程,以開始使用 PyTorch
透過範例學習 PyTorch,以獲得廣泛而深入的概述
適用於前 Torch 使用者的 PyTorch,如果您是前 Lua Torch 使用者
了解 RNN 及其工作原理也很有用
遞迴神經網路令人難以置信的有效性顯示了一堆真實生活範例
了解 LSTM 網路特別是關於 LSTM,但通常也提供有關 RNN 的資訊
我也建議之前的教學,從頭開始的 NLP:使用字元級 RNN 對名稱進行分類
準備資料¶
注意
從此處下載資料並將其解壓縮到目前目錄。
請參閱上一個教學以了解此過程的更多詳細資訊。簡而言之,有許多純文字檔案 data/names/[Language].txt
,每行一個名稱。我們將行分割成陣列,將 Unicode 轉換為 ASCII,並最終得到一個字典 {language: [names ...]}
。
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):
with open(filename, encoding='utf-8') as some_file:
return [unicodeToAscii(line.strip()) for line in some_file]
# 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 ['Arabic', 'Chinese', 'Czech', 'Dutch', 'English', 'French', 'German', 'Greek', 'Irish', 'Italian', 'Japanese', 'Korean', 'Polish', 'Portuguese', 'Russian', 'Scottish', 'Spanish', 'Vietnamese']
O'Neal
建立網路¶
此網路使用類別張量的額外參數擴充了 上一個教學的 RNN,該張量與其他張量連接在一起。類別張量是一個單熱向量,就像字母輸入一樣。
我們將把輸出解釋為下一個字母的機率。在取樣時,最可能的輸出字母會被用作下一個輸入字母。
我新增了第二個線性層 o2o
(在組合隱藏層和輸出層之後),以便為其提供更多功能。還有一個 dropout 層,它以給定的機率隨機將其輸入的部分歸零(此處為 0.1),通常用於模糊輸入以防止過擬合。在這裡,我們在網路的末端使用它,以便有目的地增加一些混亂並增加取樣多樣性。

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)
訓練¶
為訓練做準備¶
首先,輔助函數取得 (類別,行) 的隨機配對
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
對於每個時間步(即,對於訓練單詞中的每個字母),網路的輸入將為 (category, current letter, hidden state)
,輸出將為 (next letter, next hidden state)
。因此,對於每個訓練集,我們需要類別、一組輸入字母和一組輸出/目標字母。
由於我們正在預測每個時間步從目前字母開始的下一個字母,因此字母配對是行中連續字母的群組 - 例如,對於 "ABCD<EOS>"
,我們將建立(“A”,“B”),(“B”,“C”),(“C”,“D”),(“D”,“EOS”)。

類別張量 (category tensor) 是一個大小為 <1 x n_categories>
的 one-hot 張量。在訓練時,我們會在每個時間步 (timestep) 將它餵給網路 - 這是一個設計選擇,它也可以被包含在初始隱藏狀態 (initial hidden state) 中,或使用其他策略。
# 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
函式,它會提取一個隨機的 (類別, 行) 配對,並將它們轉換成所需的 (類別, 輸入, 目標) 張量。
# 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
訓練網路¶
與僅使用最後一個輸出的分類不同,我們在每個步驟都進行預測,因此我們在每個步驟都計算損失 (loss)。
Autograd 的神奇之處在於,您可以簡單地將每個步驟的這些損失加總,並在最後呼叫 backward。
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 = torch.Tensor([0]) # you can also just simply use ``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_(p.grad.data, alpha=-learning_rate)
return output, loss.item() / input_line_tensor.size(0)
為了追蹤訓練花費的時間,我添加了一個 timeSince(timestamp)
函式,它會回傳一個人類可讀的字串。
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)
訓練與往常一樣 - 多次呼叫 train 函數並等待幾分鐘,每 print_every
個範例印出目前時間和損失,並將每 plot_every
個範例的平均損失儲存在 all_losses
中,以便稍後繪圖。
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
0m 29s (5000 5%) 3.1506
1m 0s (10000 10%) 2.5070
1m 31s (15000 15%) 3.3047
2m 1s (20000 20%) 2.4247
2m 31s (25000 25%) 2.6406
3m 1s (30000 30%) 2.0266
3m 31s (35000 35%) 2.6520
4m 0s (40000 40%) 2.4261
4m 31s (45000 45%) 2.2302
5m 1s (50000 50%) 1.6496
5m 31s (55000 55%) 2.7101
6m 0s (60000 60%) 2.5396
6m 31s (65000 65%) 2.5978
7m 1s (70000 70%) 1.6029
7m 30s (75000 75%) 0.9634
8m 0s (80000 80%) 3.0950
8m 29s (85000 85%) 2.0512
8m 59s (90000 90%) 2.5302
9m 29s (95000 95%) 3.2365
9m 59s (100000 100%) 1.7113
繪製損失¶
從 all_losses 繪製歷史損失可以顯示網路的學習情況
import matplotlib.pyplot as plt
plt.figure()
plt.plot(all_losses)

[<matplotlib.lines.Line2D object at 0x7f976704c3d0>]
取樣網路¶
為了取樣,我們給網路一個字母,並詢問下一個字母是什麼,將其作為下一個字母餵入,並重複此過程,直到 EOS token (結束符記) 為止。
為輸入類別、起始字母和空的隱藏狀態建立張量。
使用起始字母建立一個字串
output_name
。直到最大輸出長度,
將目前的字母餵給網路。
從最高輸出取得下一個字母,以及下一個隱藏狀態。
如果字母是 EOS,則在此停止。
如果是一個常規字母,則添加到
output_name
並繼續。
回傳最終名稱。
注意
另一種策略是,不必給定起始字母,而是在訓練中包含一個 “字串開始” token,並讓網路選擇自己的起始字母。
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')
Rovaki
Uarinovev
Shinan
Gerter
Eeren
Roune
Santera
Paneraz
Allan
Chin
Han
Ion
練習¶
嘗試使用不同的 類別 -> 行 的資料集,例如
虛構系列 -> 角色名稱
詞性 -> 單字
國家 -> 城市
使用 “句子開始” token,以便在取樣時無需選擇起始字母
使用更大和/或形狀更好的網路來獲得更好的結果
嘗試使用
nn.LSTM
和nn.GRU
層將多個這些 RNN 組合為更高等級的網路
腳本的總執行時間: ( 9 分鐘 59.492 秒)