当前位置:   article > 正文

基于MLP和CNN实现姓氏分类——NLP实验_姓名分类问题

姓名分类问题

基于多层感知机(MLP)实现姓氏分类 

一.实验目的

      我们将MLP应用于将姓氏分类到其原籍国的任务。从公开观察到的数据推断人口统计信息(如国籍)具有从产品推荐到确保不同人口统计用户获得公平结果的应用。人口统计和其他自我识别信息统称为“受保护属性”。“在建模和产品中使用这些属性时,必须小心。”我们首先对每个姓氏的字符进行拆分,并像对待“示例:将餐馆评论的情绪分类”中的单词一样对待它们。除了数据上的差异,字符层模型在结构和实现上与基于单词的模型基本相似。

二.MLP的原理

     多层感知机(MLP,Multilayer Perceptron)也叫人工神经网络(ANN,Artificial Neural Network)他有以下基本原理和关键概念:

  1. 神经元(Neurons):MLP中的基本单元。神经元接收来自上一层的输入,通过加权求和和激活函数处理后产生输出。

  2. 权重(Weights):连接神经元之间的参数,表示了输入在神经元之间传递的重要性或影响程度。权重会在训练过程中通过反向传播算法进行调整,以最小化损失函数。

  3. 偏置(Biases):每个神经元都有一个偏置项,它可以理解为神经元的激活阈值。偏置项与权重一起调整输入的线性组合,影响神经元的激活状态。

  4. 激活函数(Activation Functions):MLP中的每个神经元通常都会应用一个非线性激活函数,如Sigmoid、ReLU(Rectified Linear Unit)、Tanh等。这些激活函数引入了非线性因素,使得神经网络能够学习复杂的数据模式。

  5. 前向传播(Forward Propagation):在前向传播过程中,输入数据从输入层传递到输出层。在每一层中,输入经过加权求和和激活函数处理后生成输出,然后传递到下一层。

  6. 反向传播(Backpropagation):反向传播是用于训练MLP的一种常用方法。它通过计算损失函数对网络参数(权重和偏置)的梯度,然后根据梯度更新参数。这个过程反复进行,直到模型收敛到最优解。

  7. 损失函数(Loss Function):损失函数用于衡量模型预测结果与真实标签之间的差异。常用的损失函数包括交叉熵损失函数(用于分类问题)和均方误差损失函数(用于回归问题)。

     对于MLP结构来说,除了输入输出层,它中间可以有多个隐层,最简单的MLP只含一个隐层,即三层的结构,如下图:

    从上图可以看到,多层感知机层与层之间是全连接的(全连接的意思就是:上一层的任何一个神经元与下一层的所有神经元都有连接)。多层感知机最底层是输入层,中间是隐藏层,最后是输出层。

    对于输入层来说,你输入什么就是什么,比如输入是一个n维向量,就有n个神经元。

    隐藏层的神经元与输入层是全连接的,假设输入层用向量X表示,则隐藏层的输出就是f(W1X+b1),W1是权重(也叫连接系数),b1是偏置,函数f 可以是常用的sigmoid函数或者tanh函数:

   

    最后就是输出层,隐藏层到输出层可以看成是一个多类别的逻辑回归,也即softmax回归,所以输出层的输出就是softmax(W2X1+b2),X1表示隐藏层的输出f(W1X+b1)。

     MLP整个模型就是,函数G是softmax

     因此,MLP所有的参数就是各个层之间的连接权重以及偏置,包括W1、b1、W2、b2。对于一个具体的问题,怎么确定这些参数?求解最佳的参数是一个最优化问题,解决最优化问题,最简单的就是梯度下降法了(SGD):首先随机初始化所有参数,然后迭代地训练,不断地计算梯度和更新参数,直到满足某个条件为止(比如误差足够小、迭代次数足够多时)。这个过程涉及到代价函数、规则化(Regularization)、学习速率(learning rate)、梯度计算等

     MLP通过不断地调整权重和偏置,以及选择合适的激活函数和损失函数,使得模型能够逐渐学习输入和输出之间的复杂映射关系,从而实现对数据的有效建模和预测。

三.数据集

     姓氏数据集,它收集了来自18个不同国家的10,000个姓氏,这些姓氏是作者从互联网上不同的姓名来源收集的。该数据集将在本课程实验的几个示例中重用,并具有一些使其有趣的属性。第一个性质是它是相当不平衡的。排名前三的课程占数据的60%以上:27%是英语,21%是俄语,14%是阿拉伯语。剩下的15个民族的频率也在下降——这也是语言特有的特性。第二个特点是,在国籍和姓氏正字法(拼写)之间有一种有效和直观的关系。有些拼写变体与原籍国联系非常紧密(比如“O ‘Neill”、“Antonopoulos”、“Nagasawa”或“Zhu”)。

     为了创建最终的数据集,我们从一个比课程补充材料中包含的版本处理更少的版本开始,并执行了几个数据集修改操作。第一个目的是减少这种不平衡——原始数据集中70%以上是俄文,这可能是由于抽样偏差或俄文姓氏的增多。为此,我们通过选择标记为俄语的姓氏的随机子集对这个过度代表的类进行子样本。接下来,我们根据国籍对数据集进行分组,并将数据集分为三个部分:70%到训练数据集,15%到验证数据集,最后15%到测试数据集,以便跨这些部分的类标签分布具有可比性。

对数据集进行预处理:

  1. import collections
  2. import numpy as np
  3. import pandas as pd
  4. import re
  5. from argparse import Namespace
  6. # 定义命令行参数
  7. args = Namespace(
  8. raw_dataset_csv="surnames.csv", # 原始数据集文件名
  9. train_proportion=0.7, # 训练集比例
  10. val_proportion=0.15, # 验证集比例
  11. test_proportion=0.15, # 测试集比例
  12. output_munged_csv="surnames_with_splits.csv", # 输出文件名
  13. seed=1337 # 随机种子
  14. )
  15. # 读取原始数据集
  16. surnames = pd.read_csv(args.raw_dataset_csv, header=0)
  17. surnames.head()
  18. # 获取唯一的类别(国籍)
  19. set(surnames.nationality)
  20. # 按国籍划分训练集
  21. # 创建字典
  22. by_nationality = collections.defaultdict(list)
  23. for _, row in surnames.iterrows():
  24. by_nationality[row.nationality].append(row.to_dict())
  25. # 创建划分后的数据
  26. final_list = []
  27. np.random.seed(args.seed)
  28. # 按国籍划分并随机打乱数据
  29. for _, item_list in sorted(by_nationality.items()):
  30. np.random.shuffle(item_list)
  31. n = len(item_list)
  32. n_train = int(args.train_proportion * n)
  33. n_val = int(args.val_proportion * n)
  34. n_test = int(args.test_proportion * n)
  35. # 为每个数据点添加划分属性
  36. for item in item_list[:n_train]:
  37. item['split'] = 'train'
  38. for item in item_list[n_train:n_train+n_val]:
  39. item['split'] = 'val'
  40. for item in item_list[n_train+n_val:]:
  41. item['split'] = 'test'
  42. # 添加到最终列表中
  43. final_list.extend(item_list)
  44. # 将划分后的数据写入文件
  45. final_surnames = pd.DataFrame(final_list)
  46. final_surnames.head()
  47. # 将处理后的数据写入CSV文件
  48. final_surnames.to_csv(args.output_munged_csv, index=False)

结果:

查看前几行数据:

 唯一类别:

数据集的划分结果:

查看划分后的数据集:

四.实验步骤

1.导入必要的第三方库

  1. #导入必要的第三方库
  2. from argparse import Namespace
  3. from collections import Counter
  4. import json
  5. import os
  6. import string
  7. import numpy as np
  8. import pandas as pd
  9. import torch
  10. import torch.nn as nn
  11. import torch.nn.functional as F
  12. import torch.optim as optim
  13. from torch.utils.data import Dataset, DataLoader
  14. from tqdm import tqdm_notebook

2.数据集类的加载和处理文本

     SurnameDataset的实现与“Example: classification of Sentiment of Restaurant Reviews”中的ReviewDataset几乎相同,只是在getitem方法的实现方式上略有不同。回想一下,本课程中呈现的数据集类继承自PyTorch的数据集类,因此,我们需要实现两个函数:__getitem方法,它在给定索引时返回一个数据点;以及len方法,该方法返回数据集的长度。

  1. #创建一个自定义的数据集类来加载和处理文本数据
  2. #划分训练、验证和测试集,设置数据集大小,以及构建查找字典
  3. class SurnameDataset(Dataset):
  4. def __init__(self, surname_df, vectorizer):
  5. """
  6. Args:
  7. surname_df (pandas.DataFrame): the dataset
  8. vectorizer (SurnameVectorizer): vectorizer instatiated from dataset
  9. """
  10. self.surname_df = surname_df
  11. self._vectorizer = vectorizer
  12. self.train_df = self.surname_df[self.surname_df.split=='train']
  13. self.train_size = len(self.train_df)
  14. self.val_df = self.surname_df[self.surname_df.split=='val']
  15. self.validation_size = len(self.val_df)
  16. self.test_df = self.surname_df[self.surname_df.split=='test']
  17. self.test_size = len(self.test_df)
  18. self._lookup_dict = {'train': (self.train_df, self.train_size),
  19. 'val': (self.val_df, self.validation_size),
  20. 'test': (self.test_df, self.test_size)}
  21. self.set_split('train')
  22. # Class weights
  23. class_counts = surname_df.nationality.value_counts().to_dict()
  24. def sort_key(item):
  25. return self._vectorizer.nationality_vocab.lookup_token(item[0])
  26. sorted_counts = sorted(class_counts.items(), key=sort_key)
  27. frequencies = [count for _, count in sorted_counts]
  28. self.class_weights = 1.0 / torch.tensor(frequencies, dtype=torch.float32)
  29. #加载数据集并生成新的向量化器
  30. @classmethod
  31. def load_dataset_and_make_vectorizer(cls, surname_csv):
  32. """Load dataset and make a new vectorizer from scratch
  33. Args:
  34. surname_csv (str): location of the dataset
  35. Returns:
  36. an instance of SurnameDataset
  37. """
  38. surname_df = pd.read_csv(surname_csv)
  39. train_surname_df = surname_df[surname_df.split=='train']
  40. return cls(surname_df, SurnameVectorizer.from_dataframe(train_surname_df))
  41. #加载数据集和相应的向量化器,用于重新使用已缓存的向量化器
  42. @classmethod
  43. def load_dataset_and_load_vectorizer(cls, surname_csv, vectorizer_filepath):
  44. """Load dataset and the corresponding vectorizer.
  45. Used in the case in the vectorizer has been cached for re-use
  46. Args:
  47. surname_csv (str): location of the dataset
  48. vectorizer_filepath (str): location of the saved vectorizer
  49. Returns:
  50. an instance of SurnameDataset
  51. """
  52. surname_df = pd.read_csv(surname_csv)
  53. vectorizer = cls.load_vectorizer_only(vectorizer_filepath)
  54. return cls(surname_df, vectorizer)
  55. #从文件中加载向量化器
  56. @staticmethod
  57. def load_vectorizer_only(vectorizer_filepath):
  58. """a static method for loading the vectorizer from file
  59. Args:
  60. vectorizer_filepath (str): the location of the serialized vectorizer
  61. Returns:
  62. an instance of SurnameVectorizer
  63. """
  64. with open(vectorizer_filepath) as fp:
  65. return SurnameVectorizer.from_serializable(json.load(fp))
  66. #将向量化器保存到磁盘
  67. def save_vectorizer(self, vectorizer_filepath):
  68. """saves the vectorizer to disk using json
  69. Args:
  70. vectorizer_filepath (str): the location to save the vectorizer
  71. """
  72. with open(vectorizer_filepath, "w") as fp:
  73. json.dump(self._vectorizer.to_serializable(), fp)
  74. #回向量化器对象
  75. def get_vectorizer(self):
  76. """ returns the vectorizer """
  77. return self._vectorizer
  78. #划分数据集
  79. def set_split(self, split="train"):
  80. """ selects the splits in the dataset using a column in the dataframe """
  81. self._target_split = split
  82. self._target_df, self._target_size = self._lookup_dict[split]
  83. #返回指定数据集的大小
  84. def __len__(self):
  85. return self._target_size
  86. #获取指定索引的数据点,并将文本数据向量化,标签进行编码后返回
  87. def __getitem__(self, index):
  88. """the primary entry point method for PyTorch datasets
  89. Args:
  90. index (int): the index to the data point
  91. Returns:
  92. a dictionary holding the data point's:
  93. features (x_surname)
  94. label (y_nationality)
  95. """
  96. row = self._target_df.iloc[index]
  97. surname_vector = \
  98. self._vectorizer.vectorize(row.surname)
  99. nationality_index = \
  100. self._vectorizer.nationality_vocab.lookup_token(row.nationality)
  101. return {'x_surname': surname_vector,
  102. 'y_nationality': nationality_index}
  103. #根据指定的批量大小返回数据集中的批次数量
  104. def get_num_batches(self, batch_size):
  105. """Given a batch size, return the number of batches in the dataset
  106. Args:
  107. batch_size (int)
  108. Returns:
  109. number of batches in the dataset
  110. """
  111. return len(self) // batch_size
  112. #生成批次数据
  113. def generate_batches(dataset, batch_size, shuffle=True,
  114. drop_last=True, device="cpu"):
  115. """
  116. A generator function which wraps the PyTorch DataLoader. It will
  117. ensure each tensor is on the write device location.
  118. """
  119. dataloader = DataLoader(dataset=dataset, batch_size=batch_size,
  120. shuffle=shuffle, drop_last=drop_last)
  121. for data_dict in dataloader:
  122. out_data_dict = {}
  123. for name, tensor in data_dict.items():
  124. out_data_dict[name] = data_dict[name].to(device)
  125. yield out_data_dict

3.将姓氏字符串转换为向量化的minibatches

     为了使用字符对姓氏进行分类,我们使用词汇表、向量化器和DataLoader将姓氏字符串转换为向量化的minibatches。这些数据结构与“Example: Classifying Sentiment of Restaurant Reviews”中使用的数据结构相同,它们举例说明了一种多态性,这种多态性将姓氏的字符标记与Yelp评论的单词标记相同对待。数据不是通过将字令牌映射到整数来向量化的,而是通过将字符映射到整数来向量化的。

  1. class Vocabulary(object):
  2. """Class to process text and extract vocabulary for mapping"""
  3. #初始化词汇表
  4. def __init__(self, token_to_idx=None, add_unk=True, unk_token="<UNK>"):
  5. """
  6. Args:
  7. token_to_idx (dict): a pre-existing map of tokens to indices
  8. add_unk (bool): a flag that indicates whether to add the UNK token
  9. unk_token (str): the UNK token to add into the Vocabulary
  10. """
  11. if token_to_idx is None:
  12. token_to_idx = {}
  13. self._token_to_idx = token_to_idx
  14. self._idx_to_token = {idx: token
  15. for token, idx in self._token_to_idx.items()}
  16. self._add_unk = add_unk
  17. self._unk_token = unk_token
  18. self.unk_index = -1
  19. if add_unk:
  20. self.unk_index = self.add_token(unk_token)
  21. #将词汇表保存为可序列化的格式
  22. def to_serializable(self):
  23. """ returns a dictionary that can be serialized """
  24. return {'token_to_idx': self._token_to_idx,
  25. 'add_unk': self._add_unk,
  26. 'unk_token': self._unk_token}
  27. #从序列化的字典实例化词汇表对象
  28. @classmethod
  29. def from_serializable(cls, contents):
  30. """ instantiates the Vocabulary from a serialized dictionary """
  31. return cls(**contents)
  32. #据输入的标记更新词汇表的映射字典
  33. def add_token(self, token):
  34. """Update mapping dicts based on the token.
  35. Args:
  36. token (str): the item to add into the Vocabulary
  37. Returns:
  38. index (int): the integer corresponding to the token
  39. """
  40. if token in self._token_to_idx:
  41. index = self._token_to_idx[token]
  42. else:
  43. index = len(self._token_to_idx)
  44. self._token_to_idx[token] = index
  45. self._idx_to_token[index] = token
  46. return index
  47. #将一个标记列表添加到词汇表
  48. def add_many(self, tokens):
  49. """Add a list of tokens into the Vocabulary
  50. Args:
  51. tokens (list): a list of string tokens
  52. Returns:
  53. indices (list): a list of indices corresponding to the tokens
  54. """
  55. return [self.add_token(token) for token in tokens]
  56. #用于检索与标记相关联的索引
  57. def lookup_token(self, token):
  58. """Retrieve the index associated with the token
  59. or the UNK index if token isn't present.
  60. Args:
  61. token (str): the token to look up
  62. Returns:
  63. index (int): the index corresponding to the token
  64. Notes:
  65. `unk_index` needs to be >=0 (having been added into the Vocabulary)
  66. for the UNK functionality
  67. """
  68. if self.unk_index >= 0:
  69. return self._token_to_idx.get(token, self.unk_index)
  70. else:
  71. return self._token_to_idx[token]
  72. #用于返回与给定索引相关联的标记
  73. def lookup_index(self, index):
  74. """Return the token associated with the index
  75. Args:
  76. index (int): the index to look up
  77. Returns:
  78. token (str): the token corresponding to the index
  79. Raises:
  80. KeyError: if the index is not in the Vocabulary
  81. """
  82. if index not in self._idx_to_token:
  83. raise KeyError("the index (%d) is not in the Vocabulary" % index)
  84. return self._idx_to_token[index]
  85. #返回描述词汇表大小的字符串表示
  86. def __str__(self):
  87. return "<Vocabulary(size=%d)>" % len(self)
  88. #返回词汇表中的唯一标记数
  89. def __len__(self):
  90. return len(self._token_to_idx)
  1. #将文本数据向量化,并配合词汇表进行处理
  2. class SurnameVectorizer(object):
  3. """ The Vectorizer which coordinates the Vocabularies and puts them to use"""
  4. def __init__(self, surname_vocab, nationality_vocab):
  5. """
  6. Args:
  7. surname_vocab (Vocabulary): maps characters to integers
  8. nationality_vocab (Vocabulary): maps nationalities to integers
  9. """
  10. self.surname_vocab = surname_vocab
  11. self.nationality_vocab = nationality_vocab
  12. # 将给定的评论文本转换为一个折叠的单热编码向量
  13. def vectorize(self, surname):
  14. """
  15. Args:
  16. surname (str): the surname
  17. Returns:
  18. one_hot (np.ndarray): a collapsed one-hot encoding
  19. """
  20. vocab = self.surname_vocab
  21. one_hot = np.zeros(len(vocab), dtype=np.float32)
  22. for token in surname:
  23. one_hot[vocab.lookup_token(token)] = 1
  24. return one_hot
  25. @classmethod
  26. #从数据框实例化 ReviewVectorizer对象
  27. def from_dataframe(cls, surname_df):
  28. """Instantiate the vectorizer from the dataset dataframe
  29. Args:
  30. surname_df (pandas.DataFrame): the surnames dataset
  31. Returns:
  32. an instance of the SurnameVectorizer
  33. """
  34. surname_vocab = Vocabulary(unk_token="@")
  35. nationality_vocab = Vocabulary(add_unk=False)
  36. for index, row in surname_df.iterrows():
  37. for letter in row.surname:
  38. surname_vocab.add_token(letter)
  39. nationality_vocab.add_token(row.nationality)
  40. return cls(surname_vocab, nationality_vocab)
  41. @classmethod
  42. # 从序列化的字典实例化 ReviewVectorizer对象
  43. def from_serializable(cls, contents):
  44. surname_vocab = Vocabulary.from_serializable(contents['surname_vocab'])
  45. nationality_vocab = Vocabulary.from_serializable(contents['nationality_vocab'])
  46. return cls(surname_vocab=surname_vocab, nationality_vocab=nationality_vocab)
  47. #将 ReviewVectorizer对象序列化为字典,以便缓存或保存
  48. def to_serializable(self):
  49. return {'surname_vocab': self.surname_vocab.to_serializable(),
  50. 'nationality_vocab': self.nationality_vocab.to_serializable()}

4.用多层感知器进行姓氏分类

    第一个线性层将输入向量映射到中间向量,并对该向量应用非线性。第二线性层将中间向量映射到预测向量。

   在最后一步中,可选地应用softmax操作,以确保输出和为1;这就是所谓的“概率”。它是可选的原因与我们使用的损失函数的数学公式有关——交叉熵损失。我们研究了“损失函数”中的交叉熵损失。回想一下,交叉熵损失对于多类分类是最理想的,但是在训练过程中软最大值的计算不仅浪费而且在很多情况下并不稳定。

  1. class SurnameClassifier(nn.Module):
  2. """ 用于对姓氏进行分类的两层多层感知器 """
  3. def __init__(self, input_dim, hidden_dim, output_dim):
  4. """
  5. Args:
  6. input_dim (int): 输入向量的大小
  7. hidden_dim (int): 第一层线性层的输出大小
  8. output_dim (int): 第二层线性层的输出大小
  9. """
  10. super(SurnameClassifier, self).__init__()
  11. # 定义两个线性层
  12. self.fc1 = nn.Linear(input_dim, hidden_dim)
  13. self.fc2 = nn.Linear(hidden_dim, output_dim)
  14. def forward(self, x_in, apply_softmax=False):
  15. """分类器的前向传播
  16. Args:
  17. x_in (torch.Tensor): 输入数据张量。
  18. x_in.shape 应为 (batch, input_dim)
  19. apply_softmax (bool): 是否进行 softmax 激活。
  20. 如果与交叉熵损失一起使用,则应为 False
  21. Returns:
  22. 结果张量。tensor.shape 应为 (batch, output_dim)
  23. """
  24. # 第一层的线性变换,并使用 ReLU 激活函数
  25. intermediate_vector = F.relu(self.fc1(x_in))
  26. # 第二层的线性变换
  27. prediction_vector = self.fc2(intermediate_vector)
  28. if apply_softmax:
  29. # 如果需要应用 softmax 激活函数,则进行 softmax 操作
  30. prediction_vector = F.softmax(prediction_vector, dim=1)
  31. return prediction_vector

5.辅助函数

  1. #创建一个表示训练状态的字典,初始化各种参数和指标
  2. def make_train_state(args):
  3. return {'stop_early': False,
  4. 'early_stopping_step': 0,
  5. 'early_stopping_best_val': 1e8,
  6. 'learning_rate': args.learning_rate,
  7. 'epoch_index': 0,
  8. 'train_loss': [],
  9. 'train_acc': [],
  10. 'val_loss': [],
  11. 'val_acc': [],
  12. 'test_loss': -1,
  13. 'test_acc': -1,
  14. 'model_filename': args.model_state_file}
  15. #处理训练状态的更新
  16. def update_train_state(args, model, train_state):
  17. """Handle the training state updates.
  18. Components:
  19. - Early Stopping: Prevent overfitting.
  20. - Model Checkpoint: Model is saved if the model is better
  21. :param args: main arguments
  22. :param model: model to train
  23. :param train_state: a dictionary representing the training state values
  24. :returns:
  25. a new train_state
  26. """
  27. # 至少保存一个模型
  28. if train_state['epoch_index'] == 0:
  29. torch.save(model.state_dict(), train_state['model_filename'])
  30. train_state['stop_early'] = False
  31. # 性能得到改善,则保存模型
  32. elif train_state['epoch_index'] >= 1:
  33. loss_tm1, loss_t = train_state['val_loss'][-2:]
  34. #如果损失恶化
  35. if loss_t >= train_state['early_stopping_best_val']:
  36. # Update step
  37. train_state['early_stopping_step'] += 1
  38. # 损失减少
  39. else:
  40. # 保存最佳模型
  41. if loss_t < train_state['early_stopping_best_val']:
  42. torch.save(model.state_dict(), train_state['model_filename'])
  43. # 重置提前停止步骤
  44. train_state['early_stopping_step'] = 0
  45. # 早停?
  46. train_state['stop_early'] = \
  47. train_state['early_stopping_step'] >= args.early_stopping_criteria
  48. return train_state
  49. #计算模型预测的准确率
  50. def compute_accuracy(y_pred, y_target):
  51. _, y_pred_indices = y_pred.max(dim=1)
  52. n_correct = torch.eq(y_pred_indices, y_target).sum().item()
  53. return n_correct / len(y_pred_indices) * 100
  54. #设置随机种子
  55. def set_seed_everywhere(seed, cuda):
  56. np.random.seed(seed)
  57. torch.manual_seed(seed)
  58. if cuda:
  59. torch.cuda.manual_seed_all(seed)
  60. #处理文件目录
  61. def handle_dirs(dirpath):
  62. if not os.path.exists(dirpath):
  63. os.makedirs(dirpath)
  64. args = Namespace(
  65. # 数据和路径信息
  66. surname_csv="surnames_with_splits.csv",
  67. vectorizer_file="vectorizer.json",
  68. model_state_file="model.pth",
  69. save_dir="model_storage/ch4/surname_mlp",
  70. # 模型超参数
  71. hidden_dim=300,
  72. # 训练超参数
  73. seed=1337,
  74. num_epochs=5,
  75. early_stopping_criteria=5,
  76. learning_rate=0.001,
  77. batch_size=64,
  78. # 运行时选项
  79. cuda=False,
  80. reload_from_files=False,
  81. expand_filepaths_to_save_dir=True,
  82. )
  83. if args.expand_filepaths_to_save_dir:
  84. args.vectorizer_file = os.path.join(args.save_dir,
  85. args.vectorizer_file)
  86. args.model_state_file = os.path.join(args.save_dir,
  87. args.model_state_file)
  88. print("Expanded filepaths: ")
  89. print("\t{}".format(args.vectorizer_file))
  90. print("\t{}".format(args.model_state_file))
  91. # 检查CUDA
  92. if not torch.cuda.is_available():
  93. args.cuda = False
  94. args.device = torch.device("cuda" if args.cuda else "cpu")
  95. print("Using CUDA: {}".format(args.cuda))
  96. # 为可重复性奠定种子
  97. set_seed_everywhere(args.seed, args.cuda)
  98. #句柄目录
  99. handle_dirs(args.save_dir)
  100. #确定是重新加载已有的数据集和词向量化器,还是创建新的数据集和词向量化器。
  101. if args.reload_from_files:
  102. # training from a checkpoint
  103. print("Reloading!")
  104. dataset = SurnameDataset.load_dataset_and_load_vectorizer(args.surname_csv,
  105. args.vectorizer_file)
  106. else:
  107. # create dataset and vectorizer
  108. print("Creating fresh!")
  109. dataset = SurnameDataset.load_dataset_and_make_vectorizer(args.surname_csv)
  110. dataset.save_vectorizer(args.vectorizer_file)
  111. vectorizer = dataset.get_vectorizer()
  112. classifier = SurnameClassifier(input_dim=len(vectorizer.surname_vocab),
  113. hidden_dim=args.hidden_dim,
  114. output_dim=len(vectorizer.nationality_vocab))

6.模型训练

  1. #模型训练的准备工作
  2. classifier = classifier.to(args.device)
  3. dataset.class_weights = dataset.class_weights.to(args.device)
  4. loss_func = nn.CrossEntropyLoss(dataset.class_weights)
  5. optimizer = optim.Adam(classifier.parameters(), lr=args.learning_rate)
  6. scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer,
  7. mode='min', factor=0.5,
  8. patience=1)
  9. train_state = make_train_state(args)
  10. epoch_bar = tqdm_notebook(desc='training routine',
  11. total=args.num_epochs,
  12. position=0)
  13. dataset.set_split('train')
  14. train_bar = tqdm_notebook(desc='split=train',
  15. total=dataset.get_num_batches(args.batch_size),
  16. position=1,
  17. leave=True)
  18. dataset.set_split('val')
  19. val_bar = tqdm_notebook(desc='split=val',
  20. total=dataset.get_num_batches(args.batch_size),
  21. position=1,
  22. leave=True)
  23. try:
  24. for epoch_index in range(args.num_epochs):
  25. train_state['epoch_index'] = epoch_index
  26. # 迭代训练数据集
  27. # 设置:批量发电机,设置损耗和acc为0
  28. dataset.set_split('train')
  29. batch_generator = generate_batches(dataset,
  30. batch_size=args.batch_size,
  31. device=args.device)
  32. running_loss = 0.0
  33. running_acc = 0.0
  34. classifier.train()
  35. for batch_index, batch_dict in enumerate(batch_generator):
  36. # 训练程序有以下5个步骤:
  37. # --------------------------------------
  38. # 步骤1.将梯度归零
  39. optimizer.zero_grad()
  40. #步骤2.计算输出
  41. y_pred = classifier(batch_dict['x_surname'])
  42. #步骤3.计算损失
  43. loss = loss_func(y_pred, batch_dict['y_nationality'])
  44. loss_t = loss.item()
  45. running_loss += (loss_t - running_loss) / (batch_index + 1)
  46. #步骤4.使用损耗来产生梯度
  47. loss.backward()
  48. #步骤5.使用优化器采取梯度步骤
  49. optimizer.step()
  50. # -----------------------------------------
  51. # 计算准确率
  52. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  53. running_acc += (acc_t - running_acc) / (batch_index + 1)
  54. #更新值
  55. train_bar.set_postfix(loss=running_loss, acc=running_acc,
  56. epoch=epoch_index)
  57. train_bar.update()
  58. train_state['train_loss'].append(running_loss)
  59. train_state['train_acc'].append(running_acc)
  60. #遍历数据集
  61. #设置损耗和acc为0;设置eval模式为on
  62. dataset.set_split('val')
  63. batch_generator = generate_batches(dataset,
  64. batch_size=args.batch_size,
  65. device=args.device)
  66. running_loss = 0.
  67. running_acc = 0.
  68. classifier.eval()
  69. for batch_index, batch_dict in enumerate(batch_generator):
  70. # 输出
  71. y_pred = classifier(batch_dict['x_surname'])
  72. # 计算损失
  73. loss = loss_func(y_pred, batch_dict['y_nationality'])
  74. loss_t = loss.to("cpu").item()
  75. running_loss += (loss_t - running_loss) / (batch_index + 1)
  76. # 计算准确率
  77. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  78. running_acc += (acc_t - running_acc) / (batch_index + 1)
  79. val_bar.set_postfix(loss=running_loss, acc=running_acc,
  80. epoch=epoch_index)
  81. val_bar.update()
  82. train_state['val_loss'].append(running_loss)
  83. train_state['val_acc'].append(running_acc)
  84. train_state = update_train_state(args=args, model=classifier,
  85. train_state=train_state)
  86. scheduler.step(train_state['val_loss'][-1])
  87. if train_state['stop_early']:
  88. break
  89. train_bar.n = 0
  90. val_bar.n = 0
  91. epoch_bar.update()
  92. except KeyboardInterrupt:
  93. print("Exiting loop")
  1. # 使用最佳可用模型计算测试集上的损耗和精度
  2. classifier.load_state_dict(torch.load(train_state['model_filename']))
  3. classifier = classifier.to(args.device)
  4. dataset.class_weights = dataset.class_weights.to(args.device)
  5. loss_func = nn.CrossEntropyLoss(dataset.class_weights)
  6. dataset.set_split('test')
  7. batch_generator = generate_batches(dataset,
  8. batch_size=args.batch_size,
  9. device=args.device)
  10. running_loss = 0.
  11. running_acc = 0.
  12. classifier.eval()
  13. for batch_index, batch_dict in enumerate(batch_generator):
  14. # compute the output
  15. y_pred = classifier(batch_dict['x_surname'])
  16. # compute the loss
  17. loss = loss_func(y_pred, batch_dict['y_nationality'])
  18. loss_t = loss.item()
  19. running_loss += (loss_t - running_loss) / (batch_index + 1)
  20. # compute the accuracy
  21. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  22. running_acc += (acc_t - running_acc) / (batch_index + 1)
  23. train_state['test_loss'] = running_loss
  24. train_state['test_acc'] = running_acc
  25. #输出损失和准确率
  26. print("Test loss: {};".format(train_state['test_loss']))
  27. print("Test Accuracy: {}".format(train_state['test_acc']))

 7.预测结果

     该模型对测试数据的准确性达到50%左右。如果在附带的notebook中运行训练例程,会注意到在训练数据上的性能更高。这是因为模型总是更适合它所训练的数据,所以训练数据的性能并不代表新数据的性能。如果遵循代码,你可以尝试隐藏维度的不同大小,应该注意到性能的提高。然而,这种增长不会很大(尤其是与“用CNN对姓氏进行分类的例子”中的模型相比)。其主要原因是收缩的onehot向量化方法是一种弱表示。虽然它确实简洁地将每个姓氏表示为单个向量,但它丢弃了字符之间的顺序信息,这对于识别起源非常重要。

  1. #使用分类器和矢量化器来预测给定姓名的国籍分
  2. def predict_nationality(name, classifier, vectorizer):
  3. vectorized_name = vectorizer.vectorize(name)
  4. vectorized_name = torch.tensor(vectorized_name).view(1, -1)
  5. result = classifier(vectorized_name, apply_softmax=True)
  6. probability_values, indices = result.max(dim=1)
  7. index = indices.item()
  8. predicted_nationality = vectorizer.nationality_vocab.lookup_index(index)
  9. probability_value = probability_values.item()
  10. return {'nationality': predicted_nationality,
  11. 'probability': probability_value}
  12. #接收用户输入的姓氏,然后使用提供的分类器和矢量化器对该姓氏进行国籍分类预测,并打印出预测结果及其概率
  13. new_surname = input("Enter a surname to classify: ")
  14. classifier = classifier.to("cpu")
  15. prediction = predict_nationality(new_surname, classifier, vectorizer)
  16. print("{} -> {} (p={:0.2f})".format(new_surname,
  17. prediction['nationality'],
  18. prediction['probability']))
  19. #从矢量化器的国籍词汇表中查找索引为 8 的国籍
  20. vectorizer.nationality_vocab.lookup_index(8)
  21. #使用了分类器和矢量化器来对给定的姓名进行国籍分类预测,并返回概率最高的前 k 个国籍预测结果
  22. def predict_topk_nationality(name, classifier, vectorizer, k=5):
  23. vectorized_name = vectorizer.vectorize(name)
  24. vectorized_name = torch.tensor(vectorized_name).view(1, -1)
  25. prediction_vector = classifier(vectorized_name, apply_softmax=True)
  26. probability_values, indices = torch.topk(prediction_vector, k=k)
  27. probability_values = probability_values.detach().numpy()[0]
  28. indices = indices.detach().numpy()[0]
  29. results = []
  30. for prob_value, index in zip(probability_values, indices):
  31. nationality = vectorizer.nationality_vocab.lookup_index(index)
  32. results.append({'nationality': nationality,
  33. 'probability': prob_value})
  34. return results
  35. new_surname = input("Enter a surname to classify: ")
  36. classifier = classifier.to("cpu")
  37. k = int(input("How many of the top predictions to see? "))
  38. if k > len(vectorizer.nationality_vocab):
  39. print("Sorry! That's more than the # of nationalities we have.. defaulting you to max size :)")
  40. k = len(vectorizer.nationality_vocab)
  41. predictions = predict_topk_nationality(new_surname, classifier, vectorizer, k=k)
  42. print("Top {} predictions:".format(k))
  43. print("===================")
  44. for prediction in predictions:
  45. print("{} -> {} (p={:0.2f})".format(new_surname,
  46. prediction['nationality'],
  47. prediction['probability']))

五.实验结果

由于时间原因训练轮数只有5轮,所以结果较差:

损失和准确率:

给定一个姓氏作为字符串,然后获得模型预测:

给定的姓名进行国籍分类预测,并返回概率最高的前 k 个国籍预测结果:

基于卷积神经网络(CNN)实现姓氏分类

一.实验目的

   我们将MLP应用于将姓氏分类到其原籍国的任务。从公开观察到的数据推断人口统计信息(如国籍)具有从产品推荐到确保不同人口统计用户获得公平结果的应用。人口统计和其他自我识别信息统称为“受保护属性”。“在建模和产品中使用这些属性时,必须小心。”我们首先对每个姓氏的字符进行拆分,并像对待“示例:将餐馆评论的情绪分类”中的单词一样对待它们。除了数据上的差异,字符层模型在结构和实现上与基于单词的模型基本相似。

二.CNN的原理

    卷积神经网络(Convolutional Neural Network,CNN)是一种专门用于处理具有网格状拓扑结构数据的人工神经网络。CNN在计算机视觉领域得到了广泛应用,特别是在图像识别、对象检测和图像分类等任务中表现出色。下面是CNN的基本原理和关键概念:

  1. 卷积层(Convolutional Layer):CNN的核心组件之一。卷积层通过应用一系列滤波器(也称为卷积核)来提取输入数据的特征。每个滤波器在输入数据上进行滑动操作(卷积运算),计算出一系列特征映射。这些特征映射捕获了输入数据中的不同局部特征。

  2. 滤波器(Filter):滤波器是卷积层中的参数,用于提取输入数据的特征。每个滤波器都是一个小型的矩阵,其值在训练过程中通过反向传播算法学习得到。每个滤波器在输入数据上进行滑动操作,计算出一个特征映射。

  3. 步幅(Stride):步幅是指滤波器在输入数据上移动的步长。较大的步幅可以减小输出特征图的尺寸,而较小的步幅可以保持输出特征图的尺寸与输入数据相同。

  4. 填充(Padding):填充是在输入数据周围添加额外的值(通常是0),以控制输出特征图的尺寸。填充可以帮助保持特征图的空间维度,避免由于卷积操作导致尺寸减小而丢失信息。

  5. 激活函数(Activation Function):卷积层通常会在卷积运算后应用一个非线性激活函数,如ReLU(Rectified Linear Unit)。激活函数引入了非线性因素,使得网络能够学习复杂的数据模式。

  6. 池化层(Pooling Layer):池化层用于降低特征图的空间维度,并减少模型对位置变化的敏感性。常见的池化操作包括最大池化和平均池化,它们分别取输入区域的最大值或平均值作为输出值。

  7. 全连接层(Fully Connected Layer):全连接层是传统神经网络中的一种层,它将上一层的所有神经元与当前层的所有神经元相连接。在CNN中,全连接层通常用于将卷积和池化层提取的特征转换为最终的输出。

  8. 前向传播(Forward Propagation):在前向传播过程中,输入数据从输入层经过一系列卷积、激活和池化操作后,最终生成输出结果。

  9. 反向传播(Backpropagation):反向传播是用于训练CNN的一种常用方法。它通过计算损失函数对网络参数的梯度,并根据梯度更新参数。这个过程反复进行,直到模型收敛到最优解。

CNN的结构: 

    CNN通过多层卷积和池化操作逐渐提取输入数据的高级特征,然后通过全连接层将这些特征映射到最终的输出空间。这种层级结构使得CNN能够有效地处理大规模图像数据,并在图像识别和分类等任务中取得优秀的性能。

三.数据集

     姓氏数据集,它收集了来自18个不同国家的10,000个姓氏,这些姓氏是作者从互联网上不同的姓名来源收集的。该数据集将在本课程实验的几个示例中重用,并具有一些使其有趣的属性。第一个性质是它是相当不平衡的。排名前三的课程占数据的60%以上:27%是英语,21%是俄语,14%是阿拉伯语。剩下的15个民族的频率也在下降——这也是语言特有的特性。第二个特点是,在国籍和姓氏正字法(拼写)之间有一种有效和直观的关系。有些拼写变体与原籍国联系非常紧密(比如“O ‘Neill”、“Antonopoulos”、“Nagasawa”或“Zhu”)。

     为了创建最终的数据集,我们从一个比课程补充材料中包含的版本处理更少的版本开始,并执行了几个数据集修改操作。第一个目的是减少这种不平衡——原始数据集中70%以上是俄文,这可能是由于抽样偏差或俄文姓氏的增多。为此,我们通过选择标记为俄语的姓氏的随机子集对这个过度代表的类进行子样本。接下来,我们根据国籍对数据集进行分组,并将数据集分为三个部分:70%到训练数据集,15%到验证数据集,最后15%到测试数据集,以便跨这些部分的类标签分布具有可比性。

对数据集进行预处理:

  1. import collections
  2. import numpy as np
  3. import pandas as pd
  4. import re
  5. from argparse import Namespace
  6. # 定义命令行参数
  7. args = Namespace(
  8. raw_dataset_csv="surnames.csv", # 原始数据集文件名
  9. train_proportion=0.7, # 训练集比例
  10. val_proportion=0.15, # 验证集比例
  11. test_proportion=0.15, # 测试集比例
  12. output_munged_csv="surnames_with_splits.csv", # 输出文件名
  13. seed=1337 # 随机种子
  14. )
  15. # 读取原始数据集
  16. surnames = pd.read_csv(args.raw_dataset_csv, header=0)
  17. surnames.head()
  18. # 获取唯一的类别(国籍)
  19. set(surnames.nationality)
  20. # 按国籍划分训练集
  21. # 创建字典
  22. by_nationality = collections.defaultdict(list)
  23. for _, row in surnames.iterrows():
  24. by_nationality[row.nationality].append(row.to_dict())
  25. # 创建划分后的数据
  26. final_list = []
  27. np.random.seed(args.seed)
  28. # 按国籍划分并随机打乱数据
  29. for _, item_list in sorted(by_nationality.items()):
  30. np.random.shuffle(item_list)
  31. n = len(item_list)
  32. n_train = int(args.train_proportion * n)
  33. n_val = int(args.val_proportion * n)
  34. n_test = int(args.test_proportion * n)
  35. # 为每个数据点添加划分属性
  36. for item in item_list[:n_train]:
  37. item['split'] = 'train'
  38. for item in item_list[n_train:n_train+n_val]:
  39. item['split'] = 'val'
  40. for item in item_list[n_train+n_val:]:
  41. item['split'] = 'test'
  42. # 添加到最终列表中
  43. final_list.extend(item_list)
  44. # 将划分后的数据写入文件
  45. final_surnames = pd.DataFrame(final_list)
  46. final_surnames.head()
  47. # 将处理后的数据写入CSV文件
  48. final_surnames.to_csv(args.output_munged_csv, index=False)

结果:

查看前几行数据:

 唯一类别:

数据集的划分结果:

查看划分后的数据集:

四.实验步骤

1.导入必要的第三方库

  1. from argparse import Namespace
  2. from collections import Counter
  3. import json
  4. import os
  5. import string
  6. import numpy as np
  7. import pandas as pd
  8. import torch
  9. import torch.nn as nn
  10. import torch.nn.functional as F
  11. import torch.optim as optim
  12. from torch.utils.data import Dataset, DataLoader
  13. from tqdm import tqdm_notebook

2.数据集类的加载和处理文本

      SurnameDataset的实现与“Example: classification of Sentiment of Restaurant Reviews”中的ReviewDataset几乎相同,只是在getitem方法的实现方式上略有不同。回想一下,本课程中呈现的数据集类继承自PyTorch的数据集类,因此,我们需要实现两个函数:__getitem方法,它在给定索引时返回一个数据点;以及len方法,该方法返回数据集的长度。

  1. #创建一个自定义的数据集类来加载和处理文本数据
  2. #划分训练、验证和测试集,设置数据集大小,以及构建查找字典
  3. class SurnameDataset(Dataset):
  4. def __init__(self, surname_df, vectorizer):
  5. """
  6. Args:
  7. name_df (pandas.DataFrame): the dataset
  8. vectorizer (SurnameVectorizer): vectorizer instatiated from dataset
  9. """
  10. self.surname_df = surname_df
  11. self._vectorizer = vectorizer
  12. self.train_df = self.surname_df[self.surname_df.split=='train']
  13. self.train_size = len(self.train_df)
  14. self.val_df = self.surname_df[self.surname_df.split=='val']
  15. self.validation_size = len(self.val_df)
  16. self.test_df = self.surname_df[self.surname_df.split=='test']
  17. self.test_size = len(self.test_df)
  18. self._lookup_dict = {'train': (self.train_df, self.train_size),
  19. 'val': (self.val_df, self.validation_size),
  20. 'test': (self.test_df, self.test_size)}
  21. self.set_split('train')
  22. # Class weights
  23. class_counts = surname_df.nationality.value_counts().to_dict()
  24. def sort_key(item):
  25. return self._vectorizer.nationality_vocab.lookup_token(item[0])
  26. sorted_counts = sorted(class_counts.items(), key=sort_key)
  27. frequencies = [count for _, count in sorted_counts]
  28. self.class_weights = 1.0 / torch.tensor(frequencies, dtype=torch.float32)
  29. #加载数据集并生成新的向量化器
  30. @classmethod
  31. def load_dataset_and_make_vectorizer(cls, surname_csv):
  32. """Load dataset and make a new vectorizer from scratch
  33. Args:
  34. surname_csv (str): location of the dataset
  35. Returns:
  36. an instance of SurnameDataset
  37. """
  38. surname_df = pd.read_csv(surname_csv)
  39. train_surname_df = surname_df[surname_df.split=='train']
  40. return cls(surname_df, SurnameVectorizer.from_dataframe(train_surname_df))
  41. #加载数据集和相应的向量化器,用于重新使用已缓存的向量化器
  42. @classmethod
  43. def load_dataset_and_load_vectorizer(cls, surname_csv, vectorizer_filepath):
  44. """Load dataset and the corresponding vectorizer.
  45. Used in the case in the vectorizer has been cached for re-use
  46. Args:
  47. surname_csv (str): location of the dataset
  48. vectorizer_filepath (str): location of the saved vectorizer
  49. Returns:
  50. an instance of SurnameDataset
  51. """
  52. surname_df = pd.read_csv(surname_csv)
  53. vectorizer = cls.load_vectorizer_only(vectorizer_filepath)
  54. return cls(surname_df, vectorizer)
  55. #从文件中加载向量化器
  56. @staticmethod
  57. def load_vectorizer_only(vectorizer_filepath):
  58. """a static method for loading the vectorizer from file
  59. Args:
  60. vectorizer_filepath (str): the location of the serialized vectorizer
  61. Returns:
  62. an instance of SurnameDataset
  63. """
  64. with open(vectorizer_filepath) as fp:
  65. return SurnameVectorizer.from_serializable(json.load(fp))
  66. #将向量化器保存到磁盘
  67. def save_vectorizer(self, vectorizer_filepath):
  68. """saves the vectorizer to disk using json
  69. Args:
  70. vectorizer_filepath (str): the location to save the vectorizer
  71. """
  72. with open(vectorizer_filepath, "w") as fp:
  73. json.dump(self._vectorizer.to_serializable(), fp)
  74. #回向量化器对象
  75. def get_vectorizer(self):
  76. """ returns the vectorizer """
  77. return self._vectorizer
  78. #划分数据集
  79. def set_split(self, split="train"):
  80. """ selects the splits in the dataset using a column in the dataframe """
  81. self._target_split = split
  82. self._target_df, self._target_size = self._lookup_dict[split]
  83. #返回指定数据集的大小
  84. def __len__(self):
  85. return self._target_size
  86. #根据指定的批量大小返回数据集中的批次数量
  87. def __getitem__(self, index):
  88. """the primary entry point method for PyTorch datasets
  89. Args:
  90. index (int): the index to the data point
  91. Returns:
  92. a dictionary holding the data point's features (x_data) and label (y_target)
  93. """
  94. row = self._target_df.iloc[index]
  95. surname_matrix = \
  96. self._vectorizer.vectorize(row.surname)
  97. nationality_index = \
  98. self._vectorizer.nationality_vocab.lookup_token(row.nationality)
  99. return {'x_surname': surname_matrix,
  100. 'y_nationality': nationality_index}
  101. #生成批次数据
  102. def get_num_batches(self, batch_size):
  103. """Given a batch size, return the number of batches in the dataset
  104. Args:
  105. batch_size (int)
  106. Returns:
  107. number of batches in the dataset
  108. """
  109. return len(self) // batch_size
  110. def generate_batches(dataset, batch_size, shuffle=True,
  111. drop_last=True, device="cpu"):
  112. """
  113. A generator function which wraps the PyTorch DataLoader. It will
  114. ensure each tensor is on the write device location.
  115. """
  116. dataloader = DataLoader(dataset=dataset, batch_size=batch_size,
  117. shuffle=shuffle, drop_last=drop_last)
  118. for data_dict in dataloader:
  119. out_data_dict = {}
  120. for name, tensor in data_dict.items():
  121. out_data_dict[name] = data_dict[name].to(device)
  122. yield out_data_dict

3.将姓氏字符串转换为向量化的minibatches

    为了使用字符对姓氏进行分类,我们使用词汇表、向量化器和DataLoader将姓氏字符串转换为向量化的minibatches。这些数据结构与“Example: Classifying Sentiment of Restaurant Reviews”中使用的数据结构相同,它们举例说明了一种多态性,这种多态性将姓氏的字符标记与Yelp评论的单词标记相同对待。数据不是通过将字令牌映射到整数来向量化的,而是通过将字符映射到整数来向量化的。

  1. class Vocabulary(object):
  2. """用于处理文本并提取词汇的类"""
  3. def __init__(self, token_to_idx=None, add_unk=True, unk_token="<UNK>"):
  4. """
  5. 初始化Vocabulary对象
  6. Args:
  7. token_to_idx (dict): 一个词汇到索引的映射字典
  8. add_unk (bool): 是否添加UNK标记的标志
  9. unk_token (str): 要添加到词汇表中的UNK标记
  10. """
  11. if token_to_idx is None:
  12. token_to_idx = {}
  13. self._token_to_idx = token_to_idx
  14. # 创建索引到词汇的映射
  15. self._idx_to_token = {idx: token
  16. for token, idx in self._token_to_idx.items()}
  17. self._add_unk = add_unk
  18. self._unk_token = unk_token
  19. self.unk_index = -1
  20. # 如果需要添加UNK标记,则添加它
  21. if add_unk:
  22. self.unk_index = self.add_token(unk_token)
  23. def to_serializable(self):
  24. """返回一个可序列化的字典"""
  25. return {'token_to_idx': self._token_to_idx,
  26. 'add_unk': self._add_unk,
  27. 'unk_token': self._unk_token}
  28. @classmethod
  29. def from_serializable(cls, contents):
  30. """从一个可序列化的字典中实例化Vocabulary对象"""
  31. return cls(**contents)
  32. def add_token(self, token):
  33. """根据词汇更新映射字典
  34. Args:
  35. token (str): 要添加到词汇表中的词汇
  36. Returns:
  37. index (int): 词汇对应的整数索引
  38. """
  39. try:
  40. index = self._token_to_idx[token]
  41. except KeyError:
  42. index = len(self._token_to_idx)
  43. self._token_to_idx[token] = index
  44. self._idx_to_token[index] = token
  45. return index
  46. def add_many(self, tokens):
  47. """将一个词汇列表添加到词汇表中
  48. Args:
  49. tokens (list): 一个字符串词汇列表
  50. Returns:
  51. indices (list): 与词汇对应的整数索引列表
  52. """
  53. return [self.add_token(token) for token in tokens]
  54. def lookup_token(self, token):
  55. """检索与词汇关联的索引或UNK索引(如果词汇不存在)。
  56. Args:
  57. token (str): 要查找的词汇
  58. Returns:
  59. index (int): 与词汇对应的整数索引
  60. Notes:
  61. UNK功能需要unk_index >=0(已添加到词汇表中)
  62. """
  63. if self.unk_index >= 0:
  64. return self._token_to_idx.get(token, self.unk_index)
  65. else:
  66. return self._token_to_idx[token]
  67. def lookup_index(self, index):
  68. """返回与索引关联的词汇
  69. Args:
  70. index (int): 要查找的索引
  71. Returns:
  72. token (str): 与索引对应的词汇
  73. Raises:
  74. KeyError: 如果索引不在词汇表中
  75. """
  76. if index not in self._idx_to_token:
  77. raise KeyError("索引(%d)不在词汇表中" % index)
  78. return self._idx_to_token[index]
  79. def __str__(self):
  80. return "<Vocabulary(size=%d)>" % len(self)
  81. def __len__(self):
  82. return len(self._token_to_idx)
  1. class SurnameVectorizer(object):
  2. """姓氏矢量化器,协调词汇表并将其应用于数据"""
  3. def __init__(self, surname_vocab, nationality_vocab, max_surname_length):
  4. """
  5. Args:
  6. surname_vocab (Vocabulary): 将字符映射到整数的词汇表
  7. nationality_vocab (Vocabulary): 将国籍映射到整数的词汇表
  8. max_surname_length (int): 最长姓氏的长度
  9. """
  10. self.surname_vocab = surname_vocab
  11. self.nationality_vocab = nationality_vocab
  12. self._max_surname_length = max_surname_length
  13. def vectorize(self, surname):
  14. """
  15. Args:
  16. surname (str): 姓氏
  17. Returns:
  18. one_hot_matrix (np.ndarray): 一个独热向量矩阵
  19. """
  20. # 创建一个全零矩阵
  21. one_hot_matrix_size = (len(self.surname_vocab), self._max_surname_length)
  22. one_hot_matrix = np.zeros(one_hot_matrix_size, dtype=np.float32)
  23. # 将姓氏中的字符转换为独热向量
  24. for position_index, character in enumerate(surname):
  25. character_index = self.surname_vocab.lookup_token(character)
  26. one_hot_matrix[character_index][position_index] = 1
  27. return one_hot_matrix
  28. @classmethod
  29. def from_dataframe(cls, surname_df):
  30. """从数据框实例化矢量化器
  31. Args:
  32. surname_df (pandas.DataFrame): 姓氏数据集
  33. Returns:
  34. SurnameVectorizer的一个实例
  35. """
  36. surname_vocab = Vocabulary(unk_token="@")
  37. nationality_vocab = Vocabulary(add_unk=False)
  38. max_surname_length = 0
  39. for index, row in surname_df.iterrows():
  40. max_surname_length = max(max_surname_length, len(row.surname))
  41. for letter in row.surname:
  42. surname_vocab.add_token(letter)
  43. nationality_vocab.add_token(row.nationality)
  44. return cls(surname_vocab, nationality_vocab, max_surname_length)
  45. @classmethod
  46. def from_serializable(cls, contents):
  47. surname_vocab = Vocabulary.from_serializable(contents['surname_vocab'])
  48. nationality_vocab = Vocabulary.from_serializable(contents['nationality_vocab'])
  49. return cls(surname_vocab=surname_vocab, nationality_vocab=nationality_vocab,
  50. max_surname_length=contents['max_surname_length'])
  51. def to_serializable(self):
  52. return {'surname_vocab': self.surname_vocab.to_serializable(),
  53. 'nationality_vocab': self.nationality_vocab.to_serializable(),
  54. 'max_surname_length': self._max_surname_length}

4.用卷积神经网络进行姓氏分类

  1. class SurnameClassifier(nn.Module):
  2. def __init__(self, initial_num_channels, num_classes, num_channels):
  3. """
  4. Args:
  5. initial_num_channels (int): 输入特征向量的大小
  6. num_classes (int): 输出预测向量的大小
  7. num_channels (int): 网络中使用的常数通道大小
  8. """
  9. super(SurnameClassifier, self).__init__()
  10. # 定义卷积网络层
  11. self.convnet = nn.Sequential(
  12. nn.Conv1d(in_channels=initial_num_channels,
  13. out_channels=num_channels, kernel_size=3),
  14. nn.ELU(), # 使用ELU激活函数
  15. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  16. kernel_size=3, stride=2), # 步长为2的卷积层
  17. nn.ELU(),
  18. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  19. kernel_size=3, stride=2), # 步长为2的卷积层
  20. nn.ELU(),
  21. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  22. kernel_size=3), # 没有步长的卷积层
  23. nn.ELU()
  24. )
  25. # 全连接层,将卷积层的输出映射到预测向量的大小
  26. self.fc = nn.Linear(num_channels, num_classes)
  27. def forward(self, x_surname, apply_softmax=False):
  28. """分类器的前向传播
  29. Args:
  30. x_surname (torch.Tensor): 输入数据张量。
  31. x_surname.shape 应为 (batch, initial_num_channels, max_surname_length)
  32. apply_softmax (bool): softmax激活的标志
  33. 如果与交叉熵损失一起使用,应为false
  34. Returns:
  35. 结果张量。tensor.shape 应为 (batch, num_classes)
  36. """
  37. # 使用卷积网络进行特征提取
  38. features = self.convnet(x_surname).squeeze(dim=2)
  39. # 将提取的特征通过全连接层进行预测
  40. prediction_vector = self.fc(features)
  41. # 如果需要应用softmax激活函数,则进行softmax操作
  42. if apply_softmax:
  43. prediction_vector = F.softmax(prediction_vector, dim=1)
  44. return prediction_vector

5.辅助函数

  1. #创建一个表示训练状态的字典,初始化各种参数和指标
  2. def make_train_state(args):
  3. return {'stop_early': False,
  4. 'early_stopping_step': 0,
  5. 'early_stopping_best_val': 1e8,
  6. 'learning_rate': args.learning_rate,
  7. 'epoch_index': 0,
  8. 'train_loss': [],
  9. 'train_acc': [],
  10. 'val_loss': [],
  11. 'val_acc': [],
  12. 'test_loss': -1,
  13. 'test_acc': -1,
  14. 'model_filename': args.model_state_file}
  15. #处理训练状态的更新
  16. def update_train_state(args, model, train_state):
  17. """Handle the training state updates.
  18. Components:
  19. - Early Stopping: Prevent overfitting.
  20. - Model Checkpoint: Model is saved if the model is better
  21. :param args: main arguments
  22. :param model: model to train
  23. :param train_state: a dictionary representing the training state values
  24. :returns:
  25. a new train_state
  26. """
  27. # 至少保存一个模型
  28. if train_state['epoch_index'] == 0:
  29. torch.save(model.state_dict(), train_state['model_filename'])
  30. train_state['stop_early'] = False
  31. # 性能得到改善,则保存模型
  32. elif train_state['epoch_index'] >= 1:
  33. loss_tm1, loss_t = train_state['val_loss'][-2:]
  34. #如果损失恶化
  35. if loss_t >= train_state['early_stopping_best_val']:
  36. # Update step
  37. train_state['early_stopping_step'] += 1
  38. # 损失减少
  39. else:
  40. # 保存最佳模型
  41. if loss_t < train_state['early_stopping_best_val']:
  42. torch.save(model.state_dict(), train_state['model_filename'])
  43. # 重置提前停止步骤
  44. train_state['early_stopping_step'] = 0
  45. # 早停?
  46. train_state['stop_early'] = \
  47. train_state['early_stopping_step'] >= args.early_stopping_criteria
  48. return train_state
  49. #计算模型预测的准确率
  50. def compute_accuracy(y_pred, y_target):
  51. _, y_pred_indices = y_pred.max(dim=1)
  52. n_correct = torch.eq(y_pred_indices, y_target).sum().item()
  53. return n_correct / len(y_pred_indices) * 100
  54. #设置随机种子
  55. def set_seed_everywhere(seed, cuda):
  56. np.random.seed(seed)
  57. torch.manual_seed(seed)
  58. if cuda:
  59. torch.cuda.manual_seed_all(seed)
  60. #处理文件目录
  61. def handle_dirs(dirpath):
  62. if not os.path.exists(dirpath):
  63. os.makedirs(dirpath)
  64. args = Namespace(
  65. # 数据和路径信息
  66. surname_csv="surnames_with_splits.csv",
  67. vectorizer_file="vectorizer.json",
  68. model_state_file="model.pth",
  69. save_dir="model_storage/ch4/surname_mlp",
  70. # 模型超参数
  71. hidden_dim=300,
  72. # 训练超参数
  73. seed=1337,
  74. num_epochs=5,
  75. early_stopping_criteria=5,
  76. learning_rate=0.001,
  77. batch_size=64,
  78. # 运行时选项
  79. cuda=False,
  80. reload_from_files=False,
  81. expand_filepaths_to_save_dir=True,
  82. )
  83. if args.expand_filepaths_to_save_dir:
  84. args.vectorizer_file = os.path.join(args.save_dir,
  85. args.vectorizer_file)
  86. args.model_state_file = os.path.join(args.save_dir,
  87. args.model_state_file)
  88. print("Expanded filepaths: ")
  89. print("\t{}".format(args.vectorizer_file))
  90. print("\t{}".format(args.model_state_file))
  91. # 检查CUDA
  92. if not torch.cuda.is_available():
  93. args.cuda = False
  94. args.device = torch.device("cuda" if args.cuda else "cpu")
  95. print("Using CUDA: {}".format(args.cuda))
  96. # 为可重复性奠定种子
  97. set_seed_everywhere(args.seed, args.cuda)
  98. #句柄目录
  99. handle_dirs(args.save_dir)
  100. #确定是重新加载已有的数据集和词向量化器,还是创建新的数据集和词向量化器。
  101. if args.reload_from_files:
  102. # training from a checkpoint
  103. print("Reloading!")
  104. dataset = SurnameDataset.load_dataset_and_load_vectorizer(args.surname_csv,
  105. args.vectorizer_file)
  106. else:
  107. # create dataset and vectorizer
  108. print("Creating fresh!")
  109. dataset = SurnameDataset.load_dataset_and_make_vectorizer(args.surname_csv)
  110. dataset.save_vectorizer(args.vectorizer_file)
  111. vectorizer = dataset.get_vectorizer()
  112. classifier = SurnameClassifier(input_dim=len(vectorizer.surname_vocab),
  113. hidden_dim=args.hidden_dim,
  114. output_dim=len(vectorizer.nationality_vocab))

6.模型训练

    与“Example: Classifying Sentiment of Restaurant Reviews”中的训练循环相比,本例的训练循环除了变量名以外几乎是相同的。具体来说,显示了使用不同的key从batch_dict中获取数据。除了外观上的差异,训练循环的功能保持不变。利用训练数据,计算模型输出、损失和梯度。然后,使用梯度来更新模型。

  1. epoch_bar = tqdm_notebook(desc='训练过程', # 创建一个进度条显示训练过程
  2. total=args.num_epochs, # 设置总的迭代次数
  3. position=0) # 设置进度条位置
  4. # 将数据集设置为训练集并创建一个训练集进度条
  5. dataset.set_split('train')
  6. train_bar = tqdm_notebook(desc='训练集', # 创建一个显示训练集进度的进度条
  7. total=dataset.get_num_batches(args.batch_size),
  8. position=1,
  9. leave=True)
  10. # 将数据集设置为验证集并创建一个验证集进度条
  11. dataset.set_split('val')
  12. val_bar = tqdm_notebook(desc='验证集', # 创建一个显示验证集进度的进度条
  13. total=dataset.get_num_batches(args.batch_size),
  14. position=1,
  15. leave=True)
  16. try:
  17. for epoch_index in range(args.num_epochs): # 循环迭代每个epoch
  18. train_state['epoch_index'] = epoch_index
  19. # 遍历训练数据集
  20. # 设置:批次生成器,将损失和准确率设置为0,设置为训练模式
  21. dataset.set_split('train')
  22. batch_generator = generate_batches(dataset,
  23. batch_size=args.batch_size,
  24. device=args.device)
  25. running_loss = 0.0
  26. running_acc = 0.0
  27. classifier.train() # 设置模型为训练模式
  28. for batch_index, batch_dict in enumerate(batch_generator):
  29. # 训练过程的5个步骤:
  30. # --------------------------------------
  31. # 步骤1. 梯度清零
  32. optimizer.zero_grad()
  33. # 步骤2. 计算输出
  34. y_pred = classifier(batch_dict['x_surname'])
  35. # 步骤3. 计算损失
  36. loss = loss_func(y_pred, batch_dict['y_nationality'])
  37. loss_t = loss.item()
  38. running_loss += (loss_t - running_loss) / (batch_index + 1)
  39. # 步骤4. 使用损失计算梯度
  40. loss.backward()
  41. # 步骤5. 使用优化器更新参数
  42. optimizer.step()
  43. # -----------------------------------------
  44. # 计算准确率
  45. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  46. running_acc += (acc_t - running_acc) / (batch_index + 1)
  47. # 更新进度条
  48. train_bar.set_postfix(loss=running_loss, acc=running_acc,
  49. epoch=epoch_index)
  50. train_bar.update()
  51. train_state['train_loss'].append(running_loss)
  52. train_state['train_acc'].append(running_acc)
  53. # 遍历验证数据集
  54. # 设置:批次生成器,将损失和准确率设置为0,设置为评估模式
  55. dataset.set_split('val')
  56. batch_generator = generate_batches(dataset,
  57. batch_size=args.batch_size,
  58. device=args.device)
  59. running_loss = 0.
  60. running_acc = 0.
  61. classifier.eval() # 设置模型为评估模式
  62. for batch_index, batch_dict in enumerate(batch_generator):
  63. # 计算输出
  64. y_pred = classifier(batch_dict['x_surname'])
  65. # 步骤3. 计算损失
  66. loss = loss_func(y_pred, batch_dict['y_nationality'])
  67. loss_t = loss.item()
  68. running_loss += (loss_t - running_loss) / (batch_index + 1)
  69. # 计算准确率
  70. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  71. running_acc += (acc_t - running_acc) / (batch_index + 1)
  72. val_bar.set_postfix(loss=running_loss, acc=running_acc,
  73. epoch=epoch_index)
  74. val_bar.update()
  75. train_state['val_loss'].append(running_loss)
  76. train_state['val_acc'].append(running_acc)
  77. train_state = update_train_state(args=args, model=classifier,
  78. train_state=train_state)
  79. scheduler.step(train_state['val_loss'][-1])
  80. if train_state['stop_early']:
  81. break
  82. train_bar.n = 0
  83. val_bar.n = 0
  84. epoch_bar.update()
  85. except KeyboardInterrupt:
  86. print("Exiting loop")

7.预测结果

      该模型对测试数据的准确性达到50%左右。如果在附带的notebook中运行训练例程,会注意到在训练数据上的性能更高。这是因为模型总是更适合它所训练的数据,所以训练数据的性能并不代表新数据的性能。如果遵循代码,你可以尝试隐藏维度的不同大小,应该注意到性能的提高。然而,这种增长不会很大(尤其是与“用CNN对姓氏进行分类的例子”中的模型相比)。其主要原因是收缩的onehot向量化方法是一种弱表示。虽然它确实简洁地将每个姓氏表示为单个向量,但它丢弃了字符之间的顺序信息,这对于识别起源非常重要。

  1. # 加载模型权重
  2. classifier.load_state_dict(torch.load(train_state['model_filename']))
  3. # 将模型移动到指定的设备上
  4. classifier = classifier.to(args.device)
  5. # 将类别权重也移动到指定的设备上
  6. dataset.class_weights = dataset.class_weights.to(args.device)
  7. # 使用交叉熵损失函数,并考虑类别权重
  8. loss_func = nn.CrossEntropyLoss(dataset.class_weights)
  9. # 设置数据集为测试集,并生成批次数据
  10. dataset.set_split('test')
  11. batch_generator = generate_batches(dataset,
  12. batch_size=args.batch_size,
  13. device=args.device)
  14. running_loss = 0.
  15. running_acc = 0.
  16. classifier.eval() # 设置模型为评估模式
  17. # 遍历测试数据集
  18. for batch_index, batch_dict in enumerate(batch_generator):
  19. # 计算模型输出
  20. y_pred = classifier(batch_dict['x_surname'])
  21. # 计算损失
  22. loss = loss_func(y_pred, batch_dict['y_nationality'])
  23. loss_t = loss.item()
  24. running_loss += (loss_t - running_loss) / (batch_index + 1)
  25. # 计算准确率
  26. acc_t = compute_accuracy(y_pred, batch_dict['y_nationality'])
  27. running_acc += (acc_t - running_acc) / (batch_index + 1)
  28. # 将测试结果保存到训练状态中
  29. train_state['test_loss'] = running_loss
  30. train_state['test_acc'] = running_acc
  31. #输出损失和准确率
  32. print("Test loss: {};".format(train_state['test_loss']))
  33. print("Test Accuracy: {}".format(train_state['test_acc']))
  1. def predict_nationality(surname, classifier, vectorizer):
  2. """预测一个新姓氏的国籍
  3. Args:
  4. surname (str): 待分类的姓氏
  5. classifier (SurnameClassifer): 分类器的实例
  6. vectorizer (SurnameVectorizer): 对应的矢量化器
  7. Returns:
  8. 包含最可能的国籍及其概率的字典
  9. """
  10. # 将姓氏进行矢量化
  11. vectorized_surname = vectorizer.vectorize(surname)
  12. # 将矢量化后的姓氏转换为张量,并增加一个维度
  13. vectorized_surname = torch.tensor(vectorized_surname).unsqueeze(0)
  14. # 使用分类器进行预测,并应用softmax函数
  15. result = classifier(vectorized_surname, apply_softmax=True)
  16. # 获取概率最大的值及其索引
  17. probability_values, indices = result.max(dim=1)
  18. index = indices.item()
  19. # 根据索引查找对应的国籍
  20. predicted_nationality = vectorizer.nationality_vocab.lookup_index(index)
  21. probability_value = probability_values.item()
  22. return {'nationality': predicted_nationality, 'probability': probability_value}
  23. new_surname = input("Enter a surname to classify: ") # 输入待分类的姓氏
  24. classifier = classifier.cpu() # 将分类器移动到CPU上进行预测
  25. prediction = predict_nationality(new_surname, classifier, vectorizer) # 预测姓氏的国籍
  26. print("{} -> {} (p={:0.2f})".format(new_surname, # 打印预测结果
  27. prediction['nationality'],
  28. prediction['probability']))
  29. def predict_topk_nationality(surname, classifier, vectorizer, k=5):
  30. """预测一个新姓氏的前K个国籍
  31. Args:
  32. surname (str): 待分类的姓氏
  33. classifier (SurnameClassifer): 分类器的实例
  34. vectorizer (SurnameVectorizer): 对应的矢量化器
  35. k (int): 要返回的前K个国籍的数量
  36. Returns:
  37. 包含字典的列表,每个字典代表一个国籍及其概率
  38. """
  39. # 将姓氏进行矢量化
  40. vectorized_surname = vectorizer.vectorize(surname)
  41. vectorized_surname = torch.tensor(vectorized_surname).unsqueeze(dim=0)
  42. # 获取预测向量
  43. prediction_vector = classifier(vectorized_surname, apply_softmax=True)
  44. # 获取概率最高的K个值和对应的索引
  45. probability_values, indices = torch.topk(prediction_vector, k=k)
  46. # 将结果转换为numpy数组
  47. probability_values = probability_values[0].detach().numpy()
  48. indices = indices[0].detach().numpy()
  49. results = []
  50. # 遍历获取前K个预测结果
  51. for kth_index in range(k):
  52. nationality = vectorizer.nationality_vocab.lookup_index(indices[kth_index])
  53. probability_value = probability_values[kth_index]
  54. results.append({'nationality': nationality,
  55. 'probability': probability_value})
  56. return results
  57. new_surname = input("Enter a surname to classify: ") # 输入待分类的姓氏
  58. k = int(input("How many of the top predictions to see? ")) # 选择要查看的前K个预测结果
  59. if k > len(vectorizer.nationality_vocab):
  60. print("Sorry! That's more than the # of nationalities we have.. defaulting you to max size :)")
  61. k = len(vectorizer.nationality_vocab)
  62. # 获取前K个预测结果
  63. predictions = predict_topk_nationality(new_surname, classifier, vectorizer, k=k)
  64. print("Top {} predictions:".format(k))
  65. print("===================")
  66. for prediction in predictions:
  67. # 打印每个预测结果
  68. print("{} -> {} (p={:0.2f})".format(new_surname,
  69. prediction['nationality'],
  70. prediction['probability']))

五.实验结果

由于时间原因训练轮数只有5轮,所以结果较差:

损失和准确率:

给定一个姓氏作为字符串,然后获得模型预测:

给定的姓名进行国籍分类预测,并返回概率最高的前 k 个国籍预测结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/889133
推荐阅读
相关标签
  

闽ICP备14008679号