Pytorch系列教程-使用字符級RNN對姓名進行分類

前言

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

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

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

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

1. 數據準備

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

data/names 文件夾下面包含18個名字形如 [language].txt的文件。每一個文件包含多條姓名,一個姓名一行。咱們在以後須要將其編碼格式(Unicode)轉化爲ASCII。app

經過下面的步驟,咱們能夠獲得一個數據字典,形如{language:[name1,name2,...]} ,字典的鍵爲語言,值爲一個列表,包含對應文件夾下面的全部姓名。用變量 categoryline 分別標識鍵值對dom

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
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 dictinary, 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)

out:函數

['data/names\\Arabic.txt', 'data/names\\Chinese.txt', 'data/names\\Czech.txt', 'data/names\\Dutch.txt', 'data/names\\English.txt', 'data/names\\French.txt', 'data/names\\German.txt', 'data/names\\Greek.txt', 'data/names\\Irish.txt', 'data/names\\Italian.txt', 'data/names\\Japanese.txt', 'data/names\\Korean.txt', 'data/names\\Polish.txt', 'data/names\\Portuguese.txt', 'data/names\\Russian.txt', 'data/names\\Scottish.txt', 'data/names\\Spanish.txt', 'data/names\\Vietnamese.txt']
Slusarski

如今咱們有了category_lines, 這是一個字典映射了每一個語言和對應的名字。咱們一樣記錄了 all_categories(一個包含全部語言的列表)和 n_categories 方便後續的引用ui

print(category_lines['Italian'][:5])

out: ['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni']編碼

2. 將姓名轉化爲張量

如今咱們將全部的姓名組織好了,咱們須要將他們轉化爲張量(Tensor)方便使用。

爲了表示單個字母,咱們使用 one-hot 表示方法(size:<1 x n_letters>) 。一個 one-hot 向量是全0(激活字母爲1)的向量。 例如:
"b"=<0,1,0,0,0,...,0>

因而每一個姓名能夠用形狀爲 <line_length x 1 x n_letters> 的 2D 矩陣表示。

額外的一個維度是爲了構建一個假的 batch(pytorch只接受mini_batch數據)

import torch

# Fine 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())

out:

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])

3. 構建網絡

autograd 出現前, 在Torch中建立一個循環神經網絡須要在每個時間步克隆層參數。網絡層持有一個隱藏狀態和梯度信息,而目前這些徹底交由計算圖自己來處理。這意味着你能本身用一個很純淨的方式來實現一個 RNN——僅僅使用一些常規的前饋層。

這個RNN模塊只有兩個線性層,以輸入和隱藏狀態爲輸入,LogsSoftmax 層爲輸出。

以下圖所示:

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)

爲了運行這個網絡,咱們須要傳遞輸入和前一層傳遞下來的隱藏狀態(初始化爲0)。咱們使用最後一層的輸出做爲預測的結果

input = letterToTensor('A')
hidden = torch.zeros(1, n_hidden)

output, next_hidden =  rnn(input, hidden)

out:

tensor([[-2.8338, -2.9645, -2.9535, -2.9355, -2.9281, -2.8521, -2.8352,
         -2.9544, -2.8516, -2.8932, -2.7696, -2.8142, -2.8888, -2.7888,
         -2.8991, -2.9971, -2.9783, -2.9278]])

正如你所看到的,輸出是<1 x n_categories>的Tensor,其中每一個項目都是該類別的可能性(越大表明可能性越高)。

4. 訓練

4.1 訓練準備

在進入訓練以前,咱們應該作一些輔助函數。第一個是解釋網絡的輸出,咱們知道這是每一個類別的可能性。這裏使用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))

out:

('Japanese', 10)

同時咱們還想快速得到一個訓練樣本(姓名及其所屬語言):

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)

out:

category =  Czech / line = Morava
category =  English / line = Linsby
category =  Dutch / line = Agteren
category =  Scottish / line = Mccallum
category =  German / line = Laurenz
category =  Chinese / line = Long
category =  Italian / line = Pittaluga
category =  Japanese / line = Sugitani
category =  Portuguese / line = Duarte
category =  French / line = Macon

4.2 訓練網絡

如今,訓練這個網絡所須要的只是展現一堆例子,讓它作出猜想,而後告訴它是否錯了。

對於損失函數的選擇,nn.NLLLoss是合適的,由於RNN的最後一層是nn.LogSoftmax

criterion = nn.NLLLoss()

每一個循環的訓練作了以下的事情:

  • 建立輸入和目標張量
  • 初始隱藏狀態置0
  • 讀取每一個字母和
    • 保持隱藏狀態給下一個字母
  • 比較最終輸出到目標
  • 反向傳播
  • 返回輸出和丟失
learning_rate = 0.005

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()
    
    for p in rnn.parameters():
        p.data.add_(-learning_rate, p.grad.data)
        
    return output, loss.item()

如今咱們只須要用一堆例子來運行它。因爲訓練函數同時返回輸出和損失,咱們能夠打印其猜想並跟蹤繪圖的損失。因爲有1000個示例,咱們只打印每一個print_every示例,並取平均損失。

import time
import math

n_iters = 100000
print_every = 5000
plot_every = 1000

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
    
    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))
        
    if iter%plot_every==0:
        all_losses.append(current_loss / plot_every)
        current_loss = 0

out:

5000 5% (0m 9s) 2.2742 Bazovski / Polish ✗ (Russian)
10000 10% (0m 17s) 2.8028 Rossum / Arabic ✗ (Dutch)
15000 15% (0m 24s) 0.5319 Tsahalis / Greek ✓
20000 20% (0m 32s) 1.9478 Ojeda / Spanish ✓
25000 25% (0m 40s) 3.0673 Salomon / Russian ✗ (Polish)
30000 30% (0m 47s) 1.7099 Hong / Chinese ✗ (Korean)
35000 35% (0m 55s) 1.6736 Ruaidh / Irish ✓
40000 40% (1m 3s) 0.0943 Cearbhall / Irish ✓
45000 45% (1m 10s) 1.6163 Severin / Dutch ✗ (French)
50000 50% (1m 18s) 0.1879 Horiatis / Greek ✓
55000 55% (1m 26s) 0.0733 Eliopoulos / Greek ✓
60000 60% (1m 34s) 0.8175 Pagani / Italian ✓
65000 65% (1m 41s) 0.4049 Murphy / Scottish ✓
70000 70% (1m 49s) 0.5367 Seo / Korean ✓
75000 75% (1m 58s) 0.4234 Brzezicki / Polish ✓
80000 80% (2m 6s) 0.8812 Ayugai / Japanese ✓
85000 85% (2m 13s) 1.4328 Guirguis / Greek ✗ (Arabic)
90000 90% (2m 21s) 0.3510 Dam / Vietnamese ✓
95000 95% (2m 29s) 0.0634 Teunissen / Dutch ✓
100000 100% (2m 37s) 0.4243 Laganas / Greek ✓

4.3 可視化結果

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
%matplotlib inline
plt.figure()
plt.plot(all_losses)

out:

5. 評估模型

爲了瞭解網絡在不一樣類別上的表現如何,咱們將建立一個混淆矩陣,指示每一個實際語言(行)網絡猜想的哪一種語言(列)。爲了計算混淆矩陣,使用evaluate()經過網絡運行一組樣本.

confusion = torch.zeros(n_categories, n_categories)
n_confusion = 10000

def evaluate(line_tensor):
    hidden = rnn.initHidden()
    
    for i in range(line_tensor.size()[0]):
        output,hidden = rnn(line_tensor[i], hidden)
    return output

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
    
for i in range(n_categories):
    confusion[i]/=(confusion[i].sum())
    
fig = plt.figure()

ax = fig.add_subplot(111)
cax = ax.matshow(confusion.numpy())
fig.colorbar(cax)

ax.set_xticklabels(['']+all_categories,rotation=90)
ax.set_yticklabels(['']+all_categories)

ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

plt.show()

out:

你能夠從主軸上挑出明亮的點,它們能夠顯示出錯誤猜想的語言,例如:韓語猜想爲漢語,意大利語猜想爲西班牙語。希臘語的表現彷佛很好,可是英語不好(多是由於與其餘語言的重疊較多)

相關文章
相關標籤/搜索