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.

fastnlp_10tmin_tutorial.rst 12 kB

7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. fastNLP 10分钟上手教程
  2. ===============
  3. 教程原文见 https://github.com/fastnlp/fastNLP/blob/master/tutorials/fastnlp_10min_tutorial.ipynb
  4. fastNLP提供方便的数据预处理,训练和测试模型的功能
  5. DataSet & Instance
  6. ------------------
  7. fastNLP用DataSet和Instance保存和处理数据。每个DataSet表示一个数据集,每个Instance表示一个数据样本。一个DataSet存有多个Instance,每个Instance可以自定义存哪些内容。
  8. 有一些read\_\*方法,可以轻松从文件读取数据,存成DataSet。
  9. .. code:: ipython3
  10. from fastNLP import DataSet
  11. from fastNLP import Instance
  12. # 从csv读取数据到DataSet
  13. win_path = "C:\\Users\zyfeng\Desktop\FudanNLP\\fastNLP\\test\\data_for_tests\\tutorial_sample_dataset.csv"
  14. dataset = DataSet.read_csv(win_path, headers=('raw_sentence', 'label'), sep='\t')
  15. print(dataset[0])
  16. .. parsed-literal::
  17. {'raw_sentence': A series of escapades demonstrating the adage that what is good for the goose is also good for the gander , some of which occasionally amuses but none of which amounts to much of a story .,
  18. 'label': 1}
  19. .. code:: ipython3
  20. # DataSet.append(Instance)加入新数据
  21. dataset.append(Instance(raw_sentence='fake data', label='0'))
  22. dataset[-1]
  23. .. parsed-literal::
  24. {'raw_sentence': fake data,
  25. 'label': 0}
  26. .. code:: ipython3
  27. # DataSet.apply(func, new_field_name)对数据预处理
  28. # 将所有数字转为小写
  29. dataset.apply(lambda x: x['raw_sentence'].lower(), new_field_name='raw_sentence')
  30. # label转int
  31. dataset.apply(lambda x: int(x['label']), new_field_name='label_seq', is_target=True)
  32. # 使用空格分割句子
  33. dataset.drop(lambda x: len(x['raw_sentence'].split()) == 0)
  34. def split_sent(ins):
  35. return ins['raw_sentence'].split()
  36. dataset.apply(split_sent, new_field_name='words', is_input=True)
  37. .. code:: ipython3
  38. # DataSet.drop(func)筛除数据
  39. # 删除低于某个长度的词语
  40. dataset.drop(lambda x: len(x['words']) <= 3)
  41. .. code:: ipython3
  42. # 分出测试集、训练集
  43. test_data, train_data = dataset.split(0.3)
  44. print("Train size: ", len(test_data))
  45. print("Test size: ", len(train_data))
  46. .. parsed-literal::
  47. Train size: 54
  48. Test size:
  49. Vocabulary
  50. ----------
  51. fastNLP中的Vocabulary轻松构建词表,将词转成数字
  52. .. code:: ipython3
  53. from fastNLP import Vocabulary
  54. # 构建词表, Vocabulary.add(word)
  55. vocab = Vocabulary(min_freq=2)
  56. train_data.apply(lambda x: [vocab.add(word) for word in x['words']])
  57. vocab.build_vocab()
  58. # index句子, Vocabulary.to_index(word)
  59. train_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='word_seq', is_input=True)
  60. test_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='word_seq', is_input=True)
  61. print(test_data[0])
  62. .. parsed-literal::
  63. {'raw_sentence': the plot is romantic comedy boilerplate from start to finish .,
  64. 'label': 2,
  65. 'label_seq': 2,
  66. 'words': ['the', 'plot', 'is', 'romantic', 'comedy', 'boilerplate', 'from', 'start', 'to', 'finish', '.'],
  67. 'word_seq': [2, 13, 9, 24, 25, 26, 15, 27, 11, 28, 3]}
  68. .. code:: ipython3
  69. # 假设你们需要做强化学习或者gan之类的项目,也许你们可以使用这里的dataset
  70. from fastNLP.core.batch import Batch
  71. from fastNLP.core.sampler import RandomSampler
  72. batch_iterator = Batch(dataset=train_data, batch_size=2, sampler=RandomSampler())
  73. for batch_x, batch_y in batch_iterator:
  74. print("batch_x has: ", batch_x)
  75. print("batch_y has: ", batch_y)
  76. break
  77. .. parsed-literal::
  78. batch_x has: {'words': array([list(['this', 'kind', 'of', 'hands-on', 'storytelling', 'is', 'ultimately', 'what', 'makes', 'shanghai', 'ghetto', 'move', 'beyond', 'a', 'good', ',', 'dry', ',', 'reliable', 'textbook', 'and', 'what', 'allows', 'it', 'to', 'rank', 'with', 'its', 'worthy', 'predecessors', '.']),
  79. list(['the', 'entire', 'movie', 'is', 'filled', 'with', 'deja', 'vu', 'moments', '.'])],
  80. dtype=object), 'word_seq': tensor([[ 19, 184, 6, 1, 481, 9, 206, 50, 91, 1210, 1609, 1330,
  81. 495, 5, 63, 4, 1269, 4, 1, 1184, 7, 50, 1050, 10,
  82. 8, 1611, 16, 21, 1039, 1, 2],
  83. [ 3, 711, 22, 9, 1282, 16, 2482, 2483, 200, 2, 0, 0,
  84. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  85. 0, 0, 0, 0, 0, 0, 0]])}
  86. batch_y has: {'label_seq': tensor([3, 2])}
  87. Model
  88. -----
  89. .. code:: ipython3
  90. # 定义一个简单的Pytorch模型
  91. from fastNLP.models import CNNText
  92. model = CNNText(embed_num=len(vocab), embed_dim=50, num_classes=5, padding=2, dropout=0.1)
  93. model
  94. .. parsed-literal::
  95. CNNText(
  96. (embed): Embedding(
  97. (embed): Embedding(77, 50, padding_idx=0)
  98. (dropout): Dropout(p=0.0)
  99. )
  100. (conv_pool): ConvMaxpool(
  101. (convs): ModuleList(
  102. (0): Conv1d(50, 3, kernel_size=(3,), stride=(1,), padding=(2,))
  103. (1): Conv1d(50, 4, kernel_size=(4,), stride=(1,), padding=(2,))
  104. (2): Conv1d(50, 5, kernel_size=(5,), stride=(1,), padding=(2,))
  105. )
  106. )
  107. (dropout): Dropout(p=0.1)
  108. (fc): Linear(
  109. (linear): Linear(in_features=12, out_features=5, bias=True)
  110. )
  111. )
  112. Trainer & Tester
  113. ----------------
  114. 使用fastNLP的Trainer训练模型
  115. .. code:: ipython3
  116. from fastNLP import Trainer
  117. from copy import deepcopy
  118. from fastNLP import CrossEntropyLoss
  119. from fastNLP import AccuracyMetric
  120. .. code:: ipython3
  121. # 进行overfitting测试
  122. copy_model = deepcopy(model)
  123. overfit_trainer = Trainer(model=copy_model,
  124. train_data=test_data,
  125. dev_data=test_data,
  126. loss=CrossEntropyLoss(pred="output", target="label_seq"),
  127. metrics=AccuracyMetric(),
  128. n_epochs=10,
  129. save_path=None)
  130. overfit_trainer.train()
  131. .. parsed-literal::
  132. training epochs started 2018-12-07 14:07:20
  133. .. parsed-literal::
  134. HBox(children=(IntProgress(value=0, layout=Layout(flex='2'), max=20), HTML(value='')), layout=Layout(display='…
  135. .. parsed-literal::
  136. Epoch 1/10. Step:2/20. AccuracyMetric: acc=0.037037
  137. Epoch 2/10. Step:4/20. AccuracyMetric: acc=0.296296
  138. Epoch 3/10. Step:6/20. AccuracyMetric: acc=0.333333
  139. Epoch 4/10. Step:8/20. AccuracyMetric: acc=0.555556
  140. Epoch 5/10. Step:10/20. AccuracyMetric: acc=0.611111
  141. Epoch 6/10. Step:12/20. AccuracyMetric: acc=0.481481
  142. Epoch 7/10. Step:14/20. AccuracyMetric: acc=0.62963
  143. Epoch 8/10. Step:16/20. AccuracyMetric: acc=0.685185
  144. Epoch 9/10. Step:18/20. AccuracyMetric: acc=0.722222
  145. Epoch 10/10. Step:20/20. AccuracyMetric: acc=0.777778
  146. .. code:: ipython3
  147. # 实例化Trainer,传入模型和数据,进行训练
  148. trainer = Trainer(model=model,
  149. train_data=train_data,
  150. dev_data=test_data,
  151. loss=CrossEntropyLoss(pred="output", target="label_seq"),
  152. metrics=AccuracyMetric(),
  153. n_epochs=5)
  154. trainer.train()
  155. print('Train finished!')
  156. .. parsed-literal::
  157. training epochs started 2018-12-07 14:08:10
  158. .. parsed-literal::
  159. HBox(children=(IntProgress(value=0, layout=Layout(flex='2'), max=5), HTML(value='')), layout=Layout(display='i…
  160. .. parsed-literal::
  161. Epoch 1/5. Step:1/5. AccuracyMetric: acc=0.037037
  162. Epoch 2/5. Step:2/5. AccuracyMetric: acc=0.037037
  163. Epoch 3/5. Step:3/5. AccuracyMetric: acc=0.037037
  164. Epoch 4/5. Step:4/5. AccuracyMetric: acc=0.185185
  165. Epoch 5/5. Step:5/5. AccuracyMetric: acc=0.240741
  166. Train finished!
  167. .. code:: ipython3
  168. from fastNLP import Tester
  169. tester = Tester(data=test_data, model=model, metrics=AccuracyMetric())
  170. acc = tester.test()
  171. .. parsed-literal::
  172. [tester]
  173. AccuracyMetric: acc=0.240741
  174. In summary
  175. ----------
  176. fastNLP Trainer的伪代码逻辑
  177. ---------------------------
  178. 1. 准备DataSet,假设DataSet中共有如下的fields
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. ::
  181. ['raw_sentence', 'word_seq1', 'word_seq2', 'raw_label','label']
  182. 通过
  183. DataSet.set_input('word_seq1', word_seq2', flag=True)将'word_seq1', 'word_seq2'设置为input
  184. 通过
  185. DataSet.set_target('label', flag=True)将'label'设置为target
  186. 2. 初始化模型
  187. ~~~~~~~~~~~~~
  188. ::
  189. class Model(nn.Module):
  190. def __init__(self):
  191. xxx
  192. def forward(self, word_seq1, word_seq2):
  193. # (1) 这里使用的形参名必须和DataSet中的input field的名称对应。因为我们是通过形参名, 进行赋值的
  194. # (2) input field的数量可以多于这里的形参数量。但是不能少于。
  195. xxxx
  196. # 输出必须是一个dict
  197. 3. Trainer的训练过程
  198. ~~~~~~~~~~~~~~~~~~~~
  199. ::
  200. (1) 从DataSet中按照batch_size取出一个batch,调用Model.forward
  201. (2) 将 Model.forward的结果 与 标记为target的field 传入Losser当中。
  202. 由于每个人写的Model.forward的output的dict可能key并不一样,比如有人是{'pred':xxx}, {'output': xxx};
  203. 另外每个人将target可能也会设置为不同的名称, 比如有人是label, 有人设置为target;
  204. 为了解决以上的问题,我们的loss提供映射机制
  205. 比如CrossEntropyLosser的需要的输入是(prediction, target)。但是forward的output是{'output': xxx}; 'label'是target
  206. 那么初始化losser的时候写为CrossEntropyLosser(prediction='output', target='label')即可
  207. (3) 对于Metric是同理的
  208. Metric计算也是从 forward的结果中取值 与 设置target的field中取值。 也是可以通过映射找到对应的值
  209. 一些问题.
  210. ---------
  211. 1. DataSet中为什么需要设置input和target
  212. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  213. ::
  214. 只有被设置为input或者target的数据才会在train的过程中被取出来
  215. (1.1) 我们只会在设置为input的field中寻找传递给Model.forward的参数。
  216. (1.2) 我们在传递值给losser或者metric的时候会使用来自:
  217. (a)Model.forward的output
  218. (b)被设置为target的field
  219. 2. 我们是通过forwad中的形参名将DataSet中的field赋值给对应的参数
  220. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  221. ::
  222. (1.1) 构建模型过程中,
  223. 例如:
  224. DataSet中x,seq_lens是input,那么forward就应该是
  225. def forward(self, x, seq_lens):
  226. pass
  227. 我们是通过形参名称进行匹配的field的
  228. 1. 加载数据到DataSet
  229. ~~~~~~~~~~~~~~~~~~~~
  230. 2. 使用apply操作对DataSet进行预处理
  231. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  232. ::
  233. (2.1) 处理过程中将某些field设置为input,某些field设置为target
  234. 3. 构建模型
  235. ~~~~~~~~~~~
  236. ::
  237. (3.1) 构建模型过程中,需要注意forward函数的形参名需要和DataSet中设置为input的field名称是一致的。
  238. 例如:
  239. DataSet中x,seq_lens是input,那么forward就应该是
  240. def forward(self, x, seq_lens):
  241. pass
  242. 我们是通过形参名称进行匹配的field的
  243. (3.2) 模型的forward的output需要是dict类型的。
  244. 建议将输出设置为{"pred": xx}.