You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

文本分类.rst 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. 文本分类
  2. =============================
  3. 文本分类(Text classification)任务是将一句话或一段话划分到某个具体的类别。比如垃圾邮件识别,文本情绪分类等。这篇教程可以带你从零开始了解 fastNLP 的使用
  4. .. note::
  5. 本教程推荐使用 GPU 进行实验
  6. .. code-block:: text
  7. 1, 商务大床房,房间很大,床有2M宽,整体感觉经济实惠不错!
  8. 其中开头的1是只这条评论的标签,表示是正面的情绪。我们将使用到的数据可以通过 `此链接 <http://212.129.155.247/dataset/chn_senti_corp.zip>`_
  9. 下载并解压,当然也可以通过fastNLP自动下载该数据。
  10. 数据中的内容如下图所示。接下来,我们将用fastNLP在这个数据上训练一个分类网络。
  11. .. figure:: ./cn_cls_example.png
  12. :alt: jupyter
  13. 步骤
  14. ----
  15. 一共有以下的几个步骤:
  16. 1. `读取数据 <#id4>`_
  17. 2. `预处理数据 <#id5>`_
  18. 3. `选择预训练词向量 <#id6>`_
  19. 4. `创建模型 <#id7>`_
  20. 5. `训练模型 <#id8>`_
  21. (1) 读取数据
  22. ~~~~~~~~~~~~~~~~~~~~
  23. fastNLP提供多种数据的自动下载与自动加载功能,对于这里我们要用到的数据,我们可以用 :class:`~fastNLP.io.Loader` 自动下载并加载该数据。
  24. 更多有关Loader的使用可以参考 :mod:`~fastNLP.io.loader`
  25. .. code-block:: python
  26. from fastNLP.io import ChnSentiCorpLoader
  27. loader = ChnSentiCorpLoader() # 初始化一个中文情感分类的loader
  28. data_dir = loader.download() # 这一行代码将自动下载数据到默认的缓存地址, 并将该地址返回
  29. data_bundle = loader.load(data_dir) # 这一行代码将从{data_dir}处读取数据至DataBundle
  30. DataBundle的相关介绍,可以参考 :class:`~fastNLP.io.DataBundle` 。我们可以打印该data\_bundle的基本信息。
  31. .. code-block:: python
  32. print(data_bundle)
  33. .. code-block:: text
  34. In total 3 datasets:
  35. dev has 1200 instances.
  36. train has 9600 instances.
  37. test has 1200 instances.
  38. In total 0 vocabs:
  39. 可以看出,该data\_bundle中一个含有三个 :class:`~fastNLP.DataSet` 。通过下面的代码,我们可以查看DataSet的基本情况
  40. .. code-block:: python
  41. print(data_bundle.get_dataset('train')[:2]) # 查看Train集前两个sample
  42. .. code-block:: text
  43. +-----------------------------+--------+
  44. | raw_chars | target |
  45. +-----------------------------+--------+
  46. | 选择珠江花园的原因就是方... | 1 |
  47. | 15.4寸笔记本的键盘确实爽... | 1 |
  48. +-----------------------------+--------+
  49. (2) 预处理数据
  50. ~~~~~~~~~~~~~~~~~~~~
  51. 在NLP任务中,预处理一般包括:
  52. (a) 将一整句话切分成汉字或者词;
  53. (b) 将文本转换为index
  54. fastNLP中也提供了多种数据集的处理类,这里我们直接使用fastNLP的ChnSentiCorpPipe。更多关于Pipe的说明可以参考 :mod:`~fastNLP.io.pipe` 。
  55. .. code-block:: python
  56. from fastNLP.io import ChnSentiCorpPipe
  57. pipe = ChnSentiCorpPipe()
  58. data_bundle = pipe.process(data_bundle) # 所有的Pipe都实现了process()方法,且输入输出都为DataBundle类型
  59. print(data_bundle) # 打印data_bundle,查看其变化
  60. .. code-block:: text
  61. In total 3 datasets:
  62. dev has 1200 instances.
  63. train has 9600 instances.
  64. test has 1200 instances.
  65. In total 2 vocabs:
  66. chars has 4409 entries.
  67. target has 2 entries.
  68. 可以看到除了之前已经包含的3个 :class:`~fastNLP.DataSet` ,还新增了两个 :class:`~fastNLP.Vocabulary` 。我们可以打印DataSet中的内容
  69. .. code-block:: python
  70. print(data_bundle.get_dataset('train')[:2])
  71. .. code-block:: text
  72. +-----------------+--------+-----------------+---------+
  73. | raw_chars | target | chars | seq_len |
  74. +-----------------+--------+-----------------+---------+
  75. | 选择珠江花园... | 0 | [338, 464, 1... | 106 |
  76. | 15.4寸笔记本... | 0 | [50, 133, 20... | 56 |
  77. +-----------------+--------+-----------------+---------+
  78. 新增了一列为数字列表的chars,以及变为数字的target列。可以看出这两列的名称和刚好与data\_bundle中两个Vocabulary的名称是一致的,我们可以打印一下Vocabulary看一下里面的内容。
  79. .. code-block:: python
  80. char_vocab = data_bundle.get_vocab('chars')
  81. print(char_vocab)
  82. .. code-block:: text
  83. Vocabulary(['选', '择', '珠', '江', '花']...)
  84. Vocabulary是一个记录着词语与index之间映射关系的类,比如
  85. .. code-block:: python
  86. index = char_vocab.to_index('选')
  87. print("'选'的index是{}".format(index)) # 这个值与上面打印出来的第一个instance的chars的第一个index是一致的
  88. print("index:{}对应的汉字是{}".format(index, char_vocab.to_word(index)))
  89. .. code-block:: text
  90. '选'的index是338
  91. index:338对应的汉字是选
  92. (3) 选择预训练词向量
  93. ~~~~~~~~~~~~~~~~~~~~
  94. 由于Word2vec, Glove, Elmo,
  95. Bert等预训练模型可以增强模型的性能,所以在训练具体任务前,选择合适的预训练词向量非常重要。
  96. 在fastNLP中我们提供了多种Embedding使得加载这些预训练模型的过程变得更加便捷。
  97. 这里我们先给出一个使用word2vec的中文汉字预训练的示例,之后再给出一个使用Bert的文本分类。
  98. 这里使用的预训练词向量为'cn-fastnlp-100d',fastNLP将自动下载该embedding至本地缓存,
  99. fastNLP支持使用名字指定的Embedding以及相关说明可以参见 :mod:`fastNLP.embeddings`
  100. .. code-block:: python
  101. from fastNLP.embeddings import StaticEmbedding
  102. word2vec_embed = StaticEmbedding(char_vocab, model_dir_or_name='cn-char-fastnlp-100d')
  103. .. code-block:: text
  104. Found 4321 out of 4409 compound in the pre-training embedding.
  105. (4) 创建模型
  106. ~~~~~~~~~~~~
  107. .. code-block:: python
  108. from torch import nn
  109. from fastNLP.modules import LSTM
  110. import torch
  111. # 定义模型
  112. class BiLSTMMaxPoolCls(nn.Module):
  113. def __init__(self, embed, num_classes, hidden_size=400, num_layers=1, dropout=0.3):
  114. super().__init__()
  115. self.embed = embed
  116. self.lstm = LSTM(self.embed.embedding_dim, hidden_size=hidden_size//2, num_layers=num_layers,
  117. batch_first=True, bidirectional=True)
  118. self.dropout_layer = nn.Dropout(dropout)
  119. self.fc = nn.Linear(hidden_size, num_classes)
  120. def forward(self, chars, seq_len): # 这里的名称必须和DataSet中相应的field对应,比如之前我们DataSet中有chars,这里就必须为chars
  121. # chars:[batch_size, max_len]
  122. # seq_len: [batch_size, ]
  123. chars = self.embed(chars)
  124. outputs, _ = self.lstm(chars, seq_len)
  125. outputs = self.dropout_layer(outputs)
  126. outputs, _ = torch.max(outputs, dim=1)
  127. outputs = self.fc(outputs)
  128. return {'pred':outputs} # [batch_size,], 返回值必须是dict类型,且预测值的key建议设为pred
  129. # 初始化模型
  130. model = BiLSTMMaxPoolCls(word2vec_embed, len(data_bundle.get_vocab('target')))
  131. (5) 训练模型
  132. ~~~~~~~~~~~~
  133. fastNLP提供了Trainer对象来组织训练过程,包括完成loss计算(所以在初始化Trainer的时候需要指定loss类型),梯度更新(所以在初始化Trainer的时候需要提供优化器optimizer)以及在验证集上的性能验证(所以在初始化时需要提供一个Metric)
  134. .. code-block:: python
  135. from fastNLP import Trainer
  136. from fastNLP import CrossEntropyLoss
  137. from torch.optim import Adam
  138. from fastNLP import AccuracyMetric
  139. loss = CrossEntropyLoss()
  140. optimizer = Adam(model.parameters(), lr=0.001)
  141. metric = AccuracyMetric()
  142. device = 0 if torch.cuda.is_available() else 'cpu' # 如果有gpu的话在gpu上运行,训练速度会更快
  143. trainer = Trainer(train_data=data_bundle.get_dataset('train'), model=model, loss=loss,
  144. optimizer=optimizer, batch_size=32, dev_data=data_bundle.get_dataset('dev'),
  145. metrics=metric, device=device)
  146. trainer.train() # 开始训练,训练完成之后默认会加载在dev上表现最好的模型
  147. # 在测试集上测试一下模型的性能
  148. from fastNLP import Tester
  149. print("Performance on test is:")
  150. tester = Tester(data=data_bundle.get_dataset('test'), model=model, metrics=metric, batch_size=64, device=device)
  151. tester.test()
  152. .. code-block:: text
  153. input fields after batch(if batch size is 2):
  154. target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  155. chars: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 106])
  156. seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  157. target fields after batch(if batch size is 2):
  158. target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  159. seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  160. Evaluate data in 0.01 seconds!
  161. training epochs started 2019-09-03-23-57-10
  162. Evaluate data in 0.43 seconds!
  163. Evaluation on dev at Epoch 1/10. Step:300/3000:
  164. AccuracyMetric: acc=0.81
  165. Evaluate data in 0.44 seconds!
  166. Evaluation on dev at Epoch 2/10. Step:600/3000:
  167. AccuracyMetric: acc=0.8675
  168. Evaluate data in 0.44 seconds!
  169. Evaluation on dev at Epoch 3/10. Step:900/3000:
  170. AccuracyMetric: acc=0.878333
  171. ....
  172. Evaluate data in 0.48 seconds!
  173. Evaluation on dev at Epoch 9/10. Step:2700/3000:
  174. AccuracyMetric: acc=0.8875
  175. Evaluate data in 0.43 seconds!
  176. Evaluation on dev at Epoch 10/10. Step:3000/3000:
  177. AccuracyMetric: acc=0.895833
  178. In Epoch:7/Step:2100, got best dev performance:
  179. AccuracyMetric: acc=0.8975
  180. Reloaded the best model.
  181. Evaluate data in 0.34 seconds!
  182. [tester]
  183. AccuracyMetric: acc=0.8975
  184. {'AccuracyMetric': {'acc': 0.8975}}
  185. 使用Bert进行文本分类
  186. ~~~~~~~~~~~~~~~~~~~~
  187. .. code-block:: python
  188. # 只需要切换一下Embedding即可
  189. from fastNLP.embeddings import BertEmbedding
  190. # 这里为了演示一下效果,所以默认Bert不更新权重
  191. bert_embed = BertEmbedding(char_vocab, model_dir_or_name='cn', auto_truncate=True, requires_grad=False)
  192. model = BiLSTMMaxPoolCls(bert_embed, len(data_bundle.get_vocab('target')))
  193. import torch
  194. from fastNLP import Trainer
  195. from fastNLP import CrossEntropyLoss
  196. from torch.optim import Adam
  197. from fastNLP import AccuracyMetric
  198. loss = CrossEntropyLoss()
  199. optimizer = Adam(model.parameters(), lr=2e-5)
  200. metric = AccuracyMetric()
  201. device = 0 if torch.cuda.is_available() else 'cpu' # 如果有gpu的话在gpu上运行,训练速度会更快
  202. trainer = Trainer(train_data=data_bundle.get_dataset('train'), model=model, loss=loss,
  203. optimizer=optimizer, batch_size=16, dev_data=data_bundle.get_dataset('test'),
  204. metrics=metric, device=device, n_epochs=3)
  205. trainer.train() # 开始训练,训练完成之后默认会加载在dev上表现最好的模型
  206. # 在测试集上测试一下模型的性能
  207. from fastNLP import Tester
  208. print("Performance on test is:")
  209. tester = Tester(data=data_bundle.get_dataset('test'), model=model, metrics=metric, batch_size=64, device=device)
  210. tester.test()
  211. .. code-block:: text
  212. loading vocabulary file ~/.fastNLP/embedding/bert-chinese-wwm/vocab.txt
  213. Load pre-trained BERT parameters from file ~/.fastNLP/embedding/bert-chinese-wwm/chinese_wwm_pytorch.bin.
  214. Start to generating word pieces for word.
  215. Found(Or segment into word pieces) 4286 words out of 4409.
  216. input fields after batch(if batch size is 2):
  217. target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  218. chars: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 106])
  219. seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  220. target fields after batch(if batch size is 2):
  221. target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  222. seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  223. Evaluate data in 0.05 seconds!
  224. training epochs started 2019-09-04-00-02-37
  225. Evaluate data in 15.89 seconds!
  226. Evaluation on dev at Epoch 1/3. Step:1200/3600:
  227. AccuracyMetric: acc=0.9
  228. Evaluate data in 15.92 seconds!
  229. Evaluation on dev at Epoch 2/3. Step:2400/3600:
  230. AccuracyMetric: acc=0.904167
  231. Evaluate data in 15.91 seconds!
  232. Evaluation on dev at Epoch 3/3. Step:3600/3600:
  233. AccuracyMetric: acc=0.918333
  234. In Epoch:3/Step:3600, got best dev performance:
  235. AccuracyMetric: acc=0.918333
  236. Reloaded the best model.
  237. Performance on test is:
  238. Evaluate data in 29.24 seconds!
  239. [tester]
  240. AccuracyMetric: acc=0.919167
  241. {'AccuracyMetric': {'acc': 0.919167}}
  242. ----------------------------------
  243. 代码下载
  244. ----------------------------------
  245. .. raw:: html
  246. <a href="../_static/notebooks/%E6%96%87%E6%9C%AC%E5%88%86%E7%B1%BB.ipynb" download="文本分类.ipynb">点击下载 IPython Notebook 文件 </a><hr>