1. 程式人生 > >PyTorch: RNN實戰詳解之分類名字

PyTorch: RNN實戰詳解之分類名字

本文從資料集到最終模型訓練過程詳細講解RNN,教程來自於作者Sean Robertson寫的教程,我根據原始文件,一步一步跑通了程式碼,下面是我的學習筆記。

任務描述

從機器學習的角度來說,這是個分類任務。具體來說,我們將從18種語言的原始語言中訓練幾千個名字,並根據測試集的名字來預測這個名字來自哪一種語言。資料集下載地址:https://download.pytorch.org/tutorial/data.zip
裡面包含18個名為“[Language] .txt”的文字檔案。每個檔案包含很多名字資料集,每行一個名字。每個檔案所包含的名字來自一種語言(比如中文、英文),所以資料集包含的18種語言代表18類。訓練的樣本是(名字,語言),當模型訓練後,輸入名字,預測此名字屬於哪一類(屬於那種語言)。

PyTorch之RNN實戰分類

本文采用PyTorch框架使用RNN進行資料分類。

資料預處理

首先解決編碼問題以及將類別放入python list。然後類別對應的名字以字典型別讀入,方面後面模型訓練使用。

from io import open
import glob
import unicodedata
import string

def findFiles(path):
    return glob.glob(path)

# 所有的英文字母加上五個標點符號" .,;'"。一個57個字元
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters) # 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 ) #print(unicodeToAscii('Ślusàrski'))
# Build the category_lines dictionary, 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('nlpdata/data/names/*.txt'): category = filename.split('/')[-1].split('.')[0] category = category.split('\\')[1] # 18種類別 all_categories.append(category) lines = readLines(filename) # category_lines:字典型別(類別: 名字list) category_lines[category] = lines n_categories = len(all_categories) print("all_letters: "+str(len(all_letters))) print("n_categories: "+str(n_categories)) print("category_lines:"+str(category_lines['Italian'][:5])) 輸出結果: all_letters: 57 n_categories: 18 category_lines:['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni'] Process finished with exit code 0

在PyTorch中,我們需要將名字資料轉換成Tensor才能在模型中讀入使用。在本文中,最小粒度為字元,意思是我們將名字裡面的每個字元都作為一個獨立的語言粒度來處理,為了數學化字元,我們這裡使用”one-hot vector”來表示,這裡每個字元被表示成<1 * 57>的向量。由於名字由多個字元組成,所以每個名字就被表示成了2D的矩陣<名字字元個數 * 1 * 57>。

import torch

# Find letter index from all_letters, e.g. "a" = 0
# 字母所在位置
def letterToIndex(letter):
    return all_letters.find(letter)

# Turn a letter into a <1 x n_letters> Tensor (one-hot vector)
def letterToTensor(letter):
    tensor = torch.zeros(1, n_letters)
    # One-hot encoding
    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())

輸出結果:
Columns 0 to 12 
    0     0     0     0     0     0     0     0     0     0     0     0     0
Columns 13 to 25 
    0     0     0     0     0     0     0     0     0     0     0     0     0
Columns 26 to 38 
    0     0     0     0     0     0     0     0     0     1     0     0     0
Columns 39 to 51 
    0     0     0     0     0     0     0     0     0     0     0     0     0
Columns 52 to 56 
    0     0     0     0     0
[torch.FloatTensor of size 1x57]

torch.Size([5, 1, 57])

Process finished with exit code 0

定義網路模型

這裡寫圖片描述

為了執行這個網路的一個步(step),我們需要傳入輸入(在我們的例子中,當前字母的張量)和一個先前的隱藏狀態(初始化為零)。 我們將返回輸出(每種語言的概率)和下一個隱藏狀態(我們為下一步保留)。

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 Variable(torch.zeros(1, self.hidden_size))

訓練網路

訓練過程如下:
1.建立輸入和目標張量
2.建立一個初始隱藏狀態(0初始化)
3.輸入該步字母然後保持該步的隱藏狀態,將此隱藏狀態和下一步的字母輸入一起組成下一步輸出
4.比較最終輸出結果和標記目標(類)
5.反向傳播(並且更新引數)
6.返回輸出和損失

為了看網路在不同類別上的表現如何,我們建立一個混淆矩陣。

完整程式碼

from io import open
import glob

def findFiles(path):
    return glob.glob(path)

#print(findFiles('nlpdata/data/names/*.txt'))

import unicodedata
import string

# 所有的英文字母
all_letters = string.ascii_letters + " .,;'"
n_letters = len(all_letters)

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

#print(unicodeToAscii('Ślusàrski'))

# Build the category_lines dictionary, 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('nlpdata/data/names/*.txt'):
    category = filename.split('/')[-1].split('.')[0]
    category = category.split('\\')[1]
    all_categories.append(category)
    lines = readLines(filename)
    category_lines[category] = lines

n_categories = len(all_categories)


import torch

# Find 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)
    # One-hot encoding
    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)
    #print(tensor)
    for li, letter in enumerate(line):
        tensor[li][0][letterToIndex(letter)] = 1
    return tensor

import torch.nn as nn
from torch.autograd import Variable
# Creating the network
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 Variable(torch.zeros(1, self.hidden_size))

# our model
n_hidden = 128
rnn = RNN(n_letters, n_hidden, n_categories)


# 類別
def categoryFromOutput(output):
    top_n, top_i = output.data.topk(1) # Tensor out of Variable with .data
    category_i = top_i[0][0]
    return all_categories[category_i], category_i

# loss function
criterion = nn.NLLLoss()

# Train loop
learning_rate = 0.005 # If you set this too high, it might explode. If too low, it might not learn

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

    # Add parameters' gradients to their values, multiplied by learning rate
    for p in rnn.parameters():
        p.data.add_(-learning_rate, p.grad.data)
    return output, loss.data[0]

# 隨機取樣訓練樣本對
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 = Variable(torch.LongTensor([all_categories.index(category)]))
    line_tensor = Variable(lineToTensor(line))
    return category, line, category_tensor, line_tensor



import time
import math

n_iters = 100000
print_every = 5000
plot_every = 1000

# Keep track of losses for plotting
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

    # Print iter number, loss, name and guess
    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))

    # Add current loss avg to list of losses
    if iter % plot_every == 0:
        all_losses.append(current_loss / plot_every)
        current_loss = 0

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)
plt.show()

# 矩陣
confusion = torch.zeros(n_categories, n_categories)
n_confusion = 10000

# Just return an output given a line
def evaluate(line_tensor):
    hidden = rnn.initHidden()

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

    return output

# Go through a bunch of examples and record which are correctly guessed
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

# Normalize by dividing every row by its sum
for i in range(n_categories):
    confusion[i] = confusion[i] / confusion[i].sum()

# Set up plot
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(confusion.numpy())
fig.colorbar(cax)

# Set up axes
ax.set_xticklabels([''] + all_categories, rotation=90)
ax.set_yticklabels([''] + all_categories)

# Force label at every tick
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

# sphinx_gallery_thumbnail_number = 2
plt.show()

每訓練1000次輸出loss:
這裡寫圖片描述

網路在不同類別上的表現:
這裡寫圖片描述

注意:PyTorch模組對Variables 進行操作,而不是直接對Tensors進行操作。所以轉換成Tensors後要用Variables封裝。

例一:
input = Variable(letterToTensor('A'))
hidden = Variable(torch.zeros(1, n_hidden))

output, next_hidden = rnn(input, hidden)

例二:
input = Variable(lineToTensor('Albert'))
hidden = Variable(torch.zeros(1, n_hidden))

output, next_hidden = rnn(input[0], hidden)