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_0.ipynb 27 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. {
  2. "cells": [
  3. {
  4. "cell_type": "markdown",
  5. "id": "aec0fde7",
  6. "metadata": {},
  7. "source": [
  8. "# T0. trainer 和 evaluator 的基本使用\n",
  9. "\n",
  10. "  1   trainer 和 evaluator 的基本关系\n",
  11. " \n",
  12. "    1.1   trainer 和 evaluater 的初始化\n",
  13. "\n",
  14. "    1.2   driver 的含义与使用要求\n",
  15. "\n",
  16. "    1.3   trainer 内部初始化 evaluater\n",
  17. "\n",
  18. "  2   使用 fastNLP 0.8 搭建 argmax 模型\n",
  19. "\n",
  20. "    2.1   trainer_step 和 evaluator_step\n",
  21. "\n",
  22. "    2.2   trainer 和 evaluator 的参数匹配\n",
  23. "\n",
  24. "    2.3   一个实际案例:argmax 模型\n",
  25. "\n",
  26. "  3   使用 fastNLP 0.8 训练 argmax 模型\n",
  27. " \n",
  28. "    3.1   trainer 外部初始化的 evaluator\n",
  29. "\n",
  30. "    3.2   trainer 内部初始化的 evaluator "
  31. ]
  32. },
  33. {
  34. "cell_type": "markdown",
  35. "id": "09ea669a",
  36. "metadata": {},
  37. "source": [
  38. "## 1. trainer 和 evaluator 的基本关系\n",
  39. "\n",
  40. "### 1.1 trainer 和 evaluator 的初始化\n",
  41. "\n",
  42. "在`fastNLP 0.8`中,**`Trainer`模块和`Evaluator`模块分别表示“训练器”和“评测器”**\n",
  43. "\n",
  44. "  对应于之前的`fastNLP`版本中的`Trainer`模块和`Tester`模块,其定义方法如下所示\n",
  45. "\n",
  46. "在`fastNLP 0.8`中,需要注意,在同个`python`脚本中先使用`Trainer`训练,然后使用`Evaluator`评测\n",
  47. "\n",
  48. "  非常关键的问题在于**如何正确设置二者的`driver`**。这就引入了另一个问题:什么是 `driver`?\n",
  49. "\n",
  50. "\n",
  51. "```python\n",
  52. "trainer = Trainer(\n",
  53. " model=model, # 模型基于 torch.nn.Module\n",
  54. " train_dataloader=train_dataloader, # 加载模块基于 torch.utils.data.DataLoader \n",
  55. " optimizers=optimizer, # 优化模块基于 torch.optim.*\n",
  56. "\t...\n",
  57. "\tdriver=\"torch\", # 使用 pytorch 模块进行训练 \n",
  58. "\tdevice='cuda', # 使用 GPU:0 显卡执行训练\n",
  59. "\t...\n",
  60. ")\n",
  61. "...\n",
  62. "evaluator = Evaluator(\n",
  63. " model=model, # 模型基于 torch.nn.Module\n",
  64. " dataloaders=evaluate_dataloader, # 加载模块基于 torch.utils.data.DataLoader\n",
  65. " metrics={'acc': Accuracy()}, # 测评方法使用 fastNLP.core.metrics.Accuracy \n",
  66. " ...\n",
  67. " driver=trainer.driver, # 保持同 trainer 的 driver 一致\n",
  68. "\tdevice=None,\n",
  69. " ...\n",
  70. ")\n",
  71. "```"
  72. ]
  73. },
  74. {
  75. "cell_type": "markdown",
  76. "id": "3c11fe1a",
  77. "metadata": {},
  78. "source": [
  79. "### 1.2 driver 的含义与使用要求\n",
  80. "\n",
  81. "在`fastNLP 0.8`中,**`driver`**这一概念被用来表示**控制具体训练的各个步骤的最终执行部分**\n",
  82. "\n",
  83. "  例如神经网络前向、后向传播的具体执行、网络参数的优化和数据在设备间的迁移等\n",
  84. "\n",
  85. "在`fastNLP 0.8`中,**`Trainer`和`Evaluator`都依赖于具体的`driver`来完成整体的工作流程**\n",
  86. "\n",
  87. "  具体`driver`与`Trainer`以及`Evaluator`之间的关系请参考`fastNLP 0.8`的框架设计\n",
  88. "\n",
  89. "注:这里给出一条建议:**在同一脚本中**,**所有的`Trainer`和`Evaluator`使用的`driver`应当保持一致**\n",
  90. "\n",
  91. "  尽量不出现,之前使用单卡的`driver`,后面又使用多卡的`driver`,这是因为,当脚本执行至\n",
  92. "\n",
  93. "  多卡`driver`处时,会重启一个进程执行之前所有内容,如此一来可能会造成一些意想不到的麻烦"
  94. ]
  95. },
  96. {
  97. "cell_type": "markdown",
  98. "id": "2cac4a1a",
  99. "metadata": {},
  100. "source": [
  101. "### 1.3 Trainer 内部初始化 Evaluator\n",
  102. "\n",
  103. "在`fastNLP 0.8`中,如果在**初始化`Trainer`时**,**传入参数`evaluator_dataloaders`和`metrics`**\n",
  104. "\n",
  105. "  则在`Trainer`内部,也会初始化单独的`Evaluator`来帮助训练过程中对验证集的评测\n",
  106. "\n",
  107. "```python\n",
  108. "trainer = Trainer(\n",
  109. " model=model,\n",
  110. " train_dataloader=train_dataloader,\n",
  111. " optimizers=optimizer,\n",
  112. "\t...\n",
  113. "\tdriver=\"torch\",\n",
  114. "\tdevice='cuda',\n",
  115. "\t...\n",
  116. " evaluate_dataloaders=evaluate_dataloader, # 传入参数 evaluator_dataloaders\n",
  117. " metrics={'acc': Accuracy()}, # 传入参数 metrics\n",
  118. "\t...\n",
  119. ")\n",
  120. "```"
  121. ]
  122. },
  123. {
  124. "cell_type": "markdown",
  125. "id": "0c9c7dda",
  126. "metadata": {},
  127. "source": [
  128. "## 2. argmax 模型的搭建实例"
  129. ]
  130. },
  131. {
  132. "cell_type": "markdown",
  133. "id": "524ac200",
  134. "metadata": {},
  135. "source": [
  136. "### 2.1 trainer_step 和 evaluator_step\n",
  137. "\n",
  138. "在`fastNLP 0.8`中,使用`pytorch.nn.Module`搭建需要训练的模型,在搭建模型过程中,除了\n",
  139. "\n",
  140. "  添加`pytorch`要求的`forward`方法外,还需要添加 **`train_step`** 和 **`evaluate_step`** 这两个方法\n",
  141. "\n",
  142. "```python\n",
  143. "class Model(torch.nn.Module):\n",
  144. " def __init__(self):\n",
  145. " super(Model, self).__init__()\n",
  146. " self.loss_fn = torch.nn.CrossEntropyLoss()\n",
  147. " pass\n",
  148. "\n",
  149. " def forward(self, x):\n",
  150. " pass\n",
  151. "\n",
  152. " def train_step(self, x, y):\n",
  153. " pred = self(x)\n",
  154. " return {\"loss\": self.loss_fn(pred, y)}\n",
  155. "\n",
  156. " def evaluate_step(self, x, y):\n",
  157. " pred = self(x)\n",
  158. " pred = torch.max(pred, dim=-1)[1]\n",
  159. " return {\"pred\": pred, \"target\": y}\n",
  160. "```\n",
  161. "***\n",
  162. "在`fastNLP 0.8`中,**函数`train_step`是`Trainer`中参数`train_fn`的默认值**\n",
  163. "\n",
  164. "  由于,在`Trainer`训练时,**`Trainer`通过参数`train_fn`对应的模型方法获得当前数据批次的损失值**\n",
  165. "\n",
  166. "  因此,在`Trainer`训练时,`Trainer`首先会寻找模型是否定义了`train_step`这一方法\n",
  167. "\n",
  168. "    如果没有找到,那么`Trainer`会默认使用模型的`forward`函数来进行训练的前向传播过程\n",
  169. "\n",
  170. "注:在`fastNLP 0.8`中,**`Trainer`要求模型通过`train_step`来返回一个字典**,**满足如`{\"loss\": loss}`的形式**\n",
  171. "\n",
  172. "  此外,这里也可以通过传入`Trainer`的参数`output_mapping`来实现输出的转换,详见(trainer的详细讲解,待补充)\n",
  173. "\n",
  174. "同样,在`fastNLP 0.8`中,**函数`evaluate_step`是`Evaluator`中参数`evaluate_fn`的默认值**\n",
  175. "\n",
  176. "  在`Evaluator`测试时,**`Evaluator`通过参数`evaluate_fn`对应的模型方法获得当前数据批次的评测结果**\n",
  177. "\n",
  178. "  从用户角度,模型通过`evaluate_step`方法来返回一个字典,内容与传入`Evaluator`的`metrics`一致\n",
  179. "\n",
  180. "  从模块角度,该字典的键值和`metric`中的`update`函数的签名一致,这样的机制在传参时被称为“**参数匹配**”\n",
  181. "\n",
  182. "<img src=\"./figures/T0-fig-training-structure.png\" width=\"68%\" height=\"68%\" align=\"center\"></img>"
  183. ]
  184. },
  185. {
  186. "cell_type": "markdown",
  187. "id": "fb3272eb",
  188. "metadata": {},
  189. "source": [
  190. "### 2.2 trainer 和 evaluator 的参数匹配\n",
  191. "\n",
  192. "在`fastNLP 0.8`中,参数匹配涉及到两个方面,分别是在\n",
  193. "\n",
  194. "&emsp; 一方面,**在模型的前向传播中**,**`dataloader`向`train_step`或`evaluate_step`函数传递`batch`**\n",
  195. "\n",
  196. "&emsp; 另方面,**在模型的评测过程中**,**`evaluate_dataloader`向`metric`的`update`函数传递`batch`**\n",
  197. "\n",
  198. "对于前者,在`Trainer`和`Evaluator`中的参数`model_wo_auto_param_call`被设置为`False`时\n",
  199. "\n",
  200. "&emsp; &emsp; **`fastNLP 0.8`要求`dataloader`生成的每个`batch`**,**满足如`{\"x\": x, \"y\": y}`的形式**\n",
  201. "\n",
  202. "&emsp; 同时,`fastNLP 0.8`会查看模型的`train_step`和`evaluate_step`方法的参数签名,并为对应参数传入对应数值\n",
  203. "\n",
  204. "&emsp; &emsp; **字典形式的定义**,**对应在`Dataset`定义的`__getitem__`方法中**,例如下方的`ArgMaxDatset`\n",
  205. "\n",
  206. "&emsp; 而在`Trainer`和`Evaluator`中的参数`model_wo_auto_param_call`被设置为`True`时\n",
  207. "\n",
  208. "&emsp; &emsp; `fastNLP 0.8`会将`batch`直接传给模型的`train_step`、`evaluate_step`或`forward`函数\n",
  209. "\n",
  210. "```python\n",
  211. "class Dataset(torch.utils.data.Dataset):\n",
  212. " def __init__(self, x, y):\n",
  213. " self.x = x\n",
  214. " self.y = y\n",
  215. "\n",
  216. " def __len__(self):\n",
  217. " return len(self.x)\n",
  218. "\n",
  219. " def __getitem__(self, item):\n",
  220. " return {\"x\": self.x[item], \"y\": self.y[item]}\n",
  221. "```"
  222. ]
  223. },
  224. {
  225. "cell_type": "markdown",
  226. "id": "f5f1a6aa",
  227. "metadata": {},
  228. "source": [
  229. "对于后者,首先要明确,在`Trainer`和`Evaluator`中,`metrics`的计算分为`update`和`get_metric`两步\n",
  230. "\n",
  231. "&emsp; &emsp; **`update`函数**,**针对一个`batch`的预测结果**,计算其累计的评价指标\n",
  232. "\n",
  233. "&emsp; &emsp; **`get_metric`函数**,**统计`update`函数累计的评价指标**,来计算最终的评价结果\n",
  234. "\n",
  235. "&emsp; 例如对于`Accuracy`来说,`update`函数会更新一个`batch`的正例数量`right_num`和负例数量`total_num`\n",
  236. "\n",
  237. "&emsp; &emsp; 而`get_metric`函数则会返回所有`batch`的评测值`right_num / total_num`\n",
  238. "\n",
  239. "&emsp; 在此基础上,**`fastNLP 0.8`要求`evaluate_dataloader`生成的每个`batch`传递给对应的`metric`**\n",
  240. "\n",
  241. "&emsp; &emsp; **以`{\"pred\": y_pred, \"target\": y_true}`的形式**,对应其`update`函数的函数签名\n",
  242. "\n",
  243. "<img src=\"./figures/T0-fig-parameter-matching.png\" width=\"75%\" height=\"75%\" align=\"center\"></img>"
  244. ]
  245. },
  246. {
  247. "cell_type": "markdown",
  248. "id": "f62b7bb1",
  249. "metadata": {},
  250. "source": [
  251. "### 2.3 一个实际案例:argmax 模型\n",
  252. "\n",
  253. "下文将通过训练`argmax`模型,简单介绍如何`Trainer`模块的使用方式\n",
  254. "\n",
  255. "&emsp; 首先,使用`pytorch.nn.Module`定义`argmax`模型,目标是输入一组固定维度的向量,输出其中数值最大的数的索引"
  256. ]
  257. },
  258. {
  259. "cell_type": "code",
  260. "execution_count": 1,
  261. "id": "5314482b",
  262. "metadata": {
  263. "pycharm": {
  264. "is_executing": true
  265. }
  266. },
  267. "outputs": [],
  268. "source": [
  269. "import torch\n",
  270. "import torch.nn as nn\n",
  271. "\n",
  272. "class ArgMaxModel(nn.Module):\n",
  273. " def __init__(self, num_labels, feature_dimension):\n",
  274. " super(ArgMaxModel, self).__init__()\n",
  275. " self.num_labels = num_labels\n",
  276. "\n",
  277. " self.linear1 = nn.Linear(in_features=feature_dimension, out_features=10)\n",
  278. " self.ac1 = nn.ReLU()\n",
  279. " self.linear2 = nn.Linear(in_features=10, out_features=10)\n",
  280. " self.ac2 = nn.ReLU()\n",
  281. " self.output = nn.Linear(in_features=10, out_features=num_labels)\n",
  282. " self.loss_fn = nn.CrossEntropyLoss()\n",
  283. "\n",
  284. " def forward(self, x):\n",
  285. " pred = self.ac1(self.linear1(x))\n",
  286. " pred = self.ac2(self.linear2(pred))\n",
  287. " pred = self.output(pred)\n",
  288. " return pred\n",
  289. "\n",
  290. " def train_step(self, x, y):\n",
  291. " pred = self(x)\n",
  292. " return {\"loss\": self.loss_fn(pred, y)}\n",
  293. "\n",
  294. " def evaluate_step(self, x, y):\n",
  295. " pred = self(x)\n",
  296. " pred = torch.max(pred, dim=-1)[1]\n",
  297. " return {\"pred\": pred, \"target\": y}"
  298. ]
  299. },
  300. {
  301. "cell_type": "markdown",
  302. "id": "71f3fa6b",
  303. "metadata": {},
  304. "source": [
  305. "&emsp; 接着,使用`torch.utils.data.Dataset`定义`ArgMaxDataset`数据集\n",
  306. "\n",
  307. "&emsp; &emsp; 数据集包含三个参数:维度`feature_dimension`、数据量`data_num`和随机种子`seed`\n",
  308. "\n",
  309. "&emsp; &emsp; 数据及初始化是,自动生成指定维度的向量,并为每个向量标注出其中最大值的索引作为预测标签"
  310. ]
  311. },
  312. {
  313. "cell_type": "code",
  314. "execution_count": 2,
  315. "id": "fe612e61",
  316. "metadata": {
  317. "pycharm": {
  318. "is_executing": false
  319. }
  320. },
  321. "outputs": [],
  322. "source": [
  323. "from torch.utils.data import Dataset\n",
  324. "\n",
  325. "class ArgMaxDataset(Dataset):\n",
  326. " def __init__(self, feature_dimension, data_num=1000, seed=0):\n",
  327. " self.num_labels = feature_dimension\n",
  328. " self.feature_dimension = feature_dimension\n",
  329. " self.data_num = data_num\n",
  330. " self.seed = seed\n",
  331. "\n",
  332. " g = torch.Generator()\n",
  333. " g.manual_seed(1000)\n",
  334. " self.x = torch.randint(low=-100, high=100, size=[data_num, feature_dimension], generator=g).float()\n",
  335. " self.y = torch.max(self.x, dim=-1)[1]\n",
  336. "\n",
  337. " def __len__(self):\n",
  338. " return self.data_num\n",
  339. "\n",
  340. " def __getitem__(self, item):\n",
  341. " return {\"x\": self.x[item], \"y\": self.y[item]}"
  342. ]
  343. },
  344. {
  345. "cell_type": "markdown",
  346. "id": "2cb96332",
  347. "metadata": {},
  348. "source": [
  349. "&emsp; 然后,根据`ArgMaxModel`类初始化模型实例,保持输入维度`feature_dimension`和输出标签数量`num_labels`一致\n",
  350. "\n",
  351. "&emsp; &emsp; 再根据`ArgMaxDataset`类初始化两个数据集实例,分别用来模型测试和模型评测,数据量各1000笔"
  352. ]
  353. },
  354. {
  355. "cell_type": "code",
  356. "execution_count": 3,
  357. "id": "76172ef8",
  358. "metadata": {
  359. "pycharm": {
  360. "is_executing": false
  361. }
  362. },
  363. "outputs": [],
  364. "source": [
  365. "model = ArgMaxModel(num_labels=10, feature_dimension=10)\n",
  366. "\n",
  367. "train_dataset = ArgMaxDataset(feature_dimension=10, data_num=1000)\n",
  368. "evaluate_dataset = ArgMaxDataset(feature_dimension=10, data_num=100)"
  369. ]
  370. },
  371. {
  372. "cell_type": "markdown",
  373. "id": "4e7d25ee",
  374. "metadata": {},
  375. "source": [
  376. "&emsp; 此外,使用`torch.utils.data.DataLoader`初始化两个数据加载模块,批量大小同为8,分别用于训练和测评"
  377. ]
  378. },
  379. {
  380. "cell_type": "code",
  381. "execution_count": 4,
  382. "id": "363b5b09",
  383. "metadata": {},
  384. "outputs": [],
  385. "source": [
  386. "from torch.utils.data import DataLoader\n",
  387. "\n",
  388. "train_dataloader = DataLoader(train_dataset, batch_size=8, shuffle=True)\n",
  389. "evaluate_dataloader = DataLoader(evaluate_dataset, batch_size=8)"
  390. ]
  391. },
  392. {
  393. "cell_type": "markdown",
  394. "id": "c8d4443f",
  395. "metadata": {},
  396. "source": [
  397. "&emsp; 最后,使用`torch.optim.SGD`初始化一个优化模块,基于随机梯度下降法"
  398. ]
  399. },
  400. {
  401. "cell_type": "code",
  402. "execution_count": 5,
  403. "id": "dc28a2d9",
  404. "metadata": {
  405. "pycharm": {
  406. "is_executing": false
  407. }
  408. },
  409. "outputs": [],
  410. "source": [
  411. "from torch.optim import SGD\n",
  412. "\n",
  413. "optimizer = SGD(model.parameters(), lr=0.001)"
  414. ]
  415. },
  416. {
  417. "cell_type": "markdown",
  418. "id": "eb8ca6cf",
  419. "metadata": {},
  420. "source": [
  421. "## 3. 使用 fastNLP 0.8 训练 argmax 模型\n",
  422. "\n",
  423. "### 3.1 trainer 外部初始化的 evaluator"
  424. ]
  425. },
  426. {
  427. "cell_type": "markdown",
  428. "id": "55145553",
  429. "metadata": {},
  430. "source": [
  431. "通过从`fastNLP`库中导入`Trainer`类,初始化`trainer`实例,对模型进行训练\n",
  432. "\n",
  433. "&emsp; 需要导入预先定义好的模型`model`、对应的数据加载模块`train_dataloader`、优化模块`optimizer`\n",
  434. "\n",
  435. "&emsp; 通过`progress_bar`设定进度条格式,默认为`\"auto\"`,此外还有`\"rich\"`、`\"raw\"`和`None`\n",
  436. "\n",
  437. "&emsp; &emsp; 但对于`\"auto\"`和`\"rich\"`格式,在notebook中,进度条在训练结束后会被丢弃\n",
  438. "\n",
  439. "&emsp; 通过`n_epochs`设定优化迭代轮数,默认为20;全部`Trainer`的全部变量与函数可以通过`dir(trainer)`查询"
  440. ]
  441. },
  442. {
  443. "cell_type": "code",
  444. "execution_count": 6,
  445. "id": "b51b7a2d",
  446. "metadata": {
  447. "pycharm": {
  448. "is_executing": false
  449. }
  450. },
  451. "outputs": [
  452. {
  453. "data": {
  454. "text/html": [
  455. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  456. "</pre>\n"
  457. ],
  458. "text/plain": [
  459. "\n"
  460. ]
  461. },
  462. "metadata": {},
  463. "output_type": "display_data"
  464. }
  465. ],
  466. "source": [
  467. "import sys\n",
  468. "sys.path.append('..')\n",
  469. "\n",
  470. "from fastNLP import Trainer\n",
  471. "\n",
  472. "trainer = Trainer(\n",
  473. " model=model,\n",
  474. " driver=\"torch\",\n",
  475. " device='cuda',\n",
  476. " train_dataloader=train_dataloader,\n",
  477. " optimizers=optimizer,\n",
  478. " n_epochs=10, # 设定迭代轮数 \n",
  479. " progress_bar=\"auto\" # 设定进度条格式\n",
  480. ")"
  481. ]
  482. },
  483. {
  484. "cell_type": "markdown",
  485. "id": "6e202d6e",
  486. "metadata": {},
  487. "source": [
  488. "通过使用`Trainer`类的`run`函数,进行训练\n",
  489. "\n",
  490. "&emsp; 其中,可以通过参数`num_train_batch_per_epoch`决定每个`epoch`运行多少个`batch`后停止,默认全部\n",
  491. "\n",
  492. "&emsp; 此外,可以通过`inspect.getfullargspec(trainer.run)`查询`run`函数的全部参数列表"
  493. ]
  494. },
  495. {
  496. "cell_type": "code",
  497. "execution_count": 7,
  498. "id": "ba047ead",
  499. "metadata": {
  500. "pycharm": {
  501. "is_executing": true
  502. }
  503. },
  504. "outputs": [
  505. {
  506. "data": {
  507. "application/vnd.jupyter.widget-view+json": {
  508. "model_id": "",
  509. "version_major": 2,
  510. "version_minor": 0
  511. },
  512. "text/plain": [
  513. "Output()"
  514. ]
  515. },
  516. "metadata": {},
  517. "output_type": "display_data"
  518. },
  519. {
  520. "data": {
  521. "text/html": [
  522. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  523. ],
  524. "text/plain": []
  525. },
  526. "metadata": {},
  527. "output_type": "display_data"
  528. },
  529. {
  530. "data": {
  531. "text/html": [
  532. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  533. "</pre>\n"
  534. ],
  535. "text/plain": [
  536. "\n"
  537. ]
  538. },
  539. "metadata": {},
  540. "output_type": "display_data"
  541. }
  542. ],
  543. "source": [
  544. "trainer.run()"
  545. ]
  546. },
  547. {
  548. "cell_type": "markdown",
  549. "id": "c16c5fa4",
  550. "metadata": {},
  551. "source": [
  552. "通过从`fastNLP`库中导入`Evaluator`类,初始化`evaluator`实例,对模型进行评测\n",
  553. "\n",
  554. "&emsp; 需要导入预先定义好的模型`model`、对应的数据加载模块`evaluate_dataloader`\n",
  555. "\n",
  556. "&emsp; 需要注意的是评测方法`metrics`,设定为形如`{'acc': fastNLP.core.metrics.Accuracy()}`的字典\n",
  557. "\n",
  558. "&emsp; 类似地,也可以通过`progress_bar`限定进度条格式,默认为`\"auto\"`"
  559. ]
  560. },
  561. {
  562. "cell_type": "code",
  563. "execution_count": 8,
  564. "id": "1c6b6b36",
  565. "metadata": {
  566. "pycharm": {
  567. "is_executing": true
  568. }
  569. },
  570. "outputs": [],
  571. "source": [
  572. "from fastNLP import Evaluator\n",
  573. "from fastNLP.core.metrics import Accuracy\n",
  574. "\n",
  575. "evaluator = Evaluator(\n",
  576. " model=model,\n",
  577. " driver=trainer.driver, # 需要使用 trainer 已经启动的 driver\n",
  578. " device=None,\n",
  579. " dataloaders=evaluate_dataloader,\n",
  580. " metrics={'acc': Accuracy()} # 需要严格使用此种形式的字典\n",
  581. ")"
  582. ]
  583. },
  584. {
  585. "cell_type": "markdown",
  586. "id": "8157bb9b",
  587. "metadata": {},
  588. "source": [
  589. "通过使用`Evaluator`类的`run`函数,进行训练\n",
  590. "\n",
  591. "&emsp; 其中,可以通过参数`num_eval_batch_per_dl`决定每个`evaluate_dataloader`运行多少个`batch`停止,默认全部\n",
  592. "\n",
  593. "&emsp; 最终,输出形如`{'acc#acc': acc}`的字典,在notebook中,进度条在评测结束后会被丢弃"
  594. ]
  595. },
  596. {
  597. "cell_type": "code",
  598. "execution_count": 9,
  599. "id": "f7cb0165",
  600. "metadata": {
  601. "pycharm": {
  602. "is_executing": true
  603. }
  604. },
  605. "outputs": [
  606. {
  607. "data": {
  608. "text/html": [
  609. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  610. ],
  611. "text/plain": []
  612. },
  613. "metadata": {},
  614. "output_type": "display_data"
  615. },
  616. {
  617. "data": {
  618. "text/html": [
  619. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">{</span><span style=\"color: #008000; text-decoration-color: #008000\">'acc#acc'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">0.37</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'total#acc'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">100.0</span>, <span style=\"color: #008000; text-decoration-color: #008000\">'correct#acc'</span>: <span style=\"color: #008080; text-decoration-color: #008080; font-weight: bold\">37.0</span><span style=\"font-weight: bold\">}</span>\n",
  620. "</pre>\n"
  621. ],
  622. "text/plain": [
  623. "\u001b[1m{\u001b[0m\u001b[32m'acc#acc'\u001b[0m: \u001b[1;36m0.37\u001b[0m, \u001b[32m'total#acc'\u001b[0m: \u001b[1;36m100.0\u001b[0m, \u001b[32m'correct#acc'\u001b[0m: \u001b[1;36m37.0\u001b[0m\u001b[1m}\u001b[0m\n"
  624. ]
  625. },
  626. "metadata": {},
  627. "output_type": "display_data"
  628. },
  629. {
  630. "data": {
  631. "text/plain": [
  632. "{'acc#acc': 0.37, 'total#acc': 100.0, 'correct#acc': 37.0}"
  633. ]
  634. },
  635. "execution_count": 9,
  636. "metadata": {},
  637. "output_type": "execute_result"
  638. }
  639. ],
  640. "source": [
  641. "evaluator.run()"
  642. ]
  643. },
  644. {
  645. "cell_type": "markdown",
  646. "id": "dd9f68fa",
  647. "metadata": {},
  648. "source": [
  649. "### 3.2 trainer 内部初始化的 evaluator \n",
  650. "\n",
  651. "通过在初始化`trainer`实例时加入`evaluate_dataloaders`和`metrics`,可以实现在训练过程中进行评测\n",
  652. "\n",
  653. "&emsp; 通过`progress_bar`同时设定训练和评估进度条格式,在notebook中,在进度条训练结束后会被丢弃\n",
  654. "\n",
  655. "&emsp; **通过`evaluate_every`设定评估频率**,可以为负数、正数或者函数:\n",
  656. "\n",
  657. "&emsp; &emsp; **为负数时**,**表示每隔几个`epoch`评估一次**;**为正数时**,**则表示每隔几个`batch`评估一次**"
  658. ]
  659. },
  660. {
  661. "cell_type": "code",
  662. "execution_count": 10,
  663. "id": "183c7d19",
  664. "metadata": {
  665. "pycharm": {
  666. "is_executing": true
  667. }
  668. },
  669. "outputs": [],
  670. "source": [
  671. "trainer = Trainer(\n",
  672. " model=model,\n",
  673. " driver=trainer.driver, # 因为是在同个脚本中,这里的 driver 同样需要重用\n",
  674. " train_dataloader=train_dataloader,\n",
  675. " evaluate_dataloaders=evaluate_dataloader,\n",
  676. " metrics={'acc': Accuracy()},\n",
  677. " optimizers=optimizer,\n",
  678. " n_epochs=10, \n",
  679. " evaluate_every=-1, # 表示每个 epoch 的结束进行评估\n",
  680. ")"
  681. ]
  682. },
  683. {
  684. "cell_type": "markdown",
  685. "id": "714cc404",
  686. "metadata": {},
  687. "source": [
  688. "通过使用`Trainer`类的`run`函数,进行训练\n",
  689. "\n",
  690. "&emsp; 还可以通过参数`num_eval_sanity_batch`决定每次训练前运行多少个`evaluate_batch`进行评测,默认为2\n",
  691. "\n",
  692. "&emsp; 之所以“先评测后训练”,是为了保证训练很长时间的数据,不会在评测阶段出问题,故作此试探性评测"
  693. ]
  694. },
  695. {
  696. "cell_type": "code",
  697. "execution_count": 11,
  698. "id": "2e4daa2c",
  699. "metadata": {
  700. "pycharm": {
  701. "is_executing": true
  702. }
  703. },
  704. "outputs": [
  705. {
  706. "data": {
  707. "text/html": [
  708. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  709. ],
  710. "text/plain": []
  711. },
  712. "metadata": {},
  713. "output_type": "display_data"
  714. },
  715. {
  716. "data": {
  717. "text/html": [
  718. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  719. ],
  720. "text/plain": []
  721. },
  722. "metadata": {},
  723. "output_type": "display_data"
  724. },
  725. {
  726. "data": {
  727. "text/html": [
  728. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
  729. "</pre>\n"
  730. ],
  731. "text/plain": [
  732. "\n"
  733. ]
  734. },
  735. "metadata": {},
  736. "output_type": "display_data"
  737. }
  738. ],
  739. "source": [
  740. "trainer.run()"
  741. ]
  742. },
  743. {
  744. "cell_type": "code",
  745. "execution_count": 12,
  746. "id": "c4e9c619",
  747. "metadata": {},
  748. "outputs": [
  749. {
  750. "data": {
  751. "text/html": [
  752. "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"></pre>\n"
  753. ],
  754. "text/plain": []
  755. },
  756. "metadata": {},
  757. "output_type": "display_data"
  758. },
  759. {
  760. "data": {
  761. "text/plain": [
  762. "{'acc#acc': 0.47, 'total#acc': 100.0, 'correct#acc': 47.0}"
  763. ]
  764. },
  765. "execution_count": 12,
  766. "metadata": {},
  767. "output_type": "execute_result"
  768. }
  769. ],
  770. "source": [
  771. "trainer.evaluator.run()"
  772. ]
  773. },
  774. {
  775. "cell_type": "code",
  776. "execution_count": null,
  777. "id": "db784d5b",
  778. "metadata": {},
  779. "outputs": [],
  780. "source": []
  781. }
  782. ],
  783. "metadata": {
  784. "kernelspec": {
  785. "display_name": "Python 3 (ipykernel)",
  786. "language": "python",
  787. "name": "python3"
  788. },
  789. "language_info": {
  790. "codemirror_mode": {
  791. "name": "ipython",
  792. "version": 3
  793. },
  794. "file_extension": ".py",
  795. "mimetype": "text/x-python",
  796. "name": "python",
  797. "nbconvert_exporter": "python",
  798. "pygments_lexer": "ipython3",
  799. "version": "3.7.13"
  800. },
  801. "pycharm": {
  802. "stem_cell": {
  803. "cell_type": "raw",
  804. "metadata": {
  805. "collapsed": false
  806. },
  807. "source": []
  808. }
  809. }
  810. },
  811. "nbformat": 4,
  812. "nbformat_minor": 5
  813. }