python 构建RNN分类器对“名字-国家”分类、并使用Visdom绘制loss值和acc
前言
为什么使用RNN对文本的分类?
RNN考虑当前输入以及先前接收的输入,前文出现内容将影响接下来要出现的内容。因此RNN是文本和语音分析的理想选择。
Visdom的安装与使用:
https://blog.csdn.net/qq_42962681/article/details/116271548?spm=1001.2014.3001.5501
刘二大人b站讲解视频:
https://www.bilibili.com/video/BV1Y7411d7Ys?p=13&share_source=copy_web
提示:以下是本篇文章正文内容,下面案例可供参考
一、名字对应的国家分类
如图所示:通过训练,快速的预测各个姓名对应的国家。
二、整体程序
1.代码
代码中使用的数据集连接如下
链接:https://pan.baidu.com/s/1jCmi8Qj6lzzb4R4rUgMEew
提取码:trac
代码如下(示例):
import torch
import time
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import gzip
import csv
import matplotlib.pyplot as plt
import numpy as np
import math
from torch.nn.utils.rnn import pack_padded_sequence
# 引入可视化工具visdom
import visdom
#国家-人名进行分类
HIDDEN_SIZE = 100
BATCH_SIZE =256
N_LAYER =2
N_EPOCHS = 100
N_CHARS = 128
USE_GPU = True
# 为训练添加环境变量,之后程序产生的所有数据都会出现在这个环境变量中,visdom就可以监听数据实现可视化
# 而且在visdom中还可以按照环境变量名选择性监听,便于分类管理
viz = visdom.Visdom(env='countries_names')
# 创建线图初始点。loss是差值图,acc是精度图
viz.line([0], [0], win='train_loss', opts=dict(title='train loss'))
viz.line([0], [0], win='acc', opts=dict(title='test acc'))
#读取数据集
class NameDataset(Dataset):
def __init__(self, is_train_set = True):
# 判断是否要训练集还是测试集
filename = 'names_train.csv.gz' if is_train_set else 'names_test.csv.gz'
with gzip.open(filename, 'rt') as f:
reader = csv.reader(f)
rows = list(reader)
# 提取数据集中的名字
self.names = [row[0] for row in rows]
self.len = len(self.names)
self.countries = [row[1] for row in rows]
# set变成集合去除重复国家 sort排序 list 生成列表
self.country_list = list(sorted(set(self.countries)))
# 将列表变成词典
self.country_dict = self.getCountryDict()
self.country_num = len(self.country_list)
# 返回名字(字符串)和对应的国家(索引)
def __getitem__(self, index):
return self.names[index], self.country_dict[self.countries[index]]
def __len__(self):
return self.len
def getCountryDict(self):
country_dict = dict()
for idx, country_name in enumerate(self.country_list, 0):
country_dict[country_name] = idx
return country_dict
def idx2country(self, index):
return self.country_list[index]
def getCountriesNum(self):
return self.country_num
trainset = NameDataset(is_train_set=True)
# print(len(trainset))
trainloader = DataLoader(trainset, batch_size = BATCH_SIZE, shuffle=True)
testset = NameDataset(is_train_set=False)
testloader = DataLoader(testset, batch_size = BATCH_SIZE, shuffle=False)
N_COUNTRY = trainset.getCountriesNum()
#构建模型
class RNNClassifier(torch.nn.Module):
def __init__(self, input_size, hidden_size, output_size, n_layers=1, bidirectional=True): # 构造函数
super(RNNClassifier, self).__init__()
self.hidden_size = hidden_size
self.n_layers = n_layers
self.n_directions = 2 if bidirectional else 1
# bidirectional 双向循环网络
self.embedding = torch.nn.Embedding(input_size, hidden_size)
self.gru = torch.nn.GRU(hidden_size, hidden_size, n_layers,
bidirectional=bidirectional)
self.fc = torch.nn.Linear(hidden_size*self.n_directions, output_size)
def _init_hidden(self, batch_size):
hidden = torch.zeros((self.n_layers * self.n_directions,
batch_size, self.hidden_size))
return create_tensor(hidden)
def forward(self, input, seq_lengths):
#input shape: BXS -> SXB
#结合下方make_tensors和trainModel
input = input.t()
batch_size = input.size(1)
hidden = self._init_hidden(batch_size)
embedding = self.embedding(input)
#pack them up
# 将填充的0计算时去除,提升运算效率,并按单词序列长度从大到小进行排序
gru_input = pack_padded_sequence(embedding, seq_lengths)
output, hidden = self.gru(gru_input, hidden)
# 判断是否为双向gru,是的话进行拼接
if self.n_directions == 2:
hidden_cat = torch.cat([hidden[-1], hidden[-2]],dim=1)
else:
hidden_cat = hidden[-1]
fc_output = self.fc(hidden_cat)
return fc_output
#将名字转换成ASSIC并进行填充,输入序列为矩阵,因为名字长短不一,
# 需要将名字填充到最长的名字的长度名字转换为tensor
def name2list(name):
arr = [ord(c) for c in name]
return arr, len(arr)
def make_tensors(names, countries):
sequences_and_lengths = [name2list(name) for name in names]
# 名字长度
name_sequences = [sl[0] for sl in sequences_and_lengths]
seq_lengths = torch.LongTensor([sl[1] for sl in sequences_and_lengths])
countries = countries.long()
#make tensor of name, BatchSize x SeqLen
# 先生成全0的tensor,再将名字序列赋值进去
seq_tensor = torch.zeros(len(name_sequences), seq_lengths.max()).long()
for idx, (seq, seq_len) in enumerate(zip(name_sequences, seq_lengths), 0):
seq_tensor[idx, :seq_len] = torch.LongTensor(seq)
#sort by length to use pack_padded_sequence
# 按照序列长度进行排序sort返回排序后的序列和排序后的索引
seq_lengths, perm_idx = seq_lengths.sort(dim=0, descending=True)
seq_tensor = seq_tensor[perm_idx]
countries = countries[perm_idx]
return create_tensor(seq_tensor),create_tensor(seq_lengths), create_tensor(countries)
global_step = 0.0
global_step2 = 0.0
#训练
#python中计时以秒做单位,除以60转换为分钟,做后做一个分钟和秒的显示
def trainModel():
def time_since(since):
s = time.time() - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
global global_step
total_loss = 0
for i, (names, countries) in enumerate(trainloader, 1):
inputs, seq_lengths, target = make_tensors(names, countries)
output = classifier(inputs, seq_lengths)
loss = criterion(output, target)
# print( loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 更新全局步数
global_step = global_step + 1
# print(global_step,loss)
# 数据变化,点与点用线line连接
viz.line([loss.item()], [global_step], win='train_loss', update='append')
total_loss += loss.item()
#10个batch_size进行一轮输出
if i % 10 == 0:
print(f'[{time_since(start)}] Epoch {epoch}',end='')
print(f'[{i * len(inputs)} / {len(trainset)}]', end='')
# ?len(inputs)应该删除?
print(f'loss={total_loss / (i )}')
# print(f'loss={total_loss / (i * len(inputs))}')
return total_loss
#测试
def testModel():
correct = 0
# total = len(testset)
total = 0
global global_step2
print('evaluating trained model ...')
with torch.no_grad():
for i, (names,countries) in enumerate(testloader, 1):
inputs, seq_lengths, target = make_tensors(names, countries)
output = classifier(inputs, seq_lengths)
pred = output.max(dim=1, keepdim=True)[1]
correct += pred.eq(target.view_as(pred)).sum().item()
total += target.size(0)
# 更新全局步数
global_step2 = global_step2 + 1
# 精度可视化显示
viz.line([correct / total], [global_step2], win='acc', update='append')
percent = '%.2f' % (100 * correct / total)
print(f'Test set: Accuracy {correct}/{total} {percent}%')
return correct / total
#调用GPU
def create_tensor(tensor):
if USE_GPU:
device = torch.device("cuda:0")
tensor = tensor.to(device)
return tensor
#训练
#N_CHARS:英文字母
classifier = RNNClassifier(N_CHARS, HIDDEN_SIZE, N_COUNTRY, N_LAYER)
classifier = create_tensor(classifier)
#损失函数和优化器
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(classifier.parameters(), lr=0.01)
start = time.time()
print('Training for %d epochs...'% N_EPOCHS)
# acc_list = []
if __name__=='__main__':
for epoch in range(1, N_EPOCHS + 1):
# TRAIN CYCLE
trainModel()
acc = testModel()
#
# #每个epoch 记录准确率
# acc_list.append(acc)
#也可使用matplolib进行可视化绘图
#可视化
# epoch = np.arange(1, len(acc_list) + 1, 1)
# acc_list = np.array(acc_list)
# plt.plot(epoch, acc_list)
# plt.xlabel('Epoch')
# plt.ylabel('Accuracy')
# plt.grid()
# plt.show()
2.Visdom输出的结果
loss值如下:
acc值如下: