当前位置:   article > 正文

「PyTorch自然语言处理系列」5. 词嵌入和类型(下)

agnews数据集多少年

来源 |  Natural Language Processing with PyTorch

作者 | Rao,McMahan

译者 | Liangchu

校对 | gongyouliu

编辑 | auroral-L

全文共5190字,预计阅读时间40分钟。

上下拉动翻看这个目录

5.1 为什么要学习嵌入?
  5.1.1 嵌入的有效性
  5.1.2 学习词嵌入的方式
  5.1.3 预训练词嵌入的实践
   5.1.3.1 加载嵌入
   5.1.3.2 词嵌入之间的关系
 5.2 示例:学习词嵌入的连续词袋
  5.2.1 Frankenstein数据集
  5.2.2 Vocabulary,Vectorizer和DataLoader
  5.2.3. CBOWClassifier模型
  5.2.4 训练例程
  5.2.5 模型评估和预测

5.3 示例:使用预训练嵌入用于文档分类的迁移学习
  5.3.1 AG News数据集
  5.3.2 Vocabulary,Vectorizer和DataLoader
  5.3.3 NewsClassifier模型
  5.3.4 训练例程
  5.3.5 模型评估和分类
  5.3.5.1 在测试集上评估
  5.3.5.2 预测新的新闻头条的类别
 5.4 总结

5.3 示例:使用预训练嵌入用于文档分类的迁移学习

前面的示例使用了一个嵌入层(embedding layer)做简单分类,这个例子的构建基于三个方面:首先加载预训练的词嵌入,然后通过对整个新闻文章进行分类来微调这些预训练的嵌入,最后使用卷积神经网络来捕获单词之间的空间关系。

在本例中,我们使用 AG News 数据集。为了对 AG News 中的单词序列进行建模,我们引入了Vocabulary类的一个变体SequenceVocabulary,以绑定一些对建模序列至关重要的token。Vectorizer将演示如何使用这个类。

在描述数据集以及向量化的minibatch是如何构建的之后,我们将逐步将预先训练好的单词向量加载到一个Embedding层中,并演示如何自定义它们。然后,该模型将预训练嵌入层与“示例:使用 CNN 对姓氏进行分类”一节中使用的CNN相结合使用。为了将模型的复杂性扩展到更真实的结构,我们还确定了使用正则化技术dropout的地方。接下来我们讨论训练例程。与第四章和本章中的前两个示例相比,训练例程几乎没什么变化,对此你并不会感到奇怪。最后,我们通过在测试集上对模型进行评价并讨论结果来总结这个例子。

5.3.1 AG News数据集

AG News 数据集是在2005年学术界为实验数据挖掘和信息提取方法而收集的100多万篇新闻文章的集合。这个例子的目的是说明预训练词嵌入在文本分类中的有效性。在本例中,我们使用精简版的120000篇新闻文章,它们平均分为四类:体育(Sports)、科学(Science)/技术(Technology)、世界(World)和商业(Business)。除了精简数据集之外,我们还将文章标题作为我们的观察重点,并创建多元分类任务来预测给定标题的类别。

和以前一样,我们通过删除标点符号、在标点符号周围添加空格(如逗号、撇号和句点)来预处理文本,并将文本转换为小写。此外,我们将数据集拆分为训练集、验证集和测试集,这是通过按类标签聚合数据点,然后将每个数据点分配给三个拆分集中的一个完成的。通过这种方式,保证了跨数据集的类分布是相同的。

如下例(5-11)所示,NewsDataset.__getitem__()方法遵循一个你很熟悉的基本公式:表示模型输入的字符串由数据集中的特定行检索,由Vectorizer进行向量化,并与表示新闻类别(类标签)的整数配对。

示例 5-11:NewsDataset.__getitem__()方法

  1. class NewsDataset(Dataset):
  2. @classmethod
  3. def load_dataset_and_make_vectorizer(cls, news_csv):
  4. """Load dataset and make a new vectorizer from scratch
  5. Args:
  6. surname_csv (str): location of the dataset
  7. Returns:
  8. an instance of SurnameDataset
  9. """
  10. news_df = pd.read_csv(news_csv)
  11. train_news_df = news_df[news_df.split=='train']
  12. return cls(news_df, NewsVectorizer.from_dataframe(train_news_df))
  13. def __getitem__(self, index):
  14. """the primary entry point method for PyTorch datasets
  15. Args:
  16. index (int): the index to the data point
  17. Returns:
  18. a dict holding the data point's features (x_data) and label (y_target)
  19. """
  20. row = self._target_df.iloc[index]
  21. title_vector = \
  22. self._vectorizer.vectorize(row.title, self._max_seq_length)
  23. category_index = \
  24. self._vectorizer.category_vocab.lookup_token(row.category)
  25. return {'x_data': title_vector,
  26. 'y_target': category_index}
5.3.2 Vocabulary,Vectorizer和DataLoader

在本例中,我们引入了SequenceVocabulary,它是标准Vocabulary类的子类,它绑定了用于序列数据的四个特殊token:UNK token,MASK token,BEGIN-SEQUENCE token和END-SEQUENCE token。我们会在第六章中详细介绍这些token,但简而言之,它们的用途有三:我们在第四章中看到的UNK token(unknown 的缩写)允许模型学习罕见单词的表示,以便它可以在测试时接受从未见过的单词。当我们有可变长度的序列时,MASK token充当Embedding层和损失计算的标记。最后,BEGIN-SEQUENCE和END-SEQUENCE给出了神经网络关于序列边界的提示。下图(5-3)展示了在更广泛的向量化管道中使用这些特殊标记的结果:

3a9eb3099efe9c7358b416e37003bbfc.png

文本到向量化minibatch的管道中的第二个部分是Vectorizer,它实例化并封装了SequenceVocabulary。在本例中,Vectorizer遵循我们在前面“Vectorizer”一节中演示的模式,即通过对特定频率进行计数和阈值化来限制词汇表中允许的词的总数。此操作的核心目的是改善模型的信号质量,并通过消除噪声低频词来限制内存模型的内存使用。

实例化之后,Vectorizer的vectorize()方法将新闻标题作为输入,并返回与数据集中最长标题一样长的向量,它有两个关键行为:第一,它在本地存储最大序列长度,通常,数据集会跟踪最大序列长度,并在推断时,测试序列的长度会被视为向量的长度,但由于我们有 CNN 模型,所以即使在推理时也要保持大小不变;第二,正如下例(5-11)中的代码片段所示,它输出一个由零填充的整数向量,它表示序列中的单词。此外,这个整数向量将BEGIN-SEQUENCE的整数添加到开头,并将END-SEQUENCE的整数添加到结尾。对分类器来说,这些特殊标记提示了序列边界,使其能够对边界附近的单词作出反应,而不是对靠近中心的单词作出反应。

示例 5-12:为 AG News数据集实现Vectorizer

  1. class NewsVectorizer(object):
  2. def vectorize(self, title, vector_length=-1):
  3. """
  4. Args:
  5. title (str): the string of words separated by a space
  6. vector_length (int): forces the length of index vector
  7. Returns:
  8. the vectorized title (numpy.array)
  9. """
  10. indices = [self.title_vocab.begin_seq_index]
  11. indices.extend(self.title_vocab.lookup_token(token)
  12. for token in title.split(" "))
  13. indices.append(self.title_vocab.end_seq_index)
  14. if vector_length < 0:
  15. vector_length = len(indices)
  16. out_vector = np.zeros(vector_length, dtype=np.int64)
  17. out_vector[:len(indices)] = indices
  18. out_vector[len(indices):] = self.title_vocab.mask_index
  19. return out_vector
  20. @classmethod
  21. def from_dataframe(cls, news_df, cutoff=25):
  22. """Instantiate the vectorizer from the dataset dataframe
  23. Args:
  24. news_df (pandas.DataFrame): the target dataset
  25. cutoff (int): frequency threshold for including in Vocabulary
  26. Returns:
  27. an instance of the NewsVectorizer
  28. """
  29. category_vocab = Vocabulary()
  30. for category in sorted(set(news_df.category)):
  31. category_vocab.add_token(category)
  32. word_counts = Counter()
  33. for title in news_df.title:
  34. for token in title.split(" "):
  35. if token not in string.punctuation:
  36. word_counts[token] += 1
  37. title_vocab = SequenceVocabulary()
  38. for word, word_count in word_counts.items():
  39. if word_count >= cutoff:
  40. title_vocab.add_token(word)
  41. return cls(title_vocab, category_vocab)
5.3.3 NewsClassifier模型

我们在本章前面介绍了如何从磁盘中加载预训练嵌入,并使用Spotify’s的annoy库中的近似最近邻数据结构有效地使用它们。在前面的示例中,我们比较向量以获得有趣的语言学见解。然而,预训练的单词向量具有更有效的用途:我们可以使用它们来初始化Embedding层的嵌入矩阵。

使用词嵌入(word embedding)作为初始嵌入矩阵的过程包括:首先从磁盘加载嵌入,然后为数据中实际存在的单词选择正确的嵌入子集,最后将嵌入层的权重矩阵设置为加载的子集。在下例(5-13)中演示了选择子集的前两步。通常出现的一个问题是:数据集中存在的单词并没有包含在预训练的GloVe嵌入中,处理该问题的一种常用方法是使用PyTorch库中的初始化方法,例如Xavier Uniform方法,如下例(5-13)所示(Glorot 和 Bengio,2010):

示例 5-13:基于词汇表选择词嵌入的子集

  1. def load_glove_from_file(glove_filepath):
  2. """Load the GloVe embeddings
  3. Args:
  4. glove_filepath (str): path to the glove embeddings file
  5. Returns:
  6. word_to_index (dict), embeddings (numpy.ndarray)
  7. """
  8. word_to_index = {}
  9. embeddings = []
  10. with open(glove_filepath, "r") as fp:
  11. for index, line in enumerate(fp):
  12. line = line.split(" ") # each line: word num1 num2 ...
  13. word_to_index[line[0]] = index # word = line[0]
  14. embedding_i = np.array([float(val) for val in line[1:]])
  15. embeddings.append(embedding_i)
  16. return word_to_index, np.stack(embeddings)
  17. def make_embedding_matrix(glove_filepath, words):
  18. """Create embedding matrix for a specific set of words.
  19. Args:
  20. glove_filepath (str): file path to the glove embeddings
  21. words (list): list of words in the dataset
  22. Returns:
  23. final_embeddings (numpy.ndarray): embedding matrix
  24. """
  25. word_to_idx, glove_embeddings = load_glove_from_file(glove_filepath)
  26. embedding_size = glove_embeddings.shape[1]
  27. final_embeddings = np.zeros((len(words), embedding_size))
  28. for i, word in enumerate(words):
  29. if word in word_to_idx:
  30. final_embeddings[i, :] = glove_embeddings[word_to_idx[word]]
  31. else:
  32. embedding_i = torch.ones(1, embedding_size)
  33. torch.nn.init.xavier_uniform_(embedding_i)
  34. final_embeddings[i, :] = embedding_i
  35. return final_embeddings

本例中的NewsClassifier是基于4-4节的ConvNet 分类器(使用 CNN 对字符的独热嵌入来对姓氏进行分类)而建立的。具体而言,我们使用Embedding层,它将输入token索引映射到向量表示。我们通过替换Embedding层的权重矩阵来使用预训练嵌入子集,如下例(5-14)所示。然后在forward()中使用嵌入以从索引映射到向量。除了嵌入层,一切都与第4-4节中的示例完全相同。

示例 5-14:实现NewsClassifier

  1. class NewsClassifier(nn.Module):
  2. def __init__(self, embedding_size, num_embeddings, num_channels,
  3. hidden_dim, num_classes, dropout_p,
  4. pretrained_embeddings=None, padding_idx=0):
  5. """
  6. Args:
  7. embedding_size (int): size of the embedding vectors
  8. num_embeddings (int): number of embedding vectors
  9. filter_width (int): width of the convolutional kernels
  10. num_channels (int): number of convolutional kernels per layer
  11. hidden_dim (int): the size of the hidden dimension
  12. num_classes (int): the number of classes in classification
  13. dropout_p (float): a dropout parameter
  14. pretrained_embeddings (numpy.array): previously trained word embeddings
  15. default is None. If provided,
  16. padding_idx (int): an index representing a null position
  17. """
  18. super(NewsClassifier, self).__init__()
  19. if pretrained_embeddings is None:
  20. self.emb = nn.Embedding(embedding_dim=embedding_size,
  21. num_embeddings=num_embeddings,
  22. padding_idx=padding_idx)
  23. else:
  24. pretrained_embeddings = torch.from_numpy(pretrained_embeddings).float()
  25. self.emb = nn.Embedding(embedding_dim=embedding_size,
  26. num_embeddings=num_embeddings,
  27. padding_idx=padding_idx,
  28. _weight=pretrained_embeddings)
  29. self.convnet = nn.Sequential(
  30. nn.Conv1d(in_channels=embedding_size,
  31. out_channels=num_channels, kernel_size=3),
  32. nn.ELU(),
  33. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  34. kernel_size=3, stride=2),
  35. nn.ELU(),
  36. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  37. kernel_size=3, stride=2),
  38. nn.ELU(),
  39. nn.Conv1d(in_channels=num_channels, out_channels=num_channels,
  40. kernel_size=3),
  41. nn.ELU()
  42. )
  43. self._dropout_p = dropout_p
  44. self.fc1 = nn.Linear(num_channels, hidden_dim)
  45. self.fc2 = nn.Linear(hidden_dim, num_classes)
  46. def forward(self, x_in, apply_softmax=False):
  47. """The forward pass of the classifier
  48. Args:
  49. x_in (torch.Tensor): an input data tensor.
  50. x_in.shape should be (batch, dataset._max_seq_length)
  51. apply_softmax (bool): a flag for the softmax activation
  52. should be false if used with the Cross Entropy losses
  53. Returns:
  54. the resulting tensor. tensor.shape should be (batch, num_classes)
  55. """
  56. # embed and permute so features are channels
  57. x_embedded = self.emb(x_in).permute(0, 2, 1)
  58. features = self.convnet(x_embedded)
  59. # average and remove the extra dimension
  60. remaining_size = features.size(dim=2)
  61. features = F.avg_pool1d(features, remaining_size).squeeze(dim=2)
  62. features = F.dropout(features, p=self._dropout_p)
  63. # final linear layer to produce classification outputs
  64. intermediate_vector = F.relu(F.dropout(self.fc1(features),
  65. p=self._dropout_p))
  66. prediction_vector = self.fc2(intermediate_vector)
  67. if apply_softmax:
  68. prediction_vector = F.softmax(prediction_vector, dim=1)
  69. return prediction_vector
5.3.4 训练例程

训练例程包括以下步骤:实例化数据集、实例化模型、实例化损失函数、实例化优化器、迭代数据集的训练部分并更新模型参数、迭代数据集的验证部分并测量性能、然后重复数据集迭代一定次数。此时你应该已经非常熟悉这一系列步骤了。下例(5-15)中展示了此示例的超参数和其他训练参数:

示例 5-15:使用与训练嵌入的 CNN NewsClassifier的参数

  1. args = Namespace(
  2. # Data and path hyper parameters
  3. news_csv="data/ag_news/news_with_splits.csv",
  4. vectorizer_file="vectorizer.json",
  5. model_state_file="model.pth",
  6. save_dir="model_storage/ch5/document_classification",
  7. # Model hyper parameters
  8. glove_filepath='data/glove/glove.6B.100d.txt',
  9. use_glove=False,
  10. embedding_size=100,
  11. hidden_dim=100,
  12. num_channels=100,
  13. # Training hyper parameter
  14. seed=1337,
  15. learning_rate=0.001,
  16. dropout_p=0.1,
  17. batch_size=128,
  18. num_epochs=100,
  19. early_stopping_criteria=5,
  20. # ... runtime options not shown for space
  21. )
5.3.5 模型评估和分类

在本例中,任务是根据新闻标题分类。如前所述,有两种方法可以理解模型执行任务的效果:使用测试集的定量评估,以及亲自检查分类结果的定性评估。

5.3.5.1 在测试集上评估

虽然这是你第一次分类新闻标题,但是定量评估例程和前面的示例是一样的:设置模型为eval模式以关掉dropout和反向传播(使用classifier.eval()),然后和遍历训练集和验证集一样遍历测试集。典型情况是,你应该尝试不同选项直到符合预期,然后执行模型评估,我们会把这个留作练习。在这个测试集中你能得到的最终准确度是多少?请记住,在整个实验过程中,测试集只能用一次。

5.3.5.2 预测新的新闻头条的类别

训练分类器的目标是将其部署到生产环境中,以便对不知道的新闻标题执行推理或预测。要预测数据集中尚未处理的新闻标题的类别,有几个步骤:首先是对文本进行预处理,其方式类似于对训练中的数据进行预处理。对于推理,我们对输入使用与训练中相同的预处理函数。这个预处理后的字符串使用训练期间使用的Vectorizer向量化,并转换为 PyTorch 张量。接下来,对它应用分类器。计算预测向量的最大值以查找类别名称。下例(5-16)给出了代码:

示例 5-16:使用训练模型作预测

  1. def predict_category(title, classifier, vectorizer, max_length):
  2. """Predict a News category for a new title
  3. Args:
  4. title (str): a raw title string
  5. classifier (NewsClassifier): an instance of the trained classifier
  6. vectorizer (NewsVectorizer): the corresponding vectorizer
  7. max_length (int): the max sequence length
  8. Note: CNNs are sensitive to the input data tensor size.
  9. This ensures to keep it the same size as the training data
  10. """
  11. title = preprocess_text(title)
  12. vectorized_title = \
  13. torch.tensor(vectorizer.vectorize(title, vector_length=max_length))
  14. result = classifier(vectorized_title.unsqueeze(0), apply_softmax=True)
  15. probability_values, indices = result.max(dim=1)
  16. predicted_category = vectorizer.category_vocab.lookup_index(indices.item())
  17. return {'category': predicted_category,
  18. 'probability': probability_values.item()}


5.4 总结

在本章中,我们研究了词嵌入,这是一种将离散项(如单词)表示为空间中的固定维向量的方法,使得向量之间的距离编码了各种语言属性。请记住,本章介绍的技术适用于任何离散单元,如句子、段落、文档、数据库记录等, 这使得嵌入技术对于深度学习(特别是在 NLP 中)不可或缺。我们展示了如何以黑盒方式使用预训练嵌入。我们简要讨论了直接从数据中学习这些嵌入的几种方法,包括连续词袋(Continuous Bag-of-Words,CBOW)方法。我们接着展示了如何在语言建模任务的上下文中训练 CBOW 模型。最后,我们学习了一个使用预训练嵌入的示例,并探索了在像文档分类的任务中的微调嵌入。

不幸的是,由于篇幅问题,本章略过了许多重要的话题,比如词嵌入除偏(debiasing word embeddings)、建模上下文(modeling context)和一词多义(polysemy)。语言数据是现实世界的反映,社会偏见可以通过有偏见的训练语料库编码成模型。在一项研究中,最接近代词“she”的词是家庭主妇、护士、接待员、图书管理员、理发师等,然而最接近“he”的词则是外科医生、保护者、哲学家、建筑师、金融家等。在这种有偏见的嵌入上训练的模型会继续做出可能产生不公平结果的决策。词嵌入除偏仍然是一个新兴领域,我们建议你阅读提到了这一点的Bolukbasi等人(2016 年)和最近的论文。此外,我们使用的词嵌入不考虑上下文。例如,根据上下文,单词play可能有两个不同的含义,但这里讨论的所有嵌入(embedding)方法都会破坏这两个含义。最近的研究如 Peters(2018)探索了以上下文为条件提供嵌入的方法。

dfa2f50f214be55d385f8ab6573ea382.png

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/790284
推荐阅读
相关标签
  

闽ICP备14008679号