使用字符级的RNN做姓名分类

7 篇文章 0 订阅

原文:CLASSIFYING NAMES WITH A CHARACTER-LEVEL RNN

作者:Sean Robertson

翻译:Jerry

日期:2019-01-24

Preparing the Data

此处下载数据,将txt文件解压至同目录的data/names

数据集共有18个文本文件,命名规则是“[语种].txt”。文件内容每一行是一个姓名,许多是罗马字母(但是我们需要将其从Unicode转换为ASCII格式)

首先我们构建一个语种-姓名的字典 {languages: [names ... ]}。变量“category”和“line”对应文件的“语种”和“姓名”

from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os

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

print("data:", findFiles('data/names/*.txt'))

import unicodedata
import string

all_letters = string.ascii_letters + " .,:'"
n_letters = len(all_letters)


# 将Unicode字符串转换成ASCII: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
    )

print("Ślusàrski => " , unicodeToAscii("Ślusàrski"))

# 构建 category_lines 字典,每一种语言的名字列表
category_lines = {}
all_categories = []

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: ['data/names/Russian.txt', 'data/names/German.txt', 'data/names/Italian.txt', 'data/names/Portuguese.txt', 'data/names/French.txt', 'data/names/Czech.txt', 'data/names/Vietnamese.txt', 'data/names/Japanese.txt', 'data/names/English.txt', 'data/names/Scottish.txt', 'data/names/Korean.txt', 'data/names/Arabic.txt', 'data/names/Spanish.txt', 'data/names/Greek.txt', 'data/names/Chinese.txt', 'data/names/Irish.txt', 'data/names/Polish.txt', 'data/names/Dutch.txt']
Ślusàrski =>  Slusarski

现在我们有了category_lines,它保存了语种-姓名列表。同时我们也有all_categories,保存了语种列表,以及n_categories表示语种的数量

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

Out:

['Abandonato', 'Abatangelo', 'Abatantuono', 'Abate', 'Abategiovanni']

将名字转换成Tensor

我们现在有了结构化的名字数据,现在我们需要将其转换成Tensor才能使用

文本的表示有很多方法,这里我们使用“独热编码”(one-hot)表示一个字母。独热码是指维度是 <1 x n_letters> 的向量,向量所有位置上的值都是0,只有在对应字母的索引位置上的值是1。比如字母 b 在索引是1,则独热码为: [ 0 1 0 0 ... ]

为了表示一个名字,我们需要一个2D矩阵 <ling_length x 1 x n_letters>

这额外的 1 个维度被保留下来,是因为PyTorch假定所有东西都是批量的,我们只是使用了批量的大小为1

import torch

# 找到字母在字母表中的位置。比如 'a' = 0
def letterToIndex(letter):
    return all_letters.find(letter)

# 独热编码,一个 <1 x n_letters> 的Tensor
def letterToTensor(letter):
    tensor = torch.zeros(1, n_letters)
    tensor[0][letterToIndex(letter)] = 1
    return tensor

# 将一行文本转换成 <line_length x 1 x n_letters> 的Tensor
# 或者是一个独热码的数组
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])

构建网络

在进行autograd之前,我们需要使用PyTorch构建循环神经网络,在这神经网络中我们需要在一些时间步上共享参数。神经元保存了隐层状态和梯度,完全由计算图本身来处理。这意味着只需要以非常“纯粹”的方式实现RNN,就把它当做是前向传播中的一层

这个RNN模块只有两个线性层,分别操作输入和隐藏状态,得到输出后再经过LogSoftmax层

RNN的神经元结构如下:

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)

为了提高效率,我们不希望为每一个时间步都创建一个新的Tensor,所以我们使用 lineToTensor 而不是 letterToTensor。这可以被Tensor的批量预计算进一步的优化

input = lineToTensor('Albert')
hidden = torch.zeros(1, n_hidden)

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

print(output)

Out:

tensor([[-2.8619, -2.9139, -2.8839, -2.9897, -2.9166, -2.9055, -2.8508, -2.9507,
         -2.8785, -2.8848, -2.8242, -2.9322, -2.9182, -2.8118, -2.8402, -2.8435,
         -2.9021, -2.9372]], grad_fn=<LogSoftmaxBackward>)

训练网络

在训练之前,我们先构建几个函数。首先是从输出的归一化概率中提取出预测类标。我们使用 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:

('Greek', 13)

接着是从训练数据中随机取出一个样本(姓名和它的语种)

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 = Scottish / line = Boyle
category = Japanese / line = Tokuda
category = Japanese / line = Mishima
category = Italian / line = Ganza
category = Czech / line = Blazek
category = Scottish / line = Reid
category = Vietnamese / line = Bach
category = Portuguese / line = Henriques
category = Italian / line = Nave
category = Spanish / line = Fierro

现在训练这个神经网络只需要输入一些样本数据,让它进行预测,如果预测错了就告诉它(有监督学习)

对于损失函数,我们使用 nn.NLLLoss,因为RNN的最后一层是 nn.LogSoftmax

criterion = nn.NLLLoss()

每一个循环中,训练的步骤是:

  • 创建输入和真实值Tensor
  • 创建0初始的隐藏层状态
  • 读取一个字符,并且保存隐藏状态给下一个字符用
  • 对比输出和真实值
  • 反向传播
  • 返回输出和损失值
lr = 5*1e-3
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_(-lr, p.grad.data)
    return output, loss.item()
    

现在我们只需要在数据上跑起来即可。因为 train 函数返回的是输出和损失,所以我们能实时的看到训练过程中loss的变化,也可以画出来。因为我们有1000多个样本,所以我们每隔 print_every 个样本时就显示一次平均loss。

import time
import math

n_iters = 100000
print_every = 5000
plot_every = 1000


# 记录loss
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 8s) 4.5720 Weichert / German ✗ (Czech)
10000 10% (0m 16s) 2.8925 Mclellan / Scottish ✗ (English)
15000 15% (0m 24s) 1.0124 Miller / Scottish ✓
20000 20% (0m 32s) 0.9201 Hodowal / Czech ✓
25000 25% (0m 40s) 0.9193 Woo / Chinese ✗ (Korean)
30000 30% (0m 48s) 3.8676 Ling / Chinese ✗ (English)
35000 35% (0m 56s) 1.1872 Lennard / English ✓
40000 40% (1m 4s) 1.7544 Spiker / Czech ✗ (Dutch)
45000 45% (1m 12s) 1.0265 Totah / Arabic ✓
50000 50% (1m 19s) 0.2883 Dang / Vietnamese ✓
55000 55% (1m 27s) 0.6902 Sarno / Italian ✓
60000 60% (1m 34s) 1.0252 Hladky / Russian ✗ (Czech)
65000 65% (1m 42s) 1.1306 Cardozo / Portuguese ✓
70000 70% (1m 50s) 1.9546 Kennedy / English ✗ (Irish)
75000 75% (1m 58s) 1.3734 Kasamatsu / Greek ✗ (Japanese)
80000 80% (2m 5s) 1.0530 Gil / Chinese ✗ (Korean)
85000 85% (2m 13s) 1.3896 Zee / Chinese ✗ (Dutch)
90000 90% (2m 21s) 0.0017 Chrysanthopoulos / Greek ✓
95000 95% (2m 29s) 1.2594 Nam / Vietnamese ✗ (Korean)
100000 100% (2m 37s) 1.5061 Rapp / Dutch ✗ (German)

展示结果

all_losses 里保存了训练过程中的loss值,我们将它打印出来:

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

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

Out:

在这里插入图片描述

评估结果

为了查看网络在不同语种上的表现,我们需要创建混淆矩阵,行表示真实语种,列表示预测语种。使用 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] / confusion[i].sum()

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

# 设置 axes
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:

在这里插入图片描述

对角线越亮,则该语言的预测效果越好,比如Greek最好,而English比较差

除对角线外的点越亮则表示越容易预测错。比如(Chinese(行), Korean(列))比较亮,这说明Chinese很容易被网络错误地预测为Korean。

交互式测试

def predict(input_line, n_predictions=3):
    print('\n> %s' % input_line)
    with torch.no_grad():
        output = evaluate(lineToTensor(input_line))

        # Get top N categories
        topv, topi = output.topk(n_predictions, 1, True)
        predictions = []

        for i in range(n_predictions):
            value = topv[0][i].item()
            category_index = topi[0][i].item()
            print('(%.2f) %s' % (value, all_categories[category_index]))
            predictions.append([value, all_categories[category_index]])

predict('Ming')
predict('Takamishi')
predict('John')

Out:

> Ming
(-0.28) Chinese
(-1.67) Vietnamese
(-3.62) Korean

> Takamishi
(-0.35) Japanese
(-1.89) Polish
(-2.84) Italian

> John
(-0.28) Korean
(-2.57) Chinese
(-3.05) Irish

练习

使用不同的 实体->类别 数据集,比如:

  • 一个单词 -> 语种
  • 姓 -> 性别
  • 角色名称 -> 作者
  • 网页标题 -> 博客

使用更大或者更好的网络来得到更优的结果,比如:

  • 使用更多的线性层
  • 使用 nn.LSTMnn.GRU
  • 组合多个RNN为一个更高级的网络
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值