首页 > 编程学习 > 循环神经网络:姓名国别分类实操

循环神经网络:姓名国别分类实操

发布时间:2022/5/14 19:00:09
import math
import time
import torch

import matplotlib.pyplot as plt
import numpy as np

import gzip
import csv
from torch.nn.utils.rnn import pack_padded_sequence
from torch.utils.data import Dataset, DataLoader

#1.构建数据集
HIDDEN_SIZE = 100
BATCH_SIZE = 256
N_LAYER = 2
N_EPOCHS = 100
N_CHARS = 128  # 字典长度
USE_GPU = False

class NameDataset(Dataset):
    def __init__(self, is_train_set=True):
        filename = 'D:\迅雷下载/names_train.csv.gz' if is_train_set else 'D:\迅雷下载/names_test.csv.gz'
        with gzip.open(filename, 'rt') as f:
            reader = csv.reader(f)
            rows = list(reader) #(name,language)
        self.names = [row[0] for row in rows] #(name,language) 的第零维,接入到其中去
        self.len = len(self.names)
        self.countries = [row[1] for row in rows]
        self.country_list = list(sorted(set(self.countries))) #set 构建集合 去掉重复的国家 sort 排序 list 构建列表
        self.country_dict = self.getCountryDict() #将列表转化为词典
        self.country_num = len(self.country_list)
    def __getitem__(self, index):#索引 通过下标返回name 通过下标找到name对应得language 然后根据词典返回对应language得数字
        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)
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() #决定最终输出维度得大小

#2.搭建神经网络
def create_tensor(tensor):
    if USE_GPU:
        device = torch.device("cuda:0")
        tensor = tensor.to(device)
    return tensor

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

        self.embedding = torch.nn.Embedding(input_size, hidden_size) #(seqlen,batchsize)->(seqlen,batchsize,hiddensize)
        self.gru = torch.nn.GRU(hidden_size, hidden_size, n_layers, #第二个是输出维度  input(seqlen,batchsize,hiddensize)->(seqlen,batchsize,hiddensize*nDirections)
                                bidirectional=bidirectional) #说明单向 1 or双向 2          hidden(nlayers*nDirections,batchsize,hiddensize) 维度不变
        self.fc = torch.nn.Linear(hidden_size * self.n_directions, output_size)#hiddensize*2是因为两次拼接

    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 = input.t()  # 转置 t -> transpose: input shape : B x S -> S x B
        batch_size = input.size(1)

        hidden = self._init_hidden(batch_size)  # h0(nLayer*nDirection,batchsize,hiddensize)
        embedding = self.embedding(input)  # out=(seqLen,batchSize,hiddenSize)

        # PackedSquence:把为0的填充量去除,把每个样本的长度记录下来,按长度排序(长度是降序)后拼接在一起  先长度排序后 经过嵌入层embed
        gru_input = pack_padded_sequence(embedding, seq_lengths)

        output, hidden = self.gru(gru_input, hidden) #hidden(nlayers*nDirections,batchsize,hiddensize)
        if self.n_directions == 2:  # 双向循环神经网络有两个hidden
            hidden_cat = torch.cat([hidden[-1], hidden[-2]], dim=1) #在batchsize维度进行拼接
        else:
            hidden_cat = hidden[-1]

        fc_output = self.fc(hidden_cat)
        return fc_output


classifier = RNNClassifier(N_CHARS, HIDDEN_SIZE, N_COUNTRY, N_LAYER)
#3.定义优化器和损失函数
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(classifier.parameters(), lr=0.001)

#本模块对name进行处理
def name2list(name): #name to list
    arr = [ord(c) for c in name]  # 返回对应字符的 ASCII 数值  将name 转化为对应各个字符ASCII得列表
    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]  #所有name得ASCII得列表组成得列表
    seq_lengths = torch.LongTensor([sl[1] for sl in sequences_and_lengths]) #所有name得ASCII得列表得长度组成得列表
    countries = countries.long()  # countries:国家索引   整两个整数都转化成LongTensor

    # make tensor of name, BatchSize x SeqLen  (做padding,先做一个全零得张量,然后将非零量粘贴过去)
    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
    seq_lengths, perm_idx = seq_lengths.sort(dim=0, descending=True)#返回序列长度得列表以及对应序列长度得索引
    # sort返回两个值,seq_lengths:排完序后的序列(未padding),perm_idx:排完序后对应元素的索引
    seq_tensor = seq_tensor[perm_idx]  # 排序(已padding)
    countries = countries[perm_idx]  # 排序(标签)
    return create_tensor(seq_tensor), create_tensor(seq_lengths), create_tensor(countries)

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):
        inputs, seq_lengths, target = make_tensors(names, countries)  # make_tensors
        output = classifier(inputs, seq_lengths)
        loss = criterion(output, target)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_loss += loss.item()
        if i % 10 == 0:
            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 i, (names, countries) in enumerate(testloader, 1):
            inputs, seq_lengths, target = make_tensors(names, countries)  # make_tensors
            output = classifier(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


if __name__ == '__main__':
    classifier = RNNClassifier(N_CHARS, HIDDEN_SIZE, N_COUNTRY, N_LAYER) #构造分类器:派生类 解决名字字符长度的不同
    if USE_GPU:
        device = torch.device("cuda:0")
        classifier.to(device)

    criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(classifier.parameters(), lr=0.001)

    start = time.time() #返回的是s为单位的时间
    print("Training for %d epochs..." % N_EPOCHS)
    acc_list = []
    for epoch in range(1, N_EPOCHS + 1):
        # Train cycle
        trainModel()
        acc = testModel()
        acc_list.append(acc) #将准确率记录到列表里


# 绘图
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()
Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000