PyTorch深度学习总结--13_Name_Classification

PyTorch深度学习总结–13_Name_Classification

13_Name_Classification

任务介绍

根据名称,选出国家
在这里插入图片描述

使用模型

基础模型介绍

在这里插入图片描述

在这里插入图片描述

GRU,这里采用双向的GRU模型,
在这里插入图片描述
双向GRU的结构类似于下图,将RNNCell替换为GRUCell即可
在这里插入图片描述

输入:

两个hidden0,都是zeros形成的,输入的两个hidden需要拼接在一起

输出:

结果第一个是正向的hidden,第二个是反向的hidden
因为是双向的,所以会输出两个hidden
在这里插入图片描述

单词的转化为Tensor

1、先将单词中的字母转换为对应的ASCII码,这样就形成了单词转换为数字
在这里插入图片描述
2、然后将ASCII码的向量进行填充,形成长度相同的向量
在这里插入图片描述
3、再送入Embedding层,将每个ASCII码转换为向量
在这里插入图片描述
4、使用 pack_padded_sequence函数将embedding中的零向量去掉,实现压缩去噪
在这里插入图片描述

模型的最终输出转换为种类

最后将模型输出的hidden 通过一个线性层转换为城市的种类,然后进行验证。
在这里插入图片描述

实验代码

python语言,使用PyTorch实现

"""
 -*- coding: utf-8 -*-
@Time    : 2022/1/6 21:53
@Author  : nanfang
@File    : 13_Name_Classification.py
"""
# -------------0 Import Package-------------------------#
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

# ------------0 parameters-------------#
HIDDEN_SIZE = 100
BATCH_SIZE = 256
N_LAYER = 2
N_EPOCHS = 5
N_CHARS = 128  # 字典长度
USE_GPU = False  # 不用GPU
file = '../dataset/RNN_13/'


# ---------------------1 Preparing Data and DataLoad-------------------------------#
class NameDataset(Dataset):
    def __init__(self, is_train_set=True):
        if is_train_set:
            filename = file + 'names_train.csv.gz'
        else:
            filename = file + '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.countries = [row[1] for row in rows]  # 所有城市名
        self.len = len(self.names)  # 姓名的长度
        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):
        """
        初始化 self.country_dict
        :return: (城市名,序号)
        """
        dic = dict()
        for i, v in enumerate(self.country_list, 0):
            dic[v] = i
        return dic

    def getCountryNum(self):
        """
        返回城市数量,不含重复值
        :return: int
        """
        return self.country_num

    def idx2country(self, index):
        """
        根据索引返回城市名
        :param index:
        :return: str
        """
        return self.country_list[index]


trainset = NameDataset(is_train_set=True)
testset = NameDataset(is_train_set=False)

train_loader = DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True)
test_loader = DataLoader(testset, batch_size=BATCH_SIZE, shuffle=True)
N_COUNTRY = trainset.getCountryNum()


# ------------------------------Design  Model-----------------------------------#
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.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_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):
        ## seq_lengths 表示向量的个数,也单词的个数
        input = input.t()
        batch_size = input.size(1)

        hidden = self._init_hidden(batch_size)
        embedding = self.embedding(input)

        gru_input = pack_padded_sequence(embedding, seq_lengths, enforce_sorted=False)

        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]
        fc_output = self.fc(hidden_cat)
        return fc_output


# ----------------------3 Construct Loss and Optimizer------------------------------------#
classifier = RNNClassifier(N_CHARS, HIDDEN_SIZE, N_COUNTRY, N_LAYER)

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


# -----------------------------------4 Train and Test----------------------------------------------------#

def time_since(since):
    s = time.time() - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)


def name2list(name):
    arr = [ord(c) for c in name]  # 返回对应字符的 ASCII 数值
    return arr, len(arr)  # 返回元组,列表本身和列表长度


def make_tensor(names, countires):
    seq_and_lengths = [name2list(name) for name in names]
    seqs = [seq[0] for seq in seq_and_lengths]
    seq_length = torch.LongTensor([seq[1] for seq in seq_and_lengths])
    seq_tensor = torch.zeros(len(seqs), seq_length.max()).long()
    for idx, (seq, seq_len) in enumerate(zip(seqs, seq_length)):
        seq_tensor[idx, :seq_len] = torch.LongTensor(seq)
    return seq_tensor, seq_length, countires.long()


def trainModel():
    total_loss = 0
    for i, (names, countries) in enumerate(train_loader, 1):
        inputs, seq_lengths, target = make_tensor(names, countries)

        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(test_loader, 1):
            inputs, seq_lengths, target = make_tensor(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__':
    if USE_GPU:
        device = torch.device("cuda:0")
        classifier.to(device)
    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)
epoch =np.arange(1,len(acc_list)+1)
acc_list=np.array(acc_list)
plt.plot(epoch,acc_list)
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.grid()
plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南方-D

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值