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_10min_tutorial.ipynb 24 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "fastNLP10 分钟上手教程\n",
  8. "-------\n",
  9. "\n",
  10. "fastNLP提供方便的数据预处理,训练和测试模型的功能"
  11. ]
  12. },
  13. {
  14. "cell_type": "markdown",
  15. "metadata": {},
  16. "source": [
  17. "如果您还没有通过pip安装fastNLP,可以执行下面的操作加载当前模块"
  18. ]
  19. },
  20. {
  21. "cell_type": "code",
  22. "execution_count": 4,
  23. "metadata": {},
  24. "outputs": [],
  25. "source": [
  26. "import sys\n",
  27. "sys.path.append(\"../\")"
  28. ]
  29. },
  30. {
  31. "cell_type": "markdown",
  32. "metadata": {},
  33. "source": [
  34. "DataSet & Instance\n",
  35. "------\n",
  36. "\n",
  37. "fastNLP用DataSet和Instance保存和处理数据。每个DataSet表示一个数据集,每个Instance表示一个数据样本。一个DataSet存有多个Instance,每个Instance可以自定义存哪些内容。\n",
  38. "\n",
  39. "有一些read_*方法,可以轻松从文件读取数据,存成DataSet。"
  40. ]
  41. },
  42. {
  43. "cell_type": "code",
  44. "execution_count": 6,
  45. "metadata": {},
  46. "outputs": [
  47. {
  48. "name": "stdout",
  49. "output_type": "stream",
  50. "text": [
  51. "77\n"
  52. ]
  53. }
  54. ],
  55. "source": [
  56. "from fastNLP import DataSet\n",
  57. "from fastNLP import Instance\n",
  58. "\n",
  59. "# 从csv读取数据到DataSet\n",
  60. "dataset = DataSet.read_csv('sample_data/tutorial_sample_dataset.csv', headers=('raw_sentence', 'label'), sep='\\t')\n",
  61. "print(len(dataset))"
  62. ]
  63. },
  64. {
  65. "cell_type": "code",
  66. "execution_count": 7,
  67. "metadata": {},
  68. "outputs": [
  69. {
  70. "name": "stdout",
  71. "output_type": "stream",
  72. "text": [
  73. "{'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 . type=str,\n",
  74. "'label': 1 type=str}\n",
  75. "{'raw_sentence': The plot is romantic comedy boilerplate from start to finish . type=str,\n",
  76. "'label': 2 type=str}\n"
  77. ]
  78. }
  79. ],
  80. "source": [
  81. "# 使用数字索引[k],获取第k个样本\n",
  82. "print(dataset[0])\n",
  83. "\n",
  84. "# 索引也可以是负数\n",
  85. "print(dataset[-3])"
  86. ]
  87. },
  88. {
  89. "cell_type": "markdown",
  90. "metadata": {},
  91. "source": [
  92. "## Instance\n",
  93. "Instance表示一个样本,由一个或多个field(域,属性,特征)组成,每个field有名字和值。\n",
  94. "\n",
  95. "在初始化Instance时即可定义它包含的域,使用 \"field_name=field_value\"的写法。"
  96. ]
  97. },
  98. {
  99. "cell_type": "code",
  100. "execution_count": 8,
  101. "metadata": {},
  102. "outputs": [
  103. {
  104. "data": {
  105. "text/plain": [
  106. "{'raw_sentence': fake data type=str,\n",
  107. "'label': 0 type=str}"
  108. ]
  109. },
  110. "execution_count": 8,
  111. "metadata": {},
  112. "output_type": "execute_result"
  113. }
  114. ],
  115. "source": [
  116. "# DataSet.append(Instance)加入新数据\n",
  117. "dataset.append(Instance(raw_sentence='fake data', label='0'))\n",
  118. "dataset[-1]"
  119. ]
  120. },
  121. {
  122. "cell_type": "markdown",
  123. "metadata": {},
  124. "source": [
  125. "## DataSet.apply方法\n",
  126. "数据预处理利器"
  127. ]
  128. },
  129. {
  130. "cell_type": "code",
  131. "execution_count": 9,
  132. "metadata": {},
  133. "outputs": [
  134. {
  135. "name": "stdout",
  136. "output_type": "stream",
  137. "text": [
  138. "{'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 . type=str,\n",
  139. "'label': 1 type=str}\n"
  140. ]
  141. }
  142. ],
  143. "source": [
  144. "# 将所有数字转为小写\n",
  145. "dataset.apply(lambda x: x['raw_sentence'].lower(), new_field_name='raw_sentence')\n",
  146. "print(dataset[0])"
  147. ]
  148. },
  149. {
  150. "cell_type": "code",
  151. "execution_count": 10,
  152. "metadata": {},
  153. "outputs": [
  154. {
  155. "name": "stdout",
  156. "output_type": "stream",
  157. "text": [
  158. "{'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 . type=str,\n",
  159. "'label': 1 type=int}\n"
  160. ]
  161. }
  162. ],
  163. "source": [
  164. "# label转int\n",
  165. "dataset.apply(lambda x: int(x['label']), new_field_name='label')\n",
  166. "print(dataset[0])"
  167. ]
  168. },
  169. {
  170. "cell_type": "code",
  171. "execution_count": 11,
  172. "metadata": {},
  173. "outputs": [
  174. {
  175. "name": "stdout",
  176. "output_type": "stream",
  177. "text": [
  178. "{'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 . type=str,\n",
  179. "'label': 1 type=int,\n",
  180. "'words': ['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', '.'] type=list}\n"
  181. ]
  182. }
  183. ],
  184. "source": [
  185. "# 使用空格分割句子\n",
  186. "def split_sent(ins):\n",
  187. " return ins['raw_sentence'].split()\n",
  188. "dataset.apply(split_sent, new_field_name='words')\n",
  189. "print(dataset[0])"
  190. ]
  191. },
  192. {
  193. "cell_type": "code",
  194. "execution_count": 12,
  195. "metadata": {},
  196. "outputs": [
  197. {
  198. "name": "stdout",
  199. "output_type": "stream",
  200. "text": [
  201. "{'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 . type=str,\n",
  202. "'label': 1 type=int,\n",
  203. "'words': ['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', '.'] type=list,\n",
  204. "'seq_len': 37 type=int}\n"
  205. ]
  206. }
  207. ],
  208. "source": [
  209. "# 增加长度信息\n",
  210. "dataset.apply(lambda x: len(x['words']), new_field_name='seq_len')\n",
  211. "print(dataset[0])"
  212. ]
  213. },
  214. {
  215. "cell_type": "markdown",
  216. "metadata": {},
  217. "source": [
  218. "## DataSet.drop\n",
  219. "筛选数据"
  220. ]
  221. },
  222. {
  223. "cell_type": "code",
  224. "execution_count": 13,
  225. "metadata": {},
  226. "outputs": [
  227. {
  228. "name": "stdout",
  229. "output_type": "stream",
  230. "text": [
  231. "77\n"
  232. ]
  233. }
  234. ],
  235. "source": [
  236. "# 删除低于某个长度的词语\n",
  237. "dataset.drop(lambda x: x['seq_len'] <= 3)\n",
  238. "print(len(dataset))"
  239. ]
  240. },
  241. {
  242. "cell_type": "markdown",
  243. "metadata": {},
  244. "source": [
  245. "## 配置DataSet\n",
  246. "1. 哪些域是特征,哪些域是标签\n",
  247. "2. 切分训练集/验证集"
  248. ]
  249. },
  250. {
  251. "cell_type": "code",
  252. "execution_count": 14,
  253. "metadata": {},
  254. "outputs": [],
  255. "source": [
  256. "# 设置DataSet中,哪些field要转为tensor\n",
  257. "\n",
  258. "# set target,loss或evaluate中的golden,计算loss,模型评估时使用\n",
  259. "dataset.set_target(\"label\")\n",
  260. "# set input,模型forward时使用\n",
  261. "dataset.set_input(\"words\")"
  262. ]
  263. },
  264. {
  265. "cell_type": "code",
  266. "execution_count": 15,
  267. "metadata": {},
  268. "outputs": [
  269. {
  270. "name": "stdout",
  271. "output_type": "stream",
  272. "text": [
  273. "54\n",
  274. "23\n"
  275. ]
  276. }
  277. ],
  278. "source": [
  279. "# 分出测试集、训练集\n",
  280. "\n",
  281. "test_data, train_data = dataset.split(0.3)\n",
  282. "print(len(test_data))\n",
  283. "print(len(train_data))"
  284. ]
  285. },
  286. {
  287. "cell_type": "markdown",
  288. "metadata": {},
  289. "source": [
  290. "Vocabulary\n",
  291. "------\n",
  292. "\n",
  293. "fastNLP中的Vocabulary轻松构建词表,将词转成数字"
  294. ]
  295. },
  296. {
  297. "cell_type": "code",
  298. "execution_count": 16,
  299. "metadata": {},
  300. "outputs": [
  301. {
  302. "name": "stdout",
  303. "output_type": "stream",
  304. "text": [
  305. "{'raw_sentence': a welcome relief from baseball movies that try too hard to be mythic , this one is a sweet and modest and ultimately winning story . type=str,\n",
  306. "'label': 3 type=int,\n",
  307. "'words': [4, 1, 1, 18, 1, 1, 13, 1, 1, 1, 8, 26, 1, 5, 35, 1, 11, 4, 1, 10, 1, 10, 1, 1, 1, 2] type=list,\n",
  308. "'seq_len': 26 type=int}\n"
  309. ]
  310. }
  311. ],
  312. "source": [
  313. "from fastNLP import Vocabulary\n",
  314. "\n",
  315. "# 构建词表, Vocabulary.add(word)\n",
  316. "vocab = Vocabulary(min_freq=2)\n",
  317. "train_data.apply(lambda x: [vocab.add(word) for word in x['words']])\n",
  318. "vocab.build_vocab()\n",
  319. "\n",
  320. "# index句子, Vocabulary.to_index(word)\n",
  321. "train_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='words')\n",
  322. "test_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='words')\n",
  323. "\n",
  324. "\n",
  325. "print(test_data[0])"
  326. ]
  327. },
  328. {
  329. "cell_type": "code",
  330. "execution_count": null,
  331. "metadata": {},
  332. "outputs": [],
  333. "source": [
  334. "# 如果你们需要做强化学习或者GAN之类的项目,你们也可以使用这些数据预处理的工具\n",
  335. "from fastNLP.core.batch import Batch\n",
  336. "from fastNLP.core.sampler import RandomSampler\n",
  337. "\n",
  338. "batch_iterator = Batch(dataset=train_data, batch_size=2, sampler=RandomSampler())\n",
  339. "for batch_x, batch_y in batch_iterator:\n",
  340. " print(\"batch_x has: \", batch_x)\n",
  341. " print(\"batch_y has: \", batch_y)\n",
  342. " break"
  343. ]
  344. },
  345. {
  346. "cell_type": "markdown",
  347. "metadata": {},
  348. "source": [
  349. "# Model\n",
  350. "定义一个PyTorch模型"
  351. ]
  352. },
  353. {
  354. "cell_type": "code",
  355. "execution_count": 17,
  356. "metadata": {},
  357. "outputs": [
  358. {
  359. "data": {
  360. "text/plain": [
  361. "CNNText(\n",
  362. " (embed): Embedding(\n",
  363. " (embed): Embedding(59, 50, padding_idx=0)\n",
  364. " (dropout): Dropout(p=0.0)\n",
  365. " )\n",
  366. " (conv_pool): ConvMaxpool(\n",
  367. " (convs): ModuleList(\n",
  368. " (0): Conv1d(50, 3, kernel_size=(3,), stride=(1,), padding=(2,))\n",
  369. " (1): Conv1d(50, 4, kernel_size=(4,), stride=(1,), padding=(2,))\n",
  370. " (2): Conv1d(50, 5, kernel_size=(5,), stride=(1,), padding=(2,))\n",
  371. " )\n",
  372. " )\n",
  373. " (dropout): Dropout(p=0.1)\n",
  374. " (fc): Linear(\n",
  375. " (linear): Linear(in_features=12, out_features=5, bias=True)\n",
  376. " )\n",
  377. ")"
  378. ]
  379. },
  380. "execution_count": 17,
  381. "metadata": {},
  382. "output_type": "execute_result"
  383. }
  384. ],
  385. "source": [
  386. "from fastNLP.models import CNNText\n",
  387. "model = CNNText(embed_num=len(vocab), embed_dim=50, num_classes=5, padding=2, dropout=0.1)\n",
  388. "model"
  389. ]
  390. },
  391. {
  392. "cell_type": "markdown",
  393. "metadata": {},
  394. "source": [
  395. "这是上述模型的forward方法。如果你不知道什么是forward方法,请参考我们的PyTorch教程。\n",
  396. "\n",
  397. "注意两点:\n",
  398. "1. forward参数名字叫**word_seq**,请记住。\n",
  399. "2. forward的返回值是一个**dict**,其中有个key的名字叫**output**。\n",
  400. "\n",
  401. "```Python\n",
  402. " def forward(self, word_seq):\n",
  403. " \"\"\"\n",
  404. "\n",
  405. " :param word_seq: torch.LongTensor, [batch_size, seq_len]\n",
  406. " :return output: dict of torch.LongTensor, [batch_size, num_classes]\n",
  407. " \"\"\"\n",
  408. " x = self.embed(word_seq) # [N,L] -> [N,L,C]\n",
  409. " x = self.conv_pool(x) # [N,L,C] -> [N,C]\n",
  410. " x = self.dropout(x)\n",
  411. " x = self.fc(x) # [N,C] -> [N, N_class]\n",
  412. " return {'output': x}\n",
  413. "```"
  414. ]
  415. },
  416. {
  417. "cell_type": "markdown",
  418. "metadata": {},
  419. "source": [
  420. "这是上述模型的predict方法,是用来直接输出该任务的预测结果,与forward目的不同。\n",
  421. "\n",
  422. "注意两点:\n",
  423. "1. predict参数名也叫**word_seq**。\n",
  424. "2. predict的返回值是也一个**dict**,其中有个key的名字叫**predict**。\n",
  425. "\n",
  426. "```\n",
  427. " def predict(self, word_seq):\n",
  428. " \"\"\"\n",
  429. "\n",
  430. " :param word_seq: torch.LongTensor, [batch_size, seq_len]\n",
  431. " :return predict: dict of torch.LongTensor, [batch_size, seq_len]\n",
  432. " \"\"\"\n",
  433. " output = self(word_seq)\n",
  434. " _, predict = output['output'].max(dim=1)\n",
  435. " return {'predict': predict}\n",
  436. "```"
  437. ]
  438. },
  439. {
  440. "cell_type": "markdown",
  441. "metadata": {},
  442. "source": [
  443. "Trainer & Tester\n",
  444. "------\n",
  445. "\n",
  446. "使用fastNLP的Trainer训练模型"
  447. ]
  448. },
  449. {
  450. "cell_type": "code",
  451. "execution_count": 18,
  452. "metadata": {},
  453. "outputs": [],
  454. "source": [
  455. "from fastNLP import Trainer\n",
  456. "from copy import deepcopy\n",
  457. "from fastNLP.core.losses import CrossEntropyLoss\n",
  458. "from fastNLP.core.metrics import AccuracyMetric\n",
  459. "\n",
  460. "\n",
  461. "# 更改DataSet中对应field的名称,与模型的forward的参数名一致\n",
  462. "# 因为forward的参数叫word_seq, 所以要把原本叫words的field改名为word_seq\n",
  463. "# 这里的演示是让你了解这种**命名规则**\n",
  464. "train_data.rename_field('words', 'word_seq')\n",
  465. "test_data.rename_field('words', 'word_seq')\n",
  466. "\n",
  467. "# 顺便把label换名为label_seq\n",
  468. "train_data.rename_field('label', 'label_seq')\n",
  469. "test_data.rename_field('label', 'label_seq')"
  470. ]
  471. },
  472. {
  473. "cell_type": "markdown",
  474. "metadata": {},
  475. "source": [
  476. "### loss\n",
  477. "训练模型需要提供一个损失函数\n",
  478. "\n",
  479. "下面提供了一个在分类问题中常用的交叉熵损失。注意它的**初始化参数**。\n",
  480. "\n",
  481. "pred参数对应的是模型的forward返回的dict的一个key的名字,这里是\"output\"。\n",
  482. "\n",
  483. "target参数对应的是dataset作为标签的field的名字,这里是\"label_seq\"。"
  484. ]
  485. },
  486. {
  487. "cell_type": "code",
  488. "execution_count": 19,
  489. "metadata": {},
  490. "outputs": [],
  491. "source": [
  492. "loss = CrossEntropyLoss(pred=\"output\", target=\"label_seq\")"
  493. ]
  494. },
  495. {
  496. "cell_type": "markdown",
  497. "metadata": {},
  498. "source": [
  499. "### Metric\n",
  500. "定义评价指标\n",
  501. "\n",
  502. "这里使用准确率。参数的“命名规则”跟上面类似。\n",
  503. "\n",
  504. "pred参数对应的是模型的predict方法返回的dict的一个key的名字,这里是\"predict\"。\n",
  505. "\n",
  506. "target参数对应的是dataset作为标签的field的名字,这里是\"label_seq\"。"
  507. ]
  508. },
  509. {
  510. "cell_type": "code",
  511. "execution_count": 20,
  512. "metadata": {},
  513. "outputs": [],
  514. "source": [
  515. "metric = AccuracyMetric(pred=\"predict\", target=\"label_seq\")"
  516. ]
  517. },
  518. {
  519. "cell_type": "code",
  520. "execution_count": 21,
  521. "metadata": {},
  522. "outputs": [
  523. {
  524. "name": "stdout",
  525. "output_type": "stream",
  526. "text": [
  527. "input fields after batch(if batch size is 2):\n",
  528. "\tword_seq: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 26]) \n",
  529. "target fields after batch(if batch size is 2):\n",
  530. "\tlabel_seq: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
  531. "\n",
  532. "training epochs started 2019-01-12 17-07-51\n"
  533. ]
  534. },
  535. {
  536. "data": {
  537. "text/plain": [
  538. "HBox(children=(IntProgress(value=0, layout=Layout(flex='2'), max=10), HTML(value='')), layout=Layout(display='…"
  539. ]
  540. },
  541. "metadata": {},
  542. "output_type": "display_data"
  543. },
  544. {
  545. "name": "stdout",
  546. "output_type": "stream",
  547. "text": [
  548. "Evaluation at Epoch 1/5. Step:2/10. AccuracyMetric: acc=0.425926\n",
  549. "Evaluation at Epoch 2/5. Step:4/10. AccuracyMetric: acc=0.425926\n",
  550. "Evaluation at Epoch 3/5. Step:6/10. AccuracyMetric: acc=0.611111\n",
  551. "Evaluation at Epoch 4/5. Step:8/10. AccuracyMetric: acc=0.648148\n",
  552. "Evaluation at Epoch 5/5. Step:10/10. AccuracyMetric: acc=0.703704\n",
  553. "\n",
  554. "In Epoch:5/Step:10, got best dev performance:AccuracyMetric: acc=0.703704\n",
  555. "Reloaded the best model.\n"
  556. ]
  557. },
  558. {
  559. "data": {
  560. "text/plain": [
  561. "{'best_eval': {'AccuracyMetric': {'acc': 0.703704}},\n",
  562. " 'best_epoch': 5,\n",
  563. " 'best_step': 10,\n",
  564. " 'seconds': 0.62}"
  565. ]
  566. },
  567. "execution_count": 21,
  568. "metadata": {},
  569. "output_type": "execute_result"
  570. }
  571. ],
  572. "source": [
  573. "# 实例化Trainer,传入模型和数据,进行训练\n",
  574. "# 先在test_data拟合(确保模型的实现是正确的)\n",
  575. "copy_model = deepcopy(model)\n",
  576. "overfit_trainer = Trainer(model=copy_model, train_data=test_data, dev_data=test_data,\n",
  577. " loss=loss,\n",
  578. " metrics=metric,\n",
  579. " save_path=None,\n",
  580. " batch_size=32,\n",
  581. " n_epochs=5)\n",
  582. "overfit_trainer.train()"
  583. ]
  584. },
  585. {
  586. "cell_type": "code",
  587. "execution_count": 22,
  588. "metadata": {},
  589. "outputs": [
  590. {
  591. "name": "stdout",
  592. "output_type": "stream",
  593. "text": [
  594. "input fields after batch(if batch size is 2):\n",
  595. "\tword_seq: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 20]) \n",
  596. "target fields after batch(if batch size is 2):\n",
  597. "\tlabel_seq: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
  598. "\n",
  599. "training epochs started 2019-01-12 17-09-05\n"
  600. ]
  601. },
  602. {
  603. "data": {
  604. "text/plain": [
  605. "HBox(children=(IntProgress(value=0, layout=Layout(flex='2'), max=5), HTML(value='')), layout=Layout(display='i…"
  606. ]
  607. },
  608. "metadata": {},
  609. "output_type": "display_data"
  610. },
  611. {
  612. "name": "stdout",
  613. "output_type": "stream",
  614. "text": [
  615. "Evaluation at Epoch 1/5. Step:1/5. AccuracyMetric: acc=0.37037\n",
  616. "Evaluation at Epoch 2/5. Step:2/5. AccuracyMetric: acc=0.37037\n",
  617. "Evaluation at Epoch 3/5. Step:3/5. AccuracyMetric: acc=0.462963\n",
  618. "Evaluation at Epoch 4/5. Step:4/5. AccuracyMetric: acc=0.425926\n",
  619. "Evaluation at Epoch 5/5. Step:5/5. AccuracyMetric: acc=0.481481\n",
  620. "\n",
  621. "In Epoch:5/Step:5, got best dev performance:AccuracyMetric: acc=0.481481\n",
  622. "Reloaded the best model.\n",
  623. "Train finished!\n"
  624. ]
  625. }
  626. ],
  627. "source": [
  628. "# 用train_data训练,在test_data验证\n",
  629. "trainer = Trainer(model=model, train_data=train_data, dev_data=test_data,\n",
  630. " loss=CrossEntropyLoss(pred=\"output\", target=\"label_seq\"),\n",
  631. " metrics=AccuracyMetric(pred=\"predict\", target=\"label_seq\"),\n",
  632. " save_path=None,\n",
  633. " batch_size=32,\n",
  634. " n_epochs=5)\n",
  635. "trainer.train()\n",
  636. "print('Train finished!')"
  637. ]
  638. },
  639. {
  640. "cell_type": "code",
  641. "execution_count": 23,
  642. "metadata": {},
  643. "outputs": [
  644. {
  645. "name": "stdout",
  646. "output_type": "stream",
  647. "text": [
  648. "[tester] \n",
  649. "AccuracyMetric: acc=0.481481\n",
  650. "{'AccuracyMetric': {'acc': 0.481481}}\n"
  651. ]
  652. }
  653. ],
  654. "source": [
  655. "# 调用Tester在test_data上评价效果\n",
  656. "from fastNLP import Tester\n",
  657. "\n",
  658. "tester = Tester(data=test_data, model=model, metrics=AccuracyMetric(pred=\"predict\", target=\"label_seq\"),\n",
  659. " batch_size=4)\n",
  660. "acc = tester.test()\n",
  661. "print(acc)"
  662. ]
  663. },
  664. {
  665. "cell_type": "markdown",
  666. "metadata": {},
  667. "source": [
  668. "# In summary\n",
  669. "\n",
  670. "## fastNLP Trainer的伪代码逻辑\n",
  671. "### 1. 准备DataSet,假设DataSet中共有如下的fields\n",
  672. " ['raw_sentence', 'word_seq1', 'word_seq2', 'raw_label','label']\n",
  673. " 通过\n",
  674. " DataSet.set_input('word_seq1', word_seq2', flag=True)将'word_seq1', 'word_seq2'设置为input\n",
  675. " 通过\n",
  676. " DataSet.set_target('label', flag=True)将'label'设置为target\n",
  677. "### 2. 初始化模型\n",
  678. " class Model(nn.Module):\n",
  679. " def __init__(self):\n",
  680. " xxx\n",
  681. " def forward(self, word_seq1, word_seq2):\n",
  682. " # (1) 这里使用的形参名必须和DataSet中的input field的名称对应。因为我们是通过形参名, 进行赋值的\n",
  683. " # (2) input field的数量可以多于这里的形参数量。但是不能少于。\n",
  684. " xxxx\n",
  685. " # 输出必须是一个dict\n",
  686. "### 3. Trainer的训练过程\n",
  687. " (1) 从DataSet中按照batch_size取出一个batch,调用Model.forward\n",
  688. " (2) 将 Model.forward的结果 与 标记为target的field 传入Losser当中。\n",
  689. " 由于每个人写的Model.forward的output的dict可能key并不一样,比如有人是{'pred':xxx}, {'output': xxx}; \n",
  690. " 另外每个人将target可能也会设置为不同的名称, 比如有人是label, 有人设置为target;\n",
  691. " 为了解决以上的问题,我们的loss提供映射机制\n",
  692. " 比如CrossEntropyLosser的需要的输入是(prediction, target)。但是forward的output是{'output': xxx}; 'label'是target\n",
  693. " 那么初始化losser的时候写为CrossEntropyLosser(prediction='output', target='label')即可\n",
  694. " (3) 对于Metric是同理的\n",
  695. " Metric计算也是从 forward的结果中取值 与 设置target的field中取值。 也是可以通过映射找到对应的值 \n",
  696. " \n",
  697. " \n",
  698. "\n",
  699. "## 一些问题.\n",
  700. "### 1. DataSet中为什么需要设置input和target\n",
  701. " 只有被设置为input或者target的数据才会在train的过程中被取出来\n",
  702. " (1.1) 我们只会在设置为input的field中寻找传递给Model.forward的参数。\n",
  703. " (1.2) 我们在传递值给losser或者metric的时候会使用来自: \n",
  704. " (a)Model.forward的output\n",
  705. " (b)被设置为target的field\n",
  706. " \n",
  707. "\n",
  708. "### 2. 我们是通过forwad中的形参名将DataSet中的field赋值给对应的参数\n",
  709. " (1.1) 构建模型过程中,\n",
  710. " 例如:\n",
  711. " DataSet中x,seq_lens是input,那么forward就应该是\n",
  712. " def forward(self, x, seq_lens):\n",
  713. " pass\n",
  714. " 我们是通过形参名称进行匹配的field的\n",
  715. " \n",
  716. "\n",
  717. "\n",
  718. "### 1. 加载数据到DataSet\n",
  719. "### 2. 使用apply操作对DataSet进行预处理\n",
  720. " (2.1) 处理过程中将某些field设置为input,某些field设置为target\n",
  721. "### 3. 构建模型\n",
  722. " (3.1) 构建模型过程中,需要注意forward函数的形参名需要和DataSet中设置为input的field名称是一致的。\n",
  723. " 例如:\n",
  724. " DataSet中x,seq_lens是input,那么forward就应该是\n",
  725. " def forward(self, x, seq_lens):\n",
  726. " pass\n",
  727. " 我们是通过形参名称进行匹配的field的\n",
  728. " (3.2) 模型的forward的output需要是dict类型的。\n",
  729. " 建议将输出设置为{\"pred\": xx}.\n",
  730. " \n"
  731. ]
  732. },
  733. {
  734. "cell_type": "code",
  735. "execution_count": null,
  736. "metadata": {},
  737. "outputs": [],
  738. "source": []
  739. }
  740. ],
  741. "metadata": {
  742. "kernelspec": {
  743. "display_name": "Python 3",
  744. "language": "python",
  745. "name": "python3"
  746. },
  747. "language_info": {
  748. "codemirror_mode": {
  749. "name": "ipython",
  750. "version": 3
  751. },
  752. "file_extension": ".py",
  753. "mimetype": "text/x-python",
  754. "name": "python",
  755. "nbconvert_exporter": "python",
  756. "pygments_lexer": "ipython3",
  757. "version": "3.6.7"
  758. }
  759. },
  760. "nbformat": 4,
  761. "nbformat_minor": 2
  762. }