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_4_loss_optimizer.rst 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. ==============================================================================
  2. Loss 和 optimizer 教程 ———— 以文本分类为例
  3. ==============================================================================
  4. 我们使用和 :doc:`/user/quickstart` 中一样的任务来进行详细的介绍。给出一段评价性文字,预测其情感倾向是积极(label=1)、消极(label=0)还是中性(label=2),使用 :class:`~fastNLP.Trainer` 和 :class:`~fastNLP.Tester` 来进行快速训练和测试,损失函数之前的内容与 :doc:`/tutorials/tutorial_5_datasetiter` 中的完全一样,如已经阅读过可以跳过。
  5. --------------
  6. 数据处理
  7. --------------
  8. 数据读入
  9. 我们可以使用 fastNLP :mod:`fastNLP.io` 模块中的 :class:`~fastNLP.io.SSTLoader` 类,轻松地读取SST数据集(数据来源:https://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip)。
  10. 这里的 dataset 是 fastNLP 中 :class:`~fastNLP.DataSet` 类的对象。
  11. .. code-block:: python
  12. from fastNLP.io import SSTLoader
  13. loader = SSTLoader()
  14. #这里的all.txt是下载好数据后train.txt、dev.txt、test.txt的组合
  15. dataset = loader.load("./trainDevTestTrees_PTB/trees/all.txt")
  16. print(dataset[0])
  17. 输出数据如下::
  18. {'words': ['It', "'s", 'a', 'lovely', 'film', 'with', 'lovely', 'performances', 'by', 'Buy', 'and', 'Accorsi', '.'] type=list,
  19. 'target': positive type=str}
  20. 除了读取数据外,fastNLP 还提供了读取其它文件类型的 Loader 类、读取 Embedding的 Loader 等。详见 :doc:`/fastNLP.io` 。
  21. 数据处理
  22. 我们使用 :class:`~fastNLP.DataSet` 类的 :meth:`~fastNLP.DataSet.apply` 方法将 ``target`` :mod:`~fastNLP.core.field` 转化为整数。
  23. .. code-block:: python
  24. def label_to_int(x):
  25. if x['target']=="positive":
  26. return 1
  27. elif x['target']=="negative":
  28. return 0
  29. else:
  30. return 2
  31. # 将label转为整数
  32. dataset.apply(lambda x: label_to_int(x), new_field_name='target')
  33. ``words`` 和 ``target`` 已经足够用于 :class:`~fastNLP.models.CNNText` 的训练了,但我们从其文档
  34. :class:`~fastNLP.models.CNNText` 中看到,在 :meth:`~fastNLP.models.CNNText.forward` 的时候,还可以传入可选参数 ``seq_len`` 。
  35. 所以,我们再使用 :meth:`~fastNLP.DataSet.apply_field` 方法增加一个名为 ``seq_len`` 的 :mod:`~fastNLP.core.field` 。
  36. .. code-block:: python
  37. # 增加长度信息
  38. dataset.apply_field(lambda x: len(x), field_name='words', new_field_name='seq_len')
  39. 观察可知: :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 类似,
  40. 但所传入的 `lambda` 函数是针对一个 :class:`~fastNLP.Instance` 中的一个 :mod:`~fastNLP.core.field` 的;
  41. 而 :meth:`~fastNLP.DataSet.apply` 所传入的 `lambda` 函数是针对整个 :class:`~fastNLP.Instance` 的。
  42. .. note::
  43. `lambda` 函数即匿名函数,是 Python 的重要特性。 ``lambda x: len(x)`` 和下面的这个函数的作用相同::
  44. def func_lambda(x):
  45. return len(x)
  46. 你也可以编写复杂的函数做为 :meth:`~fastNLP.DataSet.apply_field` 与 :meth:`~fastNLP.DataSet.apply` 的参数
  47. Vocabulary 的使用
  48. 我们再用 :class:`~fastNLP.Vocabulary` 类来统计数据中出现的单词,并使用 :meth:`~fastNLP.Vocabulary.index_dataset`
  49. 将单词序列转化为训练可用的数字序列。
  50. .. code-block:: python
  51. from fastNLP import Vocabulary
  52. # 使用Vocabulary类统计单词,并将单词序列转化为数字序列
  53. vocab = Vocabulary(min_freq=2).from_dataset(dataset, field_name='words')
  54. vocab.index_dataset(dataset, field_name='words',new_field_name='words')
  55. print(dataset[0])
  56. 输出数据如下::
  57. {'words': [27, 9, 6, 913, 16, 18, 913, 124, 31, 5715, 5, 1, 2] type=list,
  58. 'target': 1 type=int,
  59. 'seq_len': 13 type=int}
  60. ---------------------
  61. 使用内置模型训练
  62. ---------------------
  63. 内置模型的输入输出命名
  64. fastNLP内置了一些完整的神经网络模型,详见 :doc:`/fastNLP.models` , 我们使用其中的 :class:`~fastNLP.models.CNNText` 模型进行训练。
  65. 为了使用内置的 :class:`~fastNLP.models.CNNText`,我们必须修改 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 的名称。
  66. 在这个例子中模型输入 (forward方法的参数) 为 ``words`` 和 ``seq_len`` ; 预测输出为 ``pred`` ;标准答案为 ``target`` 。
  67. 具体的命名规范可以参考 :doc:`/fastNLP.core.const` 。
  68. 如果不想查看文档,您也可以使用 :class:`~fastNLP.Const` 类进行命名。下面的代码展示了给 :class:`~fastNLP.DataSet` 中
  69. :mod:`~fastNLP.core.field` 改名的 :meth:`~fastNLP.DataSet.rename_field` 方法,以及 :class:`~fastNLP.Const` 类的使用方法。
  70. .. code-block:: python
  71. from fastNLP import Const
  72. dataset.rename_field('words', Const.INPUT)
  73. dataset.rename_field('seq_len', Const.INPUT_LEN)
  74. dataset.rename_field('target', Const.TARGET)
  75. print(Const.INPUT)
  76. print(Const.INPUT_LEN)
  77. print(Const.TARGET)
  78. print(Const.OUTPUT)
  79. 输出结果为::
  80. words
  81. seq_len
  82. target
  83. pred
  84. 在给 :class:`~fastNLP.DataSet` 中 :mod:`~fastNLP.core.field` 改名后,我们还需要设置训练所需的输入和目标,这里使用的是
  85. :meth:`~fastNLP.DataSet.set_input` 和 :meth:`~fastNLP.DataSet.set_target` 两个函数。
  86. .. code-block:: python
  87. #使用dataset的 set_input 和 set_target函数,告诉模型dataset中那些数据是输入,那些数据是标签(目标输出)
  88. dataset.set_input(Const.INPUT, Const.INPUT_LEN)
  89. dataset.set_target(Const.TARGET)
  90. 数据集分割
  91. 除了修改 :mod:`~fastNLP.core.field` 之外,我们还可以对 :class:`~fastNLP.DataSet` 进行分割,以供训练、开发和测试使用。
  92. 下面这段代码展示了 :meth:`~fastNLP.DataSet.split` 的使用方法
  93. .. code-block:: python
  94. train_dev_data, test_data = dataset.split(0.1)
  95. train_data, dev_data = train_dev_data.split(0.1)
  96. print(len(train_data), len(dev_data), len(test_data))
  97. 输出结果为::
  98. 9603 1067 1185
  99. 评价指标
  100. 训练模型需要提供一个评价指标。这里使用准确率做为评价指标。参数的 `命名规则` 跟上面类似。
  101. ``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。
  102. ``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。
  103. .. code-block:: python
  104. from fastNLP import AccuracyMetric
  105. # metrics=AccuracyMetric() 在本例中与下面这行代码等价
  106. metrics=AccuracyMetric(pred=Const.OUTPUT, target=Const.TARGET)
  107. 损失函数
  108. 训练模型需要提供一个损失函数
  109. ,fastNLP中提供了直接可以导入使用的四种loss,分别为:
  110. * :class:`~fastNLP.CrossEntropyLoss`:包装了torch.nn.functional.cross_entropy()函数,返回交叉熵损失(可以运用于多分类场景)
  111. * :class:`~fastNLP.BCELoss`:包装了torch.nn.functional.binary_cross_entropy()函数,返回二分类的交叉熵
  112. * :class:`~fastNLP.L1Loss`:包装了torch.nn.functional.l1_loss()函数,返回L1 损失
  113. * :class:`~fastNLP.NLLLoss`:包装了torch.nn.functional.nll_loss()函数,返回负对数似然损失
  114. 下面提供了一个在分类问题中常用的交叉熵损失。注意它的 **初始化参数** 。
  115. ``pred`` 参数对应的是模型的 forward 方法返回的 dict 中的一个 key 的名字。
  116. ``target`` 参数对应的是 :class:`~fastNLP.DataSet` 中作为标签的 :mod:`~fastNLP.core.field` 的名字。
  117. 这里我们用 :class:`~fastNLP.Const` 来辅助命名,如果你自己编写模型中 forward 方法的返回值或
  118. 数据集中 :mod:`~fastNLP.core.field` 的名字与本例不同, 你可以把 ``pred`` 参数和 ``target`` 参数设定符合自己代码的值。
  119. .. code-block:: python
  120. from fastNLP import CrossEntropyLoss
  121. # loss = CrossEntropyLoss() 在本例中与下面这行代码等价
  122. loss = CrossEntropyLoss(pred=Const.OUTPUT, target=Const.TARGET)
  123. 优化器
  124. 定义模型运行的时候使用的优化器,可以使用fastNLP包装好的优化器:
  125. * :class:`~fastNLP.SGD` :包装了torch.optim.SGD优化器
  126. * :class:`~fastNLP.Adam` :包装了torch.optim.Adam优化器
  127. 也可以直接使用torch.optim.Optimizer中的优化器,并在实例化 :class:`~fastNLP.Trainer` 类的时候传入优化器实参
  128. .. code-block:: python
  129. import torch.optim as optim
  130. from fastNLP import Adam
  131. #使用 torch.optim 定义优化器
  132. optimizer_1=optim.RMSprop(model_cnn.parameters(), lr=0.01, alpha=0.99, eps=1e-08, weight_decay=0, momentum=0, centered=False)
  133. #使用fastNLP中包装的 Adam 定义优化器
  134. optimizer_2=Adam(lr=4e-3, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, model_params=model_cnn.parameters())
  135. 快速训练
  136. 现在我们可以导入 fastNLP 内置的文本分类模型 :class:`~fastNLP.models.CNNText` ,并使用 :class:`~fastNLP.Trainer` 进行训练,
  137. 除了使用 :class:`~fastNLP.Trainer`进行训练,我们也可以通过使用 :class:`~fastNLP.DataSetIter` 来编写自己的训练过程,具体见 :doc:`/tutorials/tutorial_5_datasetiter`
  138. .. code-block:: python
  139. from fastNLP.models import CNNText
  140. #词嵌入的维度、训练的轮数和batch size
  141. EMBED_DIM = 100
  142. N_EPOCHS = 10
  143. BATCH_SIZE = 16
  144. #使用CNNText的时候第一个参数输入一个tuple,作为模型定义embedding的参数
  145. #还可以传入 kernel_nums, kernel_sizes, padding, dropout的自定义值
  146. model_cnn = CNNText((len(vocab),EMBED_DIM), num_classes=3, padding=2, dropout=0.1)
  147. #如果在定义trainer的时候没有传入optimizer参数,模型默认的优化器为torch.optim.Adam且learning rate为lr=4e-3
  148. #这里只使用了optimizer_1作为优化器输入,感兴趣可以尝试optimizer_2或者其他优化器作为输入
  149. #这里只使用了loss作为损失函数输入,感兴趣可以尝试其他损失函数输入
  150. trainer = Trainer(model=model_cnn, train_data=train_data, dev_data=dev_data, loss=loss, metrics=metrics,
  151. optimizer=optimizer_1,n_epochs=N_EPOCHS, batch_size=BATCH_SIZE)
  152. trainer.train()
  153. 训练过程的输出如下::
  154. input fields after batch(if batch size is 2):
  155. words: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 40])
  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. training epochs started 2019-07-08-15-44-48
  160. Evaluation at Epoch 1/10. Step:601/6010. AccuracyMetric: acc=0.59044
  161. Evaluation at Epoch 2/10. Step:1202/6010. AccuracyMetric: acc=0.599813
  162. Evaluation at Epoch 3/10. Step:1803/6010. AccuracyMetric: acc=0.508903
  163. Evaluation at Epoch 4/10. Step:2404/6010. AccuracyMetric: acc=0.596064
  164. Evaluation at Epoch 5/10. Step:3005/6010. AccuracyMetric: acc=0.47985
  165. Evaluation at Epoch 6/10. Step:3606/6010. AccuracyMetric: acc=0.589503
  166. Evaluation at Epoch 7/10. Step:4207/6010. AccuracyMetric: acc=0.311153
  167. Evaluation at Epoch 8/10. Step:4808/6010. AccuracyMetric: acc=0.549203
  168. Evaluation at Epoch 9/10. Step:5409/6010. AccuracyMetric: acc=0.581068
  169. Evaluation at Epoch 10/10. Step:6010/6010. AccuracyMetric: acc=0.523899
  170. In Epoch:2/Step:1202, got best dev performance:AccuracyMetric: acc=0.599813
  171. Reloaded the best model.
  172. 快速测试
  173. 与 :class:`~fastNLP.Trainer` 对应,fastNLP 也提供了 :class:`~fastNLP.Tester` 用于快速测试,用法如下
  174. .. code-block:: python
  175. from fastNLP import Tester
  176. tester = Tester(test_data, model_cnn, metrics=AccuracyMetric())
  177. tester.test()
  178. 训练过程输出如下::
  179. [tester]
  180. AccuracyMetric: acc=0.565401