Pytorch系列教程-使用字符級RNN生成姓名

前言

本系列教程爲pytorch官網文檔翻譯。本文對應官網地址:https://pytorch.org/tutorials/intermediate/char_rnn_generation_tutorial.htmlhtml

系列教程總目錄傳送門:我是一個傳送門python

本系列教程對應的 jupyter notebook 能夠在個人Github倉庫下載:git

下載地址:https://github.com/Holy-Shine/Pytorch-notebookgithub

咱們仍然使用手工搭建的包含幾個線性層的小型RNN。與以前的預測姓名最大的區別是:它不是「閱讀」輸入的全部字符而後生成一個預測分類,而是輸入一個分類而後在每一個時間步生成一個字母。循環預測字母來造成一個語言的語句一般被視做語言模型網絡

1. 準備數據

數據下載通道: 點擊這裏下載數據集。解壓到當前工做目錄。app

就和上個預測姓名分類的教程同樣,咱們有一個姓名文件夾 data/names/[language].txt ,每一個姓名一行。咱們將它轉化爲一個 array, 轉爲ASCII字符,最後生成一個字典 {language: [name1, name2,...]}dom

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向量。性能

咱們將輸出解釋爲下一個字母的機率。採樣時,最可能的輸出字母用做下一個輸入字母。ui

同時,模型增長了第二個線性層(在隱藏層的輸出組合以後),從而加強其性能。後續一個 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
相關文章
相關標籤/搜索