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.

tutorial_5_loss_optimizer.rst 12 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. ==============================================================================
  2. 使用Trainer和Tester快速训练和测试
  3. ==============================================================================
  4. 我们使用前面介绍过的 :doc:`/tutorials/文本分类` 任务来进行详细的介绍。这里我们把数据集换成了SST2,使用 :class:`~fastNLP.Trainer` 和 :class:`~fastNLP.Tester` 来进行快速训练和测试。
  5. .. note::
  6. 本教程中的代码没有使用 GPU 。读者可以自行修改代码,扩大数据量并使用 GPU 进行训练。
  7. 数据读入和处理
  8. -----------------
  9. 数据读入
  10. 我们可以使用 fastNLP :mod:`fastNLP.io` 模块中的 :class:`~fastNLP.io.SST2Pipe` 类,轻松地读取以及预处理SST2数据集。:class:`~fastNLP.io.SST2Pipe` 对象的
  11. :meth:`~fastNLP.io.SST2Pipe.process_from_file` 方法能够对读入的SST2数据集进行数据的预处理,方法的参数为paths, 指要处理的文件所在目录,如果paths为None,则会自动下载数据集,函数默认paths值为None。
  12. 此函数返回一个 :class:`~fastNLP.io.DataBundle`,包含SST2数据集的训练集、测试集、验证集以及source端和target端的字典。其训练、测试、验证数据集含有四个 :mod:`~fastNLP.core.field` :
  13. * raw_words: 原source句子
  14. * target: 标签值
  15. * words: index之后的raw_words
  16. * seq_len: 句子长度
  17. 读入数据代码如下:
  18. .. code-block:: python
  19. from fastNLP.io import SST2Pipe
  20. pipe = SST2Pipe()
  21. databundle = pipe.process_from_file()
  22. vocab = databundle.get_vocab('words')
  23. print(databundle)
  24. print(databundle.get_dataset('train')[0])
  25. print(databundle.get_vocab('words'))
  26. 输出数据如下::
  27. In total 3 datasets:
  28. test has 1821 instances.
  29. train has 67349 instances.
  30. dev has 872 instances.
  31. In total 2 vocabs:
  32. words has 16293 entries.
  33. target has 2 entries.
  34. +-------------------------------------------+--------+--------------------------------------+---------+
  35. | raw_words | target | words | seq_len |
  36. +-------------------------------------------+--------+--------------------------------------+---------+
  37. | hide new secretions from the parental ... | 1 | [4111, 98, 12010, 38, 2, 6844, 9042] | 7 |
  38. +-------------------------------------------+--------+--------------------------------------+---------+
  39. Vocabulary(['hide', 'new', 'secretions', 'from', 'the']...)
  40. 除了可以对数据进行读入的Pipe类,fastNLP还提供了读入和下载数据的Loader类,不同数据集的Pipe和Loader及其用法详见 :doc:`/tutorials/tutorial_4_load_dataset` 。
  41. 数据集分割
  42. 由于SST2数据集的测试集并不带有标签数值,故我们分割出一部分训练集作为测试集。下面这段代码展示了 :meth:`~fastNLP.DataSet.split` 的使用方法,
  43. 为了能让读者快速运行完整个教程,我们只取了训练集的前5000个数据。
  44. .. code-block:: python
  45. train_data = databundle.get_dataset('train')[:5000]
  46. train_data, test_data = train_data.split(0.015)
  47. dev_data = databundle.get_dataset('dev')
  48. print(len(train_data),len(dev_data),len(test_data))
  49. 输出结果为::
  50. 4925 872 75
  51. 数据集 :meth:`~fastNLP.DataSet.set_input` 和 :meth:`~fastNLP.DataSet.set_target` 函数
  52. :class:`~fastNLP.io.SST2Pipe` 类的 :meth:`~fastNLP.io.SST2Pipe.process_from_file` 方法在预处理过程中还将训练、测试、验证
  53. 集的 `words` 、`seq_len` :mod:`~fastNLP.core.field` 设定为input,同时将 `target` :mod:`~fastNLP.core.field` 设定
  54. 为target。我们可以通过 :class:`~fastNLP.core.Dataset` 类的 :meth:`~fastNLP.core.Dataset.print_field_meta` 方法查看各个 :mod:`~fastNLP.core.field` 的设定情况,代码如下:
  55. .. code-block:: python
  56. train_data.print_field_meta()
  57. 输出结果为::
  58. +-------------+-----------+--------+-------+---------+
  59. | field_names | raw_words | target | words | seq_len |
  60. +-------------+-----------+--------+-------+---------+
  61. | is_input | False | False | True | True |
  62. | is_target | False | True | False | False |
  63. | ignore_type | | False | False | False |
  64. | pad_value | | 0 | 0 | 0 |
  65. +-------------+-----------+--------+-------+---------+
  66. 其中is_input和is_target分别表示是否为input和target。ignore_type为true时指使用 :class:`~fastNLP.DataSetIter` 取出batch数
  67. 据时fastNLP不会进行自动padding,pad_value指对应 :mod:`~fastNLP.core.field` padding所用的值,这两者只有
  68. 当 :mod:`~fastNLP.core.field` 设定为input或者target的时候才有存在的意义。
  69. is_input为true的 :mod:`~fastNLP.core.field` 在 :class:`~fastNLP.DataSetIter` 迭代取出的batch_x 中,而is_target为true
  70. 的 :mod:`~fastNLP.core.field` 在 :class:`~fastNLP.DataSetIter` 迭代取出的 batch_y 中。
  71. 具体分析见 :doc:`使用DataSetIter实现自定义训练过程 </tutorials/tutorial_6_datasetiter>` 。
  72. 使用内置模型训练
  73. ---------------------
  74. 模型定义和初始化
  75. 我们可以导入 fastNLP 内置的文本分类模型 :class:`~fastNLP.models.CNNText` 来对模型进行定义,代码如下:
  76. .. code-block:: python
  77. from fastNLP.models import CNNText
  78. #词嵌入的维度
  79. EMBED_DIM = 100
  80. #使用CNNText的时候第一个参数输入一个tuple,作为模型定义embedding的参数
  81. #还可以传入 kernel_nums, kernel_sizes, padding, dropout的自定义值
  82. model_cnn = CNNText((len(vocab),EMBED_DIM), num_classes=2, dropout=0.1)
  83. 使用fastNLP快速搭建自己的模型详见 :doc:`/tutorials/tutorial_8_modules_models` 。
  84. 评价指标
  85. 训练模型需要提供一个评价指标。这里使用准确率做为评价指标。
  86. * ``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。
  87. * ``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。
  88. 这里我们用 :class:`~fastNLP.Const` 来辅助命名,如果你自己编写模型中 forward 方法的返回值或
  89. 数据集中 :mod:`~fastNLP.core.field` 的名字与本例不同, 你可以把 ``pred`` 参数和 ``target`` 参数设定符合自己代码的值。代码如下:
  90. .. code-block:: python
  91. from fastNLP import AccuracyMetric
  92. from fastNLP import Const
  93. # metrics=AccuracyMetric() 在本例中与下面这行代码等价
  94. metrics=AccuracyMetric(pred=Const.OUTPUT, target=Const.TARGET)
  95. 损失函数
  96. 训练模型需要提供一个损失函数
  97. ,fastNLP中提供了直接可以导入使用的四种loss,分别为:
  98. * :class:`~fastNLP.CrossEntropyLoss`:包装了torch.nn.functional.cross_entropy()函数,返回交叉熵损失(可以运用于多分类场景)
  99. * :class:`~fastNLP.BCELoss`:包装了torch.nn.functional.binary_cross_entropy()函数,返回二分类的交叉熵
  100. * :class:`~fastNLP.L1Loss`:包装了torch.nn.functional.l1_loss()函数,返回L1 损失
  101. * :class:`~fastNLP.NLLLoss`:包装了torch.nn.functional.nll_loss()函数,返回负对数似然损失
  102. 下面提供了一个在分类问题中常用的交叉熵损失。注意它的 **初始化参数** 。
  103. * ``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。
  104. * ``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。
  105. 这里我们用 :class:`~fastNLP.Const` 来辅助命名,如果你自己编写模型中 forward 方法的返回值或
  106. 数据集中 :mod:`~fastNLP.core.field` 的名字与本例不同, 你可以把 ``pred`` 参数和 ``target`` 参数设定符合自己代码的值。
  107. .. code-block:: python
  108. from fastNLP import CrossEntropyLoss
  109. # loss = CrossEntropyLoss() 在本例中与下面这行代码等价
  110. loss = CrossEntropyLoss(pred=Const.OUTPUT, target=Const.TARGET)
  111. 除了使用fastNLP已经包装好的了损失函数,也可以通过fastNLP中的LossFunc类来构建自己的损失函数,方法如下:
  112. .. code-block:: python
  113. # 这表示构建了一个损失函数类,由func计算损失函数,其中将从模型返回值或者DataSet的target=True的field
  114. # 当中找到一个参数名为`pred`的参数传入func一个参数名为`input`的参数;找到一个参数名为`label`的参数
  115. # 传入func作为一个名为`target`的参数
  116. #下面自己构建了一个交叉熵函数,和之后直接使用fastNLP中的交叉熵函数是一个效果
  117. import torch
  118. from fastNLP import LossFunc
  119. func = torch.nn.functional.cross_entropy
  120. loss_func = LossFunc(func, input=Const.OUTPUT, target=Const.TARGET)
  121. 优化器
  122. 定义模型运行的时候使用的优化器,可以直接使用torch.optim.Optimizer中的优化器,并在实例化 :class:`~fastNLP.Trainer` 类的时候传入优化器实参
  123. .. code-block:: python
  124. import torch.optim as optim
  125. #使用 torch.optim 定义优化器
  126. optimizer=optim.RMSprop(model_cnn.parameters(), lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False)
  127. 快速训练
  128. 现在我们对上面定义的模型使用 :class:`~fastNLP.Trainer` 进行训练。
  129. 除了使用 :class:`~fastNLP.Trainer`进行训练,我们也可以通过使用 :class:`~fastNLP.DataSetIter` 来编写自己的训练过程,具体见 :doc:`/tutorials/tutorial_6_datasetiter`
  130. .. code-block:: python
  131. from fastNLP import Trainer
  132. #训练的轮数和batch size
  133. N_EPOCHS = 10
  134. BATCH_SIZE = 16
  135. #如果在定义trainer的时候没有传入optimizer参数,模型默认的优化器为torch.optim.Adam且learning rate为lr=4e-3
  136. #这里只使用了loss作为损失函数输入,感兴趣可以尝试其他损失函数(如之前自定义的loss_func)作为输入
  137. trainer = Trainer(model=model_cnn, train_data=train_data, dev_data=dev_data, loss=loss, metrics=metrics,
  138. optimizer=optimizer,n_epochs=N_EPOCHS, batch_size=BATCH_SIZE)
  139. trainer.train()
  140. 训练过程的输出如下::
  141. input fields after batch(if batch size is 2):
  142. words: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 13])
  143. seq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  144. target fields after batch(if batch size is 2):
  145. target: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2])
  146. training epochs started 2020-02-26-16-45-40
  147. Evaluate data in 0.5 seconds!
  148. Evaluation on dev at Epoch 1/10. Step:308/3080:
  149. AccuracyMetric: acc=0.677752
  150. ......
  151. Evaluate data in 0.44 seconds!
  152. Evaluation on dev at Epoch 10/10. Step:3080/3080:
  153. AccuracyMetric: acc=0.725917
  154. In Epoch:5/Step:1540, got best dev performance:
  155. AccuracyMetric: acc=0.740826
  156. Reloaded the best model.
  157. 快速测试
  158. 与 :class:`~fastNLP.Trainer` 对应,fastNLP 也提供了 :class:`~fastNLP.Tester` 用于快速测试,用法如下
  159. .. code-block:: python
  160. from fastNLP import Tester
  161. tester = Tester(test_data, model_cnn, metrics=AccuracyMetric())
  162. tester.test()
  163. 训练过程输出如下::
  164. Evaluate data in 0.43 seconds!
  165. [tester]
  166. AccuracyMetric: acc=0.773333
  167. ----------------------------------
  168. 代码下载
  169. ----------------------------------
  170. `点击下载 IPython Notebook 文件 <https://sourcegraph.com/github.com/fastnlp/fastNLP@master/-/raw/tutorials/tutorial_5_loss_optimizer.ipynb>`_)