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_tutorial_1204.ipynb 12 kB

6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "metadata": {},
  6. "source": [
  7. "fastNLP上手教程\n",
  8. "-------\n",
  9. "\n",
  10. "fastNLP提供方便的数据预处理,训练和测试模型的功能"
  11. ]
  12. },
  13. {
  14. "cell_type": "code",
  15. "execution_count": null,
  16. "metadata": {},
  17. "outputs": [],
  18. "source": [
  19. "import sys\n",
  20. "sys.path.append('/Users/yh/Desktop/fastNLP/fastNLP/')"
  21. ]
  22. },
  23. {
  24. "cell_type": "markdown",
  25. "metadata": {},
  26. "source": [
  27. "DataSet & Instance\n",
  28. "------\n",
  29. "\n",
  30. "fastNLP用DataSet和Instance保存和处理数据。每个DataSet表示一个数据集,每个Instance表示一个数据样本。一个DataSet存有多个Instance,每个Instance可以自定义存哪些内容。\n",
  31. "\n",
  32. "有一些read_*方法,可以轻松从文件读取数据,存成DataSet。"
  33. ]
  34. },
  35. {
  36. "cell_type": "code",
  37. "execution_count": null,
  38. "metadata": {},
  39. "outputs": [],
  40. "source": [
  41. "from fastNLP import DataSet\n",
  42. "from fastNLP import Instance\n",
  43. "\n",
  44. "# 从csv读取数据到DataSet\n",
  45. "dataset = DataSet.read_csv('../sentence.csv', headers=('raw_sentence', 'label'), sep='\\t')\n",
  46. "print(len(dataset))"
  47. ]
  48. },
  49. {
  50. "cell_type": "code",
  51. "execution_count": null,
  52. "metadata": {},
  53. "outputs": [],
  54. "source": [
  55. "# 使用数字索引[k],获取第k个样本\n",
  56. "print(dataset[0])\n",
  57. "\n",
  58. "# 索引也可以是负数\n",
  59. "print(dataset[-3])"
  60. ]
  61. },
  62. {
  63. "cell_type": "markdown",
  64. "metadata": {},
  65. "source": [
  66. "## Instance\n",
  67. "Instance表示一个样本,由一个或多个field(域,属性,特征)组成,每个field有名字和值。\n",
  68. "\n",
  69. "在初始化Instance时即可定义它包含的域,使用 \"field_name=field_value\"的写法。"
  70. ]
  71. },
  72. {
  73. "cell_type": "code",
  74. "execution_count": null,
  75. "metadata": {},
  76. "outputs": [],
  77. "source": [
  78. "# DataSet.append(Instance)加入新数据\n",
  79. "dataset.append(Instance(raw_sentence='fake data', label='0'))\n",
  80. "dataset[-1]"
  81. ]
  82. },
  83. {
  84. "cell_type": "markdown",
  85. "metadata": {},
  86. "source": [
  87. "## DataSet.apply方法\n",
  88. "数据预处理利器"
  89. ]
  90. },
  91. {
  92. "cell_type": "code",
  93. "execution_count": null,
  94. "metadata": {},
  95. "outputs": [],
  96. "source": [
  97. "# 将所有数字转为小写\n",
  98. "dataset.apply(lambda x: x['raw_sentence'].lower(), new_field_name='raw_sentence')\n",
  99. "print(dataset[0])"
  100. ]
  101. },
  102. {
  103. "cell_type": "code",
  104. "execution_count": null,
  105. "metadata": {},
  106. "outputs": [],
  107. "source": [
  108. "# label转int\n",
  109. "dataset.apply(lambda x: int(x['label']), new_field_name='label')\n",
  110. "print(dataset[0])"
  111. ]
  112. },
  113. {
  114. "cell_type": "code",
  115. "execution_count": null,
  116. "metadata": {},
  117. "outputs": [],
  118. "source": [
  119. "# 使用空格分割句子\n",
  120. "def split_sent(ins):\n",
  121. " return ins['raw_sentence'].split()\n",
  122. "dataset.apply(split_sent, new_field_name='words')\n",
  123. "print(dataset[0])"
  124. ]
  125. },
  126. {
  127. "cell_type": "code",
  128. "execution_count": null,
  129. "metadata": {},
  130. "outputs": [],
  131. "source": [
  132. "# 增加长度信息\n",
  133. "dataset.apply(lambda x: len(x['words']), new_field_name='seq_len')\n",
  134. "print(dataset[0])"
  135. ]
  136. },
  137. {
  138. "cell_type": "markdown",
  139. "metadata": {},
  140. "source": [
  141. "## DataSet.drop\n",
  142. "筛选数据"
  143. ]
  144. },
  145. {
  146. "cell_type": "code",
  147. "execution_count": null,
  148. "metadata": {},
  149. "outputs": [],
  150. "source": [
  151. "dataset.drop(lambda x: x['seq_len'] <= 3)\n",
  152. "print(len(dataset))"
  153. ]
  154. },
  155. {
  156. "cell_type": "markdown",
  157. "metadata": {},
  158. "source": [
  159. "## 配置DataSet\n",
  160. "1. 哪些域是特征,哪些域是标签\n",
  161. "2. 切分训练集/验证集"
  162. ]
  163. },
  164. {
  165. "cell_type": "code",
  166. "execution_count": null,
  167. "metadata": {},
  168. "outputs": [],
  169. "source": [
  170. "# 设置DataSet中,哪些field要转为tensor\n",
  171. "\n",
  172. "# set target,loss或evaluate中的golden,计算loss,模型评估时使用\n",
  173. "dataset.set_target(\"label\")\n",
  174. "# set input,模型forward时使用\n",
  175. "dataset.set_input(\"words\")"
  176. ]
  177. },
  178. {
  179. "cell_type": "code",
  180. "execution_count": null,
  181. "metadata": {},
  182. "outputs": [],
  183. "source": [
  184. "# 分出测试集、训练集\n",
  185. "\n",
  186. "test_data, train_data = dataset.split(0.3)\n",
  187. "print(len(test_data))\n",
  188. "print(len(train_data))"
  189. ]
  190. },
  191. {
  192. "cell_type": "markdown",
  193. "metadata": {},
  194. "source": [
  195. "Vocabulary\n",
  196. "------\n",
  197. "\n",
  198. "fastNLP中的Vocabulary轻松构建词表,将词转成数字"
  199. ]
  200. },
  201. {
  202. "cell_type": "code",
  203. "execution_count": null,
  204. "metadata": {},
  205. "outputs": [],
  206. "source": [
  207. "from fastNLP import Vocabulary\n",
  208. "\n",
  209. "# 构建词表, Vocabulary.add(word)\n",
  210. "vocab = Vocabulary(min_freq=2)\n",
  211. "train_data.apply(lambda x: [vocab.add(word) for word in x['words']])\n",
  212. "vocab.build_vocab()\n",
  213. "\n",
  214. "# index句子, Vocabulary.to_index(word)\n",
  215. "train_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='words')\n",
  216. "test_data.apply(lambda x: [vocab.to_index(word) for word in x['words']], new_field_name='words')\n",
  217. "\n",
  218. "\n",
  219. "print(test_data[0])"
  220. ]
  221. },
  222. {
  223. "cell_type": "markdown",
  224. "metadata": {},
  225. "source": [
  226. "# Model\n",
  227. "定义一个PyTorch模型"
  228. ]
  229. },
  230. {
  231. "cell_type": "code",
  232. "execution_count": null,
  233. "metadata": {},
  234. "outputs": [],
  235. "source": [
  236. "from fastNLP.models import CNNText\n",
  237. "model = CNNText(embed_num=len(vocab), embed_dim=50, num_classes=5, padding=2, dropout=0.1)\n",
  238. "model"
  239. ]
  240. },
  241. {
  242. "cell_type": "markdown",
  243. "metadata": {},
  244. "source": [
  245. "这是上述模型的forward方法。如果你不知道什么是forward方法,请参考我们的PyTorch教程。\n",
  246. "\n",
  247. "注意两点:\n",
  248. "1. forward参数名字叫**word_seq**,请记住。\n",
  249. "2. forward的返回值是一个**dict**,其中有个key的名字叫**output**。\n",
  250. "\n",
  251. "```Python\n",
  252. " def forward(self, word_seq):\n",
  253. " \"\"\"\n",
  254. "\n",
  255. " :param word_seq: torch.LongTensor, [batch_size, seq_len]\n",
  256. " :return output: dict of torch.LongTensor, [batch_size, num_classes]\n",
  257. " \"\"\"\n",
  258. " x = self.embed(word_seq) # [N,L] -> [N,L,C]\n",
  259. " x = self.conv_pool(x) # [N,L,C] -> [N,C]\n",
  260. " x = self.dropout(x)\n",
  261. " x = self.fc(x) # [N,C] -> [N, N_class]\n",
  262. " return {'output': x}\n",
  263. "```"
  264. ]
  265. },
  266. {
  267. "cell_type": "markdown",
  268. "metadata": {},
  269. "source": [
  270. "这是上述模型的predict方法,是用来直接输出该任务的预测结果,与forward目的不同。\n",
  271. "\n",
  272. "注意两点:\n",
  273. "1. predict参数名也叫**word_seq**。\n",
  274. "2. predict的返回值是也一个**dict**,其中有个key的名字叫**predict**。\n",
  275. "\n",
  276. "```\n",
  277. " def predict(self, word_seq):\n",
  278. " \"\"\"\n",
  279. "\n",
  280. " :param word_seq: torch.LongTensor, [batch_size, seq_len]\n",
  281. " :return predict: dict of torch.LongTensor, [batch_size, seq_len]\n",
  282. " \"\"\"\n",
  283. " output = self(word_seq)\n",
  284. " _, predict = output['output'].max(dim=1)\n",
  285. " return {'predict': predict}\n",
  286. "```"
  287. ]
  288. },
  289. {
  290. "cell_type": "markdown",
  291. "metadata": {},
  292. "source": [
  293. "Trainer & Tester\n",
  294. "------\n",
  295. "\n",
  296. "使用fastNLP的Trainer训练模型"
  297. ]
  298. },
  299. {
  300. "cell_type": "code",
  301. "execution_count": null,
  302. "metadata": {},
  303. "outputs": [],
  304. "source": [
  305. "from fastNLP import Trainer\n",
  306. "from copy import deepcopy\n",
  307. "from fastNLP.core.losses import CrossEntropyLoss\n",
  308. "from fastNLP.core.metrics import AccuracyMetric\n",
  309. "\n",
  310. "\n",
  311. "# 更改DataSet中对应field的名称,与模型的forward的参数名一致\n",
  312. "# 因为forward的参数叫word_seq, 所以要把原本叫words的field改名为word_seq\n",
  313. "# 这里的演示是让你了解这种**命名规则**\n",
  314. "train_data.rename_field('words', 'word_seq')\n",
  315. "test_data.rename_field('words', 'word_seq')\n",
  316. "\n",
  317. "# 顺便把label换名为label_seq\n",
  318. "train_data.rename_field('label', 'label_seq')\n",
  319. "test_data.rename_field('label', 'label_seq')"
  320. ]
  321. },
  322. {
  323. "cell_type": "markdown",
  324. "metadata": {},
  325. "source": [
  326. "### loss\n",
  327. "训练模型需要提供一个损失函数\n",
  328. "\n",
  329. "下面提供了一个在分类问题中常用的交叉熵损失。注意它的**初始化参数**。\n",
  330. "\n",
  331. "pred参数对应的是模型的forward返回的dict的一个key的名字,这里是\"output\"。\n",
  332. "\n",
  333. "target参数对应的是dataset作为标签的field的名字,这里是\"label_seq\"。"
  334. ]
  335. },
  336. {
  337. "cell_type": "code",
  338. "execution_count": null,
  339. "metadata": {},
  340. "outputs": [],
  341. "source": [
  342. "loss = CrossEntropyLoss(pred=\"output\", target=\"label_seq\")"
  343. ]
  344. },
  345. {
  346. "cell_type": "markdown",
  347. "metadata": {},
  348. "source": [
  349. "### Metric\n",
  350. "定义评价指标\n",
  351. "\n",
  352. "这里使用准确率。参数的“命名规则”跟上面类似。\n",
  353. "\n",
  354. "pred参数对应的是模型的predict方法返回的dict的一个key的名字,这里是\"predict\"。\n",
  355. "\n",
  356. "target参数对应的是dataset作为标签的field的名字,这里是\"label_seq\"。"
  357. ]
  358. },
  359. {
  360. "cell_type": "code",
  361. "execution_count": null,
  362. "metadata": {},
  363. "outputs": [],
  364. "source": [
  365. "metric = AccuracyMetric(pred=\"predict\", target=\"label_seq\")"
  366. ]
  367. },
  368. {
  369. "cell_type": "code",
  370. "execution_count": null,
  371. "metadata": {},
  372. "outputs": [],
  373. "source": [
  374. "# 实例化Trainer,传入模型和数据,进行训练\n",
  375. "# 先在test_data拟合\n",
  376. "copy_model = deepcopy(model)\n",
  377. "overfit_trainer = Trainer(model=copy_model, train_data=test_data, dev_data=test_data,\n",
  378. " losser=loss,\n",
  379. " metrics=metric,\n",
  380. " save_path=None,\n",
  381. " batch_size=32,\n",
  382. " n_epochs=5)\n",
  383. "overfit_trainer.train()"
  384. ]
  385. },
  386. {
  387. "cell_type": "code",
  388. "execution_count": null,
  389. "metadata": {},
  390. "outputs": [],
  391. "source": [
  392. "# 用train_data训练,在test_data验证\n",
  393. "trainer = Trainer(model=model, train_data=train_data, dev_data=test_data,\n",
  394. " losser=CrossEntropyLoss(pred=\"output\", target=\"label_seq\"),\n",
  395. " metrics=AccuracyMetric(pred=\"predict\", target=\"label_seq\"),\n",
  396. " save_path=None,\n",
  397. " batch_size=32,\n",
  398. " n_epochs=5)\n",
  399. "trainer.train()\n",
  400. "print('Train finished!')"
  401. ]
  402. },
  403. {
  404. "cell_type": "code",
  405. "execution_count": null,
  406. "metadata": {},
  407. "outputs": [],
  408. "source": [
  409. "# 调用Tester在test_data上评价效果\n",
  410. "from fastNLP import Tester\n",
  411. "\n",
  412. "tester = Tester(data=test_data, model=model, metrics=AccuracyMetric(pred=\"predict\", target=\"label_seq\"),\n",
  413. " batch_size=4)\n",
  414. "acc = tester.test()\n",
  415. "print(acc)"
  416. ]
  417. },
  418. {
  419. "cell_type": "code",
  420. "execution_count": null,
  421. "metadata": {},
  422. "outputs": [],
  423. "source": []
  424. }
  425. ],
  426. "metadata": {
  427. "kernelspec": {
  428. "display_name": "Python 3",
  429. "language": "python",
  430. "name": "python3"
  431. },
  432. "language_info": {
  433. "codemirror_mode": {
  434. "name": "ipython",
  435. "version": 3
  436. },
  437. "file_extension": ".py",
  438. "mimetype": "text/x-python",
  439. "name": "python",
  440. "nbconvert_exporter": "python",
  441. "pygments_lexer": "ipython3",
  442. "version": "3.6.7"
  443. }
  444. },
  445. "nbformat": 4,
  446. "nbformat_minor": 2
  447. }