前言
本系列教程為pytorch官網文檔翻譯。本文對應官網地址:https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.html
系列教程總目錄傳送門:我是一個傳送門
本系列教程對應的 jupyter notebook 可以在我的Github倉庫下載:
我們仍然使用手工搭建的包含幾個線性層的小型RNN。與之前的預測姓名最大的區別是:它不是“閱讀”輸入的所有字符然后生成一個預測分類,而是輸入一個分類然后在每個時間步生成一個字母。循環預測字母來形成一個語言的語句通常被視作語言模型。
1. 准備數據
數據下載通道: 點擊這里下載數據集。解壓到當前工作目錄。
就和上個預測姓名分類的教程一樣,我們有一個姓名文件夾 data/names/[language].txt
,每個姓名一行。我們將它轉化為一個 array, 轉為ASCII字符,最后生成一個字典 {language: [name1, name2,...]}
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 http://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"))
out:
# categories: 18 ['Arabic', 'Chinese', 'Czech', 'Dutch', 'English', 'French', 'German', 'Greek', 'Irish', 'Italian', 'Japanese', 'Korean', 'Polish', 'Portuguese', 'Russian', 'Scottish', 'Spanish', 'Vietnamese']
O'Neal
2. 搭建網絡
新的網絡結果擴充了姓名識別的RNN網絡,它的輸入增加了一個分類Tensor,該張量同樣參與與其他輸入的結合(concatenate)。分類張量也是一個one-hot向量。
我們將輸出解釋為下一個字母的概率。采樣時,最可能的輸出字母用作下一個輸入字母。
同時,模型增加了第二個線性層(在隱藏層的輸出組合之后),從而增強其性能。后續一個 dropout 層,它隨機將輸入置0(這里的概率設置為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],dim=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)
3. 訓練
3.1 訓練准備
首先,輔助函數用來獲取(category, line)對:
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','E'),('E','EOS')。
用圖來表示如下:
分類張量是一個one-hot張量,大小為 <1 x n_categories>
。在訓練的每個時間步我們都將其作為輸入。這是眾多設計選擇的一個,它同樣可以作為初始隱藏狀態或其他策略的一部分。
# 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
函數來獲取一個隨機的 (category, line) 對,然后將其轉化為輸入要求的 (category, input, target) 張量
# 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
3.2 訓練網絡
與分類相反,分類僅僅使用最后一層輸出,這里我們使用每個時間步的輸出作為預測,所以我們需要計算每個時間步的損失
autograd 的魔力使你能夠簡單的將所有時間步的loss相加,然后在最后反向傳播。
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(timestep)
函數,該函數返回一個可讀字符串
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
樣本后打印損失,同時在每個 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
out:
0m 17s (5000 5%) 2.1339
0m 34s (10000 10%) 2.3110
0m 53s (15000 15%) 2.2874
1m 13s (20000 20%) 3.5956
1m 33s (25000 25%) 2.4674
1m 52s (30000 30%) 2.3219
2m 9s (35000 35%) 3.0257
2m 27s (40000 40%) 2.5090
2m 45s (45000 45%) 1.9921
3m 4s (50000 50%) 2.0124
3m 22s (55000 55%) 2.8580
3m 41s (60000 60%) 2.4451
3m 59s (65000 65%) 3.1174
4m 16s (70000 70%) 1.7301
4m 34s (75000 75%) 2.9455
4m 52s (80000 80%) 2.3166
5m 9s (85000 85%) 1.2998
5m 27s (90000 90%) 2.1184
5m 45s (95000 95%) 2.6679
6m 3s (100000 100%) 2.4100
3.3 打印損失
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline
plt.figure()
plt.plot(all_losses)
out:
4. 網絡示例
為了示例,我們給網絡輸入一個字母並詢問下一個字母是什么,下一個字母再作為下下個字母的預測輸入,直到輸出EOS token
- 創建輸入分類的Tensor, 初始字母和空的隱藏狀態
- 輸出
output_name
,包含初始的字母 - 最大輸出長度,
- 將當前字母輸入網絡
- 獲取最大可能輸出,和下一個的隱藏狀態
- 如果字母是EOS,則停止
- 如果是一般字母,則加到
output_name
,繼續
- 返回最后的姓名單詞
另一種策略是不需要給網絡決定一個初始字母,而是在訓練時包含字符串開始標記,並讓網絡選擇自己的初始字母
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('Irish', 'O')
out:
Ramanovov
Uarin
Shavani
Garen
Eren
Roure
Sangara
Pare
Allan
Ollang