一、目的
使用RNN(RNNCell使用GRU)搭建一个姓名分类器
二、编程
我们有数据集name-country:
链接:https://pan.baidu.com/s/1vZ27gKp8Pl-qICn_p2PaSw
提取码:cxe4
我们将搭建下面这样一个网络用来对姓名进行分类
在开始搭建网络之前我们要对数据集进行处理,将非结构化姓名转化为结构化的向量
我们先将姓名表示为单个字符再用ASCII码处理
因为不同的姓名长度不同,这样的数据无法输入到RNN,所以我们取最长的序列为基准,对其他的序列进行填充0处理,让其组成为一个batch_size*seqlen_max的tensor,再将其转置让其符合RNN的输入维度
最后再对姓名序列做排序处理,让其符合embedding输入,同样的我们也要改变countries的顺序,让其保存对应的关系
本次使用的模块
import torch
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pack_padded_sequence
import math
import time
import matplotlib.pyplot as plt
2.1 准备数据集
# 准备数据集
class NameDataset(Dataset):
def __init__(self, is_train_set=True):
filename = './dataset/names/names_train.csv.gz' if is_train_set else './dataset/names/names_test.csv.gz'
# header=None 即指定原始文件数据没有列索引,这样read_csv为其自动加上列索引{从0开始}
data = pd.read_csv(filename, header=None)
# 取出名字
self.names = data[0]
self.len = len(self.names)
# 取出国家
self.countries = data[1]
self.countries_list = list(sorted(set(self.countries)))
self.countries_dict = self.getCountriesDict()
self.countries_num = len(self.countries_list)
def __getitem__(self, index):
return self.names[index], self.countries_dict[self.countries[index]]
def getCountriesDict(self):
countries_dict = dict()
for index, country_name in enumerate(self.countries_list, 0):
countries_dict[country_name] = index
return countries_dict
def __len__(self):
return self.len
def id2country(self, index):
return self.countries_list[index]
def getCountriesNum(self):
return self.countries_num
# 返回ASCII码表示的姓名列表与列表长度
def name2list(name):
arr = [ord(c) for c in name]
return arr, len(arr)
def make_tensors(names, countries):
# 元组列表,每个元组包含ASCII码表示的姓名列表与列表长度
sequences_and_lengths = [name2list(name) for name in names]
# 取出所有的ASCII码表示的姓名列表
name_sequences = [sl[0] for sl in sequences_and_lengths]
# 取出所有的列表长度
seq_lengths = torch.tensor([sl[1] for sl in sequences_and_lengths])
# 将countries转为long型
countries = countries.long()
# 接下来每个名字序列补零,使之长度一样。
# 先初始化一个全为零的tensor,大小为 所有姓名的数量*最长姓名的长度
seq_tensor = torch.zeros(len(name_sequences), max(seq_lengths)).long()
# 将姓名序列覆盖到初始化的全零tensor上
for idx, (seq, seq_length) in enumerate(zip(name_sequences, seq_lengths), 0):
seq_tensor[idx, :seq_length] = torch.LongTensor(seq)
# 根据序列长度seq_lengths对补零后tensor进行降序排列,方便后面加速计算。
# 返回排序后的seq_lengths与索引变化列表
seq_lengths, prem_idx = seq_lengths.sort(dim=0, descending=True)
# 根据索引变化列表对ASCII码表示的姓名列表进行排序
seq_tensor = seq_tensor[prem_idx]
# 根据索引变化列表对countries进行排序,使姓名与国家还是一一对应关系
# seq_tensor.shape : batch_size*max_seq_lengths,
# seq_lengths.shape : batch_size
# countries.shape : batch_size
countries = countries[prem_idx]
return seq_tensor, seq_lengths, countries
2.2 搭建模型
# 搭建模型
class Model(torch.nn.Module):
# input_size=128, hidden_size=100, output_size=18
def __init__(self, input_size, hidden_size, output_size, num_layers=1, bidirectional=True):
super(Model, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
# 是否双向
self.n_directions = 2 if bidirectional else 1
# 输入大小128,输出大小100
self.embedding = torch.nn.Embedding(num_embeddings=input_size, embedding_dim=hidden_size)
# 经过Embedding后input的大小是100,hidden_size的大小也是100,所以形参都是hidden_size。
self.gru = torch.nn.GRU(input_size=hidden_size, hidden_size=hidden_size,
num_layers=num_layers, bidirectional=bidirectional)
# 如果是双向,会输出两个hidden层,要进行拼接,所以形成的output大小是
# hidden_size * self.n_directions,输出是大小是18,是为18个国家的概率
self.fc = torch.nn.Linear(self.hidden_size * self.n_directions, output_size)
def init_hidden(self, batch_size):
hidden = torch.zeros(self.num_layers * self.n_directions, batch_size, self.hidden_size)
return hidden
def forward(self, input, seq_lengths):
# 先对input进行转置,input shape : batch_size*max_seq_lengths -> max_seq_lengths*batch_size 每一列表示姓名
input = input.t()
# 总共有多少列,既是batch_size的大小
batch_size = input.size(1)
# 初始化隐藏层
hidden = self.init_hidden(batch_size)
# embedding.shape : max_seq_lengths*batch_size*hidden_size 19*64*100
embedding = self.embedding(input)
# pack_padded_sequence方便批量计算
gru_input = pack_padded_sequence(embedding, seq_lengths)
# 进入网络进行计算
output, hidden = self.gru(gru_input, hidden)
# 如果是双向的,需要进行拼接
if self.n_directions == 2:
hidden_cat = torch.cat([hidden[-1], hidden[-2]], dim=1)
else:
hidden_cat = hidden[-1]
# 线性层输出大小为18
fc_output = self.fc(hidden_cat)
return fc_output
2.3 训练
# 训练
def time_since(since):
s = time.time() - since
m = math.floor(s/60)
s -= m*60
return '%dm %ds' % (m, s)
def trainModel():
total_loss = 0
for i, (names, countries) in enumerate(trainloader, 1):
# make_tensors函数返回经过降序排列后的 姓名列表,列表长度,国家
inputs, seq_lengths, target = make_tensors(names, countries)
output = model(inputs, seq_lengths)
optimizer.zero_grad()
loss = criterion(output, target)
loss.backward()
optimizer.step()
total_loss += loss.item()
if i % 10 == 0:
print(i)
print(f'[{time_since(start)}] Epoch {epoch} ', end='')
print(f'[{i * len(inputs)}/{len(trainset)}] ', end='')
print(f'loss={total_loss / (i * len(inputs))}')
return total_loss
def testModel():
correct = 0
total = len(testset)
print("evaluating trained model ...")
with torch.no_grad():
for idx, (names, countries) in enumerate(testloader, 1):
inputs, seq_lengths, target = make_tensors(names, countries)
output = model(inputs, seq_lengths)
pred = output.max(dim=1, keepdim=True)[1]
correct += pred.eq(target.view_as(pred)).sum().item()
percent = '%.2f' % (100 * correct / total)
print(f'Test set: Accuracy {correct}/{total} {percent}%')
return correct / total
2.4 总控程序
if __name__ == '__main__':
N_EPOCHS = 30 # epoch
HIDDEN_SIZE = 100 # 隐藏层的大小,也是Embedding后输出的大小
BATCH_SIZE = 128
N_COUNTRY = 18 # 总共有18个类别的国家,为RNN后输出的大小
N_LAYER = 2
N_CHARS = 128 # 字母字典的大小(ASCII),Embedding输入的大小
trainset = NameDataset(is_train_set=True)
trainloader = DataLoader(dataset=trainset, batch_size=BATCH_SIZE, shuffle=True)
testset = NameDataset(is_train_set=False)
testloader = DataLoader(dataset=testset, batch_size=BATCH_SIZE, shuffle=True)
model = Model(input_size=N_CHARS, hidden_size=HIDDEN_SIZE, output_size=N_COUNTRY, num_layers=N_LAYER)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
start = time.time()
print("Training for %d epochs..." % N_EPOCHS)
acc_list = []
for epoch in range(1, N_EPOCHS + 1):
trainModel()
acc = testModel()
acc_list.append(acc)
plt.plot(acc_list)
plt.xlabel('epoch')
plt.ylabel('acc')
plt.show()
该网络经训练可以达到的最佳准确率大概在85%左右。