|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206 |
- {
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 使用Metric快速评测你的模型\n",
- "\n",
- "和上一篇教程一样的实验准备代码"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 2,
- "metadata": {},
- "outputs": [],
- "source": [
- "from fastNLP.io import SST2Pipe\n",
- "from fastNLP import Trainer, CrossEntropyLoss, AccuracyMetric\n",
- "from fastNLP.models import CNNText\n",
- "import torch\n",
- "\n",
- "databundle = SST2Pipe().process_from_file()\n",
- "vocab = databundle.get_vocab('words')\n",
- "train_data = databundle.get_dataset('train')[:5000]\n",
- "train_data, test_data = train_data.split(0.015)\n",
- "dev_data = databundle.get_dataset('dev')\n",
- "\n",
- "model = CNNText((len(vocab),100), num_classes=2, dropout=0.1)\n",
- "loss = CrossEntropyLoss()\n",
- "metric = AccuracyMetric()\n",
- "device = 0 if torch.cuda.is_available() else 'cpu'"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "进行训练时,fastNLP提供了各种各样的 metrics 。 如前面的教程中所介绍,AccuracyMetric 类的对象被直接传到 Trainer 中用于训练"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "metadata": {
- "scrolled": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "input fields after batch(if batch size is 2):\n",
- "\twords: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 4]) \n",
- "\tseq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "target fields after batch(if batch size is 2):\n",
- "\ttarget: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "\n",
- "training epochs started 2020-02-28-00-37-08\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=1540.0), HTML(value='')), layout=Layout(d…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.28 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 1/10. Step:154/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.747706\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.17 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 2/10. Step:308/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.745413\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.19 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 3/10. Step:462/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.74656\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.15 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 4/10. Step:616/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.762615\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.42 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 5/10. Step:770/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.736239\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.16 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 6/10. Step:924/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.761468\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.42 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 7/10. Step:1078/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.727064\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.21 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 8/10. Step:1232/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.731651\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.52 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 9/10. Step:1386/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.752294\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.44 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 10/10. Step:1540/1540: \n",
- "\r",
- "AccuracyMetric: acc=0.760321\n",
- "\n",
- "\r\n",
- "In Epoch:4/Step:616, got best dev performance:\n",
- "AccuracyMetric: acc=0.762615\n",
- "Reloaded the best model.\n"
- ]
- },
- {
- "data": {
- "text/plain": [
- "{'best_eval': {'AccuracyMetric': {'acc': 0.762615}},\n",
- " 'best_epoch': 4,\n",
- " 'best_step': 616,\n",
- " 'seconds': 32.63}"
- ]
- },
- "execution_count": 3,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "trainer = Trainer(train_data=train_data, dev_data=dev_data, model=model,\n",
- " loss=loss, device=device, metrics=metric)\n",
- "trainer.train()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "除了 AccuracyMetric 之外,SpanFPreRecMetric 也是一种非常见的评价指标, 例如在序列标注问题中,常以span的方式计算 F-measure, precision, recall。\n",
- "\n",
- "另外,fastNLP 还实现了用于抽取式QA(如SQuAD)的metric ExtractiveQAMetric。 用户可以参考下面这个表格。\n",
- "\n",
- "| 名称 | 介绍 |\n",
- "| -------------------- | ------------------------------------------------- |\n",
- "| `MetricBase` | 自定义metrics需继承的基类 |\n",
- "| `AccuracyMetric` | 简单的正确率metric |\n",
- "| `SpanFPreRecMetric` | 同时计算 F-measure, precision, recall 值的 metric |\n",
- "| `ExtractiveQAMetric` | 用于抽取式QA任务 的metric |\n",
- "\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 定义自己的metrics\n",
- "\n",
- "在定义自己的metrics类时需继承 fastNLP 的 MetricBase, 并覆盖写入 evaluate 和 get_metric 方法。\n",
- "\n",
- "- evaluate(xxx) 中传入一个批次的数据,将针对一个批次的预测结果做评价指标的累计\n",
- "\n",
- "- get_metric(xxx) 当所有数据处理完毕时调用该方法,它将根据 evaluate函数累计的评价指标统计量来计算最终的评价结果\n",
- "\n",
- "以分类问题中,Accuracy计算为例,假设model的forward返回dict中包含 pred 这个key, 并且该key需要用于Accuracy:\n",
- "\n",
- "```python\n",
- "class Model(nn.Module):\n",
- " def __init__(xxx):\n",
- " # do something\n",
- " def forward(self, xxx):\n",
- " # do something\n",
- " return {'pred': pred, 'other_keys':xxx} # pred's shape: batch_size x num_classes\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Version 1\n",
- "\n",
- "假设dataset中 `target` 这个 field 是需要预测的值,并且该 field 被设置为了 target 对应的 `AccMetric` 可以按如下的定义"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "metadata": {},
- "outputs": [],
- "source": [
- "from fastNLP import MetricBase\n",
- "\n",
- "class AccMetric(MetricBase):\n",
- "\n",
- " def __init__(self):\n",
- " super().__init__()\n",
- " # 根据你的情况自定义指标\n",
- " self.total = 0\n",
- " self.acc_count = 0\n",
- "\n",
- " # evaluate的参数需要和DataSet 中 field 名以及模型输出的结果 field 名一致,不然找不到对应的value\n",
- " # pred, target 的参数是 fastNLP 的默认配置\n",
- " def evaluate(self, pred, target):\n",
- " # dev或test时,每个batch结束会调用一次该方法,需要实现如何根据每个batch累加metric\n",
- " self.total += target.size(0)\n",
- " self.acc_count += target.eq(pred).sum().item()\n",
- "\n",
- " def get_metric(self, reset=True): # 在这里定义如何计算metric\n",
- " acc = self.acc_count/self.total\n",
- " if reset: # 是否清零以便重新计算\n",
- " self.acc_count = 0\n",
- " self.total = 0\n",
- " return {'acc': acc}\n",
- " # 需要返回一个dict,key为该metric的名称,该名称会显示到Trainer的progress bar中"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "metadata": {
- "scrolled": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "input fields after batch(if batch size is 2):\n",
- "\twords: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 4]) \n",
- "\tseq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "target fields after batch(if batch size is 2):\n",
- "\ttarget: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "\n",
- "training epochs started 2020-02-28-00-37-41\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=1540.0), HTML(value='')), layout=Layout(d…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.27 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 1/10. Step:154/1540: \n",
- "\r",
- "AccMetric: acc=0.7431192660550459\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.42 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 2/10. Step:308/1540: \n",
- "\r",
- "AccMetric: acc=0.7522935779816514\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.51 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 3/10. Step:462/1540: \n",
- "\r",
- "AccMetric: acc=0.7477064220183486\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.48 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 4/10. Step:616/1540: \n",
- "\r",
- "AccMetric: acc=0.7442660550458715\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.5 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 5/10. Step:770/1540: \n",
- "\r",
- "AccMetric: acc=0.7362385321100917\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.45 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 6/10. Step:924/1540: \n",
- "\r",
- "AccMetric: acc=0.7293577981651376\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.33 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 7/10. Step:1078/1540: \n",
- "\r",
- "AccMetric: acc=0.7190366972477065\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.29 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 8/10. Step:1232/1540: \n",
- "\r",
- "AccMetric: acc=0.7419724770642202\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.34 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 9/10. Step:1386/1540: \n",
- "\r",
- "AccMetric: acc=0.7350917431192661\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.18 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 10/10. Step:1540/1540: \n",
- "\r",
- "AccMetric: acc=0.6846330275229358\n",
- "\n",
- "\r\n",
- "In Epoch:2/Step:308, got best dev performance:\n",
- "AccMetric: acc=0.7522935779816514\n",
- "Reloaded the best model.\n"
- ]
- },
- {
- "data": {
- "text/plain": [
- "{'best_eval': {'AccMetric': {'acc': 0.7522935779816514}},\n",
- " 'best_epoch': 2,\n",
- " 'best_step': 308,\n",
- " 'seconds': 42.7}"
- ]
- },
- "execution_count": 5,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "trainer = Trainer(train_data=train_data, dev_data=dev_data, model=model,\n",
- " loss=loss, device=device, metrics=AccMetric())\n",
- "trainer.train()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Version 2\n",
- "\n",
- "如果需要复用 metric,比如下一次使用 `AccMetric` 时,dataset中目标field不叫 `target` 而叫 `y` ,或者model的输出不是 `pred`\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 6,
- "metadata": {},
- "outputs": [],
- "source": [
- "class AccMetric(MetricBase):\n",
- " def __init__(self, pred=None, target=None):\n",
- " \"\"\"\n",
- " 假设在另一场景使用时,目标field叫y,model给出的key为pred_y。则只需要在初始化AccMetric时,\n",
- " acc_metric = AccMetric(pred='pred_y', target='y')即可。\n",
- " 当初始化为acc_metric = AccMetric() 时,fastNLP会直接使用 'pred', 'target' 作为key去索取对应的的值\n",
- " \"\"\"\n",
- "\n",
- " super().__init__()\n",
- "\n",
- " # 如果没有注册该则效果与 Version 1 就是一样的\n",
- " self._init_param_map(pred=pred, target=target) # 该方法会注册label和pred. 仅需要注册evaluate()方法会用到的参数名即可\n",
- "\n",
- " # 根据你的情况自定义指标\n",
- " self.total = 0\n",
- " self.acc_count = 0\n",
- "\n",
- " # evaluate的参数需要和DataSet 中 field 名以及模型输出的结果 field 名一致,不然找不到对应的value\n",
- " # pred, target 的参数是 fastNLP 的默认配置\n",
- " def evaluate(self, pred, target):\n",
- " # dev或test时,每个batch结束会调用一次该方法,需要实现如何根据每个batch累加metric\n",
- " self.total += target.size(0)\n",
- " self.acc_count += target.eq(pred).sum().item()\n",
- "\n",
- " def get_metric(self, reset=True): # 在这里定义如何计算metric\n",
- " acc = self.acc_count/self.total\n",
- " if reset: # 是否清零以便重新计算\n",
- " self.acc_count = 0\n",
- " self.total = 0\n",
- " return {'acc': acc}\n",
- " # 需要返回一个dict,key为该metric的名称,该名称会显示到Trainer的progress bar中"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 7,
- "metadata": {
- "scrolled": true
- },
- "outputs": [
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "input fields after batch(if batch size is 2):\n",
- "\twords: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2, 4]) \n",
- "\tseq_len: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "target fields after batch(if batch size is 2):\n",
- "\ttarget: (1)type:torch.Tensor (2)dtype:torch.int64, (3)shape:torch.Size([2]) \n",
- "\n",
- "training epochs started 2020-02-28-00-38-24\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=1540.0), HTML(value='')), layout=Layout(d…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.32 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 1/10. Step:154/1540: \n",
- "\r",
- "AccMetric: acc=0.7511467889908257\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.29 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 2/10. Step:308/1540: \n",
- "\r",
- "AccMetric: acc=0.7454128440366973\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.42 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 3/10. Step:462/1540: \n",
- "\r",
- "AccMetric: acc=0.7224770642201835\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.4 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 4/10. Step:616/1540: \n",
- "\r",
- "AccMetric: acc=0.7534403669724771\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.41 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 5/10. Step:770/1540: \n",
- "\r",
- "AccMetric: acc=0.7396788990825688\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.22 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 6/10. Step:924/1540: \n",
- "\r",
- "AccMetric: acc=0.7442660550458715\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.45 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 7/10. Step:1078/1540: \n",
- "\r",
- "AccMetric: acc=0.6903669724770642\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.25 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 8/10. Step:1232/1540: \n",
- "\r",
- "AccMetric: acc=0.7293577981651376\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.4 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 9/10. Step:1386/1540: \n",
- "\r",
- "AccMetric: acc=0.7006880733944955\n",
- "\n"
- ]
- },
- {
- "data": {
- "application/vnd.jupyter.widget-view+json": {
- "model_id": "",
- "version_major": 2,
- "version_minor": 0
- },
- "text/plain": [
- "HBox(children=(FloatProgress(value=0.0, layout=Layout(flex='2'), max=28.0), HTML(value='')), layout=Layout(dis…"
- ]
- },
- "metadata": {},
- "output_type": "display_data"
- },
- {
- "name": "stdout",
- "output_type": "stream",
- "text": [
- "\r",
- "Evaluate data in 0.48 seconds!\n",
- "\r",
- "Evaluation on dev at Epoch 10/10. Step:1540/1540: \n",
- "\r",
- "AccMetric: acc=0.7339449541284404\n",
- "\n",
- "\r\n",
- "In Epoch:4/Step:616, got best dev performance:\n",
- "AccMetric: acc=0.7534403669724771\n",
- "Reloaded the best model.\n"
- ]
- },
- {
- "data": {
- "text/plain": [
- "{'best_eval': {'AccMetric': {'acc': 0.7534403669724771}},\n",
- " 'best_epoch': 4,\n",
- " 'best_step': 616,\n",
- " 'seconds': 34.74}"
- ]
- },
- "execution_count": 7,
- "metadata": {},
- "output_type": "execute_result"
- }
- ],
- "source": [
- "trainer = Trainer(train_data=train_data, dev_data=dev_data, model=model,\n",
- " loss=loss, device=device, metrics=AccMetric())\n",
- "trainer.train()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "``MetricBase`` 将会在输入的字典 ``pred_dict`` 和 ``target_dict`` 中进行检查.\n",
- "``pred_dict`` 是模型当中 ``forward()`` 函数或者 ``predict()`` 函数的返回值.\n",
- "``target_dict`` 是DataSet当中的ground truth, 判定ground truth的条件是field的 ``is_target`` 被设置为True.\n",
- "\n",
- "``MetricBase`` 会进行以下的类型检测:\n",
- "\n",
- "1. self.evaluate当中是否有 varargs, 这是不支持的.\n",
- "2. self.evaluate当中所需要的参数是否既不在 ``pred_dict`` 也不在 ``target_dict`` .\n",
- "3. self.evaluate当中所需要的参数是否既在 ``pred_dict`` 也在 ``target_dict`` .\n",
- "\n",
- "除此以外,在参数被传入self.evaluate以前,这个函数会检测 ``pred_dict`` 和 ``target_dict`` 当中没有被用到的参数\n",
- "如果kwargs是self.evaluate的参数,则不会检测\n",
- "\n",
- "self.evaluate将计算一个批次(batch)的评价指标,并累计。 没有返回值\n",
- "self.get_metric将统计当前的评价指标并返回评价结果, 返回值需要是一个dict, key是指标名称,value是指标的值\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": []
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python Now",
- "language": "python",
- "name": "now"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.8.0"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
- }
|