File size: 29,664 Bytes
186701e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "x7seefPduh36"
      },
      "source": [
        "<div align=\"center\">\n",
        "  <img width=\"600\" src=\"https://github.com/open-mmlab/mmyolo/raw/main/resources/mmyolo-logo.png\"/>\n",
        "  <div>&nbsp;</div>\n",
        "  <div align=\"center\">\n",
        "    <b><font size=\"5\">OpenMMLab website</font></b>\n",
        "    <sup>\n",
        "      <a href=\"https://openmmlab.com\">\n",
        "        <i><font size=\"4\">HOT</font></i>\n",
        "      </a>\n",
        "    </sup>\n",
        "    &nbsp;&nbsp;&nbsp;&nbsp;\n",
        "    <b><font size=\"5\">OpenMMLab platform</font></b>\n",
        "    <sup>\n",
        "      <a href=\"https://platform.openmmlab.com\">\n",
        "        <i><font size=\"4\">TRY IT OUT</font></i>\n",
        "      </a>\n",
        "    </sup>\n",
        "  </div>\n",
        "  <div>&nbsp;</div>\n",
        "\n",
        "<a href=\"https://colab.research.google.com/drive/1ogJ7MQ6DTeKc6mN2an9GvuCjkH3RREXk?usp=sharing\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "[![PyPI](https://img.shields.io/pypi/v/mmyolo)](https://pypi.org/project/mmyolo)\n",
        "[![docs](https://img.shields.io/badge/docs-latest-blue)](https://mmyolo.readthedocs.io/en/latest/)\n",
        "[![deploy](https://github.com/open-mmlab/mmyolo/workflows/deploy/badge.svg)](https://github.com/open-mmlab/mmyolo/actions)\n",
        "[![codecov](https://codecov.io/gh/open-mmlab/mmyolo/branch/main/graph/badge.svg)](https://codecov.io/gh/open-mmlab/mmyolo)\n",
        "[![license](https://img.shields.io/github/license/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/blob/main/LICENSE)\n",
        "[![open issues](https://isitmaintained.com/badge/open/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n",
        "[![issue resolution](https://isitmaintained.com/badge/resolution/open-mmlab/mmyolo.svg)](https://github.com/open-mmlab/mmyolo/issues)\n",
        "\n",
        "[📘Documentation](https://mmyolo.readthedocs.io/en/latest/) |\n",
        "[🛠️Installation](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html) |\n",
        "[👀Model Zoo](https://mmyolo.readthedocs.io/en/latest/model_zoo.html) |\n",
        "[🆕Update News](https://mmyolo.readthedocs.io/en/latest/notes/changelog.html) |\n",
        "[🤔Reporting Issues](https://github.com/open-mmlab/mmyolo/issues/new/choose)\n",
        "\n",
        "</div>\n",
        "\n",
        "<div align=\"center\">\n",
        "  <a href=\"https://openmmlab.medium.com/\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219255827-67c1a27f-f8c5-46a9-811d-5e57448c61d1.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://discord.com/channels/1037617289144569886/1046608014234370059\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218347213-c080267f-cbb6-443e-8532-8e1ed9a58ea9.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://twitter.com/OpenMMLab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218346637-d30c8a0f-3eba-4699-8131-512fb06d46db.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://www.youtube.com/openmmlab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/218346691-ceb2116a-465a-40af-8424-9f30d2348ca9.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://space.bilibili.com/1293512903\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219026751-d7d14cce-a7c9-4e82-9942-8375fca65b99.png\" width=\"3%\" alt=\"\" /></a>\n",
        "  <img src=\"https://user-images.githubusercontent.com/25839884/218346358-56cc8e2f-a2b8-487f-9088-32480cceabcf.png\" width=\"3%\" alt=\"\" />\n",
        "  <a href=\"https://www.zhihu.com/people/openmmlab\" style=\"text-decoration:none;\">\n",
        "    <img src=\"https://user-images.githubusercontent.com/25839884/219026120-ba71e48b-6e94-4bd4-b4e9-b7d175b5e362.png\" width=\"3%\" alt=\"\" /></a>\n",
        "</div>"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "V6W8P5XEJGoc"
      },
      "source": [
        "# 15 minutes to get started with MMYOLO instance segmentation\n",
        "\n",
        "Instance segmentation is a task in computer vision that aims to segment each object in an image and assign each object a unique identifier.\n",
        "\n",
        "Unlike semantic segmentation, instance segmentation not only segments out different categories in an image, but also separates different instances of the same category.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://github.com/open-mmlab/mmyolo/assets/87774050/6fd6316f-d78d-48a5-a413-86e7a74583fd\" alt=\"Instance Segmentation\" width=\"100%\"/>\n",
        "</div>\n",
        "\n",
        "Taking the downloadable balloon dataset as an example, I will guide you through a 15-minute easy introduction to MMYOLO instance segmentation. The entire process includes the following steps:\n",
        "\n",
        "- [Installation](#installation)\n",
        "- [Dataset](#dataset)\n",
        "- [Config](#config)\n",
        "- [Training](#training)\n",
        "- [Testing](#testing)\n",
        "- [EasyDeploy](#easydeploy-deployment)\n",
        "\n",
        "In this tutorial, we will use YOLOv5-s as an example. For the demo configuration of the balloon dataset with other YOLO series algorithms, please refer to the corresponding algorithm configuration folder."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Ae5SqsA7wYGQ"
      },
      "source": [
        "## Installation\n",
        "\n",
        "Assuming you've already installed Conda in advance, then install PyTorch using the following commands."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XVLRaEIzwW-6",
        "outputId": "901b5db6-b1d7-4830-e746-485ee76d6648"
      },
      "outputs": [],
      "source": [
        "# -----------------------------------------------------------------------------------------\n",
        "# If you are using colab, you can skip this cell for PyTorch is pre-installed on the colab.\n",
        "# -----------------------------------------------------------------------------------------\n",
        "!python -V\n",
        "# Check nvcc version\n",
        "!nvcc -V\n",
        "# Check GCC version\n",
        "!gcc --version\n",
        "# Create a new Conda environment\n",
        "%conda create -n mmyolo python=3.8 -y\n",
        "%conda activate mmyolo\n",
        "# If you have GPU\n",
        "%conda install pytorch torchvision -c pytorch\n",
        "# If you only have CPU\n",
        "# %conda install pytorch torchvision cpuonly -c pytorch"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# Check PyTorch version\n",
        "import torch\n",
        "print(torch.__version__)\n",
        "print(torch.cuda.is_available())"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Install MMYOLO and dependency libraries using the following commands.\n",
        "For details about how to configure the environment, see [Installation and verification](https://mmyolo.readthedocs.io/en/latest/get_started/installation.html).\n",
        "```{note}\n",
        "Note: Since this repo uses OpenMMLab 2.0, it is better to create a new conda virtual environment to prevent conflicts with the repo installed in OpenMMLab 1.0.\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-qATUuntwmfD",
        "outputId": "24be577b-efce-46f2-8b2f-a65d02824467"
      },
      "outputs": [],
      "source": [
        "!git clone https://github.com/open-mmlab/mmyolo.git\n",
        "%cd mmyolo\n",
        "%pip install -U openmim\n",
        "!mim install -r requirements/mminstall.txt\n",
        "# Install albumentations\n",
        "!mim install -r requirements/albu.txt\n",
        "# Install MMYOLO\n",
        "!mim install -v -e .\n",
        "# \"-v\" means verbose, or more output\n",
        "# \"-e\" means installing a project in editable mode,\n",
        "# thus any local modifications made to the code will take effect without reinstallation."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Dataset\n",
        "\n",
        "The Balloon dataset is a single-class dataset that consists of 74 images and includes annotated information required for training. Here is an example image from the dataset:\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/87774050/236993643-f581b087-9231-48a5-810b-97a5f31abe63.png\" alt=\"balloon dataset\"/>\n",
        "</div>\n",
        "\n",
        "You can download and use it directly by the following command:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "gMQXwWuIw3ef",
        "outputId": "c8efeac7-5b0c-4342-b5af-d3e790e358c3"
      },
      "outputs": [],
      "source": [
        "!python tools/misc/download_dataset.py --dataset-name balloon --save-dir ./data/balloon --unzip --delete\n",
        "!python ./tools/dataset_converters/balloon2coco.py"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "covQskXXw2ul"
      },
      "source": [
        "The data for the MMYOLO project is located in the MMYOLO project directory. The `train.json` and `val.json` files store the annotations in COCO format, while the `data/balloon/train` and `data/balloon/val` directories contain all the images for the dataset.\n",
        "\n",
        "## Config\n",
        "\n",
        "Taking YOLOv5 algorithm as an example, considering the limited GPU memory of users, we need to modify some default training parameters to make them run smoothly. The key parameters to be modified are as follows:\n",
        "\n",
        "- YOLOv5 is an Anchor-Based algorithm, and different datasets need to calculate suitable anchors adaptively.\n",
        "- The default config uses 8 GPUs with a batch size of 16 per GPU. Now change it to a single GPU with a batch size of 12.\n",
        "- In principle, the learning rate should be linearly scaled accordingly when the batch size is changed, but actual measurements have found that this is not necessary.\n",
        "\n",
        "To perform the specific operation, create a new configuration file named `yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py` in the `configs/yolov5/ins_seg` folder. For convenience, we have already provided this configuration file. Copy the following contents into the configuration file.\n",
        "\n",
        "```python\n",
        "_base_ = './yolov5_ins_s-v61_syncbn_fast_8xb16-300e_coco_instance.py'  # noqa\n",
        "\n",
        "data_root = 'data/balloon/' # dataset root\n",
        "# Training set annotation file of json path\n",
        "train_ann_file = 'train.json'\n",
        "train_data_prefix = 'train/'  # Dataset prefix\n",
        "# Validation set annotation file of json path\n",
        "val_ann_file = 'val.json'\n",
        "val_data_prefix = 'val/'\n",
        "metainfo = {\n",
        "    'classes': ('balloon', ), # dataset category name\n",
        "    'palette': [\n",
        "        (220, 20, 60),\n",
        "    ]\n",
        "}\n",
        "num_classes = 1\n",
        "# Set batch size to 4\n",
        "train_batch_size_per_gpu = 4\n",
        "# dataloader num workers\n",
        "train_num_workers = 2\n",
        "log_interval = 1\n",
        "#####################\n",
        "train_dataloader = dict(\n",
        "    batch_size=train_batch_size_per_gpu,\n",
        "    num_workers=train_num_workers,\n",
        "    dataset=dict(\n",
        "        data_root=data_root,\n",
        "        metainfo=metainfo,\n",
        "        data_prefix=dict(img=train_data_prefix),\n",
        "        ann_file=train_ann_file))\n",
        "val_dataloader = dict(\n",
        "    dataset=dict(\n",
        "        data_root=data_root,\n",
        "        metainfo=metainfo,\n",
        "        data_prefix=dict(img=val_data_prefix),\n",
        "        ann_file=val_ann_file))\n",
        "test_dataloader = val_dataloader\n",
        "val_evaluator = dict(ann_file=data_root + val_ann_file)\n",
        "test_evaluator = val_evaluator\n",
        "default_hooks = dict(logger=dict(interval=log_interval))\n",
        "#####################\n",
        "\n",
        "model = dict(bbox_head=dict(head_module=dict(num_classes=num_classes)))\n",
        "```\n",
        "\n",
        "The above configuration inherits from `yolov5_ins_s-v61_syncbn_fast_8xb16-300e_coco_instance.py` and updates configurations such as `data_root`, `metainfo`, `train_dataloader`, `val_dataloader`, `num_classes`, etc., based on the characteristics of the balloon dataset.\n",
        "\n",
        "## Training"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "TQ0h6sv_rJxq"
      },
      "source": [
        "After running the training command mentioned above, the folder `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance` will be automatically generated. The weight files and the training configuration file for this session will be saved in this folder. On a lower-end GPU like the GTX 1660, the entire training process will take approximately 30 minutes.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/87774050/236995027-00a16a9e-2a2d-44cc-be8a-e2c8a36ff77f.png\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "The performance on `val.json` is as follows:\n",
        "\n",
        "```text\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.330\n",
        " Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.509\n",
        " Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.317\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.103\n",
        " Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.417\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.150\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.396\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.454\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.000\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.317\n",
        " Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.525\n",
        "```\n",
        "\n",
        "The above performance is obtained by printing using the COCO API, where -1 indicates the absence of objects of that scale.\n",
        "\n",
        "### Some Notes\n",
        "\n",
        "Two key warnings are printed during training:\n",
        "\n",
        "- You are using `YOLOv5Head` with num_classes == 1. The loss_cls will be 0. This is a normal phenomenon.\n",
        "\n",
        "The warning is because the `num_classes` currently trained is 1, the loss of the classification branch is always 0 according to the community of the YOLOv5 algorithm, which is a normal phenomenon.\n",
        "\n",
        "### Training is resumed after the interruption\n",
        "\n",
        "If you stop training, you can add `--resume` to the end of the training command and the program will automatically resume training with the latest weights file from `work_dirs`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py --resume"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "3sJxvQoUrMhX"
      },
      "source": [
        "### Save GPU memory strategy\n",
        "\n",
        "The above config requires about 3G RAM, so if you don't have enough, consider turning on mixed-precision training"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py --amp"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "jVJdyHTxrQ9a"
      },
      "source": [
        "### Training visualization\n",
        "\n",
        "MMYOLO currently supports local, TensorBoard, WandB and other back-end visualization. The default is to use local visualization, and you can switch to WandB and other real-time visualization of various indicators in the training process.\n",
        "\n",
        "#### 1 WandB\n",
        "\n",
        "WandB visualization need registered in website, and in the https://wandb.ai/settings for wandb API Keys.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://cdn.vansin.top/img/20220913212628.png\" alt=\"image\"/>\n",
        "</div>"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "%pip install wandb\n",
        "# After running wandb login, enter the API Keys obtained above, and the login is successful.\n",
        "!wandb login"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Yu0_4YYRrbyY"
      },
      "source": [
        "Add the wandb config at the end of config file we just created: `configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`.\n",
        "\n",
        "```python\n",
        "visualizer = dict(vis_backends = [dict(type='LocalVisBackend'), dict(type='WandbVisBackend')])\n",
        "```\n",
        "\n",
        "Running the training command and you will see the loss, learning rate, and coco/bbox_mAP visualizations in the link."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python tools/train.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "f_DyzfDIzwMa"
      },
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/222131114-30a79285-56bc-427d-a38d-8d6a6982ad60.png\" alt=\"image\"/>\n",
        "</div>\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/17425982/222132585-4b4962f1-211b-46f7-86b3-7534fc52a1b4.png\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "#### 2 Tensorboard\n",
        "\n",
        "Install Tensorboard using the following command."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "gHkGlii3n29Q"
      },
      "outputs": [],
      "source": [
        "%pip install tensorboard"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "bE-nx9TY1P-M"
      },
      "source": [
        "Add the `tensorboard` config at the end of config file we just created: `configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`.\n",
        "\n",
        "```python\n",
        "visualizer = dict(vis_backends=[dict(type='LocalVisBackend'),dict(type='TensorboardVisBackend')])\n",
        "```\n",
        "\n",
        "After re-running the training command, Tensorboard file will be generated in the visualization folder `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/{timestamp}/vis_data`.\n",
        "We can use Tensorboard to view the loss, learning rate, and coco/bbox_mAP visualizations from a web link by running the following command:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "g8fZgokho5CE"
      },
      "outputs": [],
      "source": [
        "!tensorboard --logdir=work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "GUZ7MPoaro-o"
      },
      "source": [
        "## Testing"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VYmxtE0GunTB",
        "outputId": "f440807c-1931-4810-b76d-617f73fde227"
      },
      "outputs": [],
      "source": [
        "!python tools/test.py configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance best_coco_bbox_mAP_epoch_300.pth --show-dir show_results"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "_cFocUqN0BCb"
      },
      "source": [
        "Run the above test command, you can not only get the AP performance printed in the **Training** section, You can also automatically save the result images to the `work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/{timestamp}/show_results` folder. Below is one of the result images, the left image is the actual annotation, and the right image is the inference result of the model.\n",
        "\n",
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/87774050/236996421-46cfd38c-0827-4251-8216-408dfa9e03dd.jpg\" alt=\"result_img\"/>\n",
        "</div>\n",
        "\n",
        "You can also visualize model inference results in a browser window if you use `WandbVisBackend` or `TensorboardVisBackend`.\n",
        "\n",
        "## Feature map visualization\n",
        "\n",
        "MMYOLO provides visualization scripts for feature map to analyze the current model training. Please refer to [Feature Map Visualization](../recommended_topics/visualization.md)\n",
        "\n",
        "Due to the bias of direct visualization of `test_pipeline`, we need to modify the `test_pipeline` of `configs/yolov5/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py`\n",
        "\n",
        "```python\n",
        "test_pipeline = [\n",
        "    dict(\n",
        "        type='LoadImageFromFile',\n",
        "        file_client_args=_base_.file_client_args),\n",
        "    dict(type='YOLOv5KeepRatioResize', scale=img_scale),\n",
        "    dict(\n",
        "        type='LetterResize',\n",
        "        scale=img_scale,\n",
        "        allow_scale_up=False,\n",
        "        pad_val=dict(img=114)),\n",
        "    dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n",
        "    dict(\n",
        "        type='mmdet.PackDetInputs',\n",
        "        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n",
        "                   'scale_factor', 'pad_param'))\n",
        "]\n",
        "```\n",
        "\n",
        "to the following config:\n",
        "\n",
        "```python\n",
        "test_pipeline = [\n",
        "    dict(\n",
        "        type='LoadImageFromFile',\n",
        "        file_client_args=_base_.file_client_args),\n",
        "    dict(type='mmdet.Resize', scale=img_scale, keep_ratio=False), # modify the LetterResize to mmdet.Resize\n",
        "    dict(type='LoadAnnotations', with_bbox=True, _scope_='mmdet'),\n",
        "    dict(\n",
        "        type='mmdet.PackDetInputs',\n",
        "        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n",
        "                   'scale_factor'))\n",
        "]\n",
        "```\n",
        "\n",
        "Let's choose the `data/balloon/train/3927754171_9011487133_b.jpg` image as an example to visualize the output feature maps of YOLOv5 backbone and neck layers.\n",
        "\n",
        "**1. Visualize the three channels of YOLOv5 backbone**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python demo/featmap_vis_demo.py data/balloon/train/3927754171_9011487133_b.jpg onfigs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/best_coco_bbox_mAP_epoch_300.pth --target-layers backbone --channel-reduction squeeze_mean"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/87774050/236997582-233e292f-5e96-4e44-9e92-9e0787f302fc.jpg\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "The result will be saved to the output folder in current path. Three output feature maps plotted in the above figure correspond to small, medium and large output feature maps.\n",
        "\n",
        "**2. Visualize the three channels of YOLOv5 neck**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python demo/featmap_vis_demo.py data/balloon/train/3927754171_9011487133_b.jpg \\\n",
        "                                 configs/yolov5/ins_seg/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance.py \\\n",
        "                                 work_dirs/yolov5_ins_s-v61_syncbn_fast_8xb16-300e_balloon_instance/best_coco_bbox_mAP_epoch_300.pth \\\n",
        "                                 --target-layers neck \\\n",
        "                                 --channel-reduction squeeze_mean"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "<div align=center>\n",
        "<img src=\"https://user-images.githubusercontent.com/87774050/236997860-719d2e18-7767-4129-a072-b21c97a5502a.jpg\" width=\"800\" alt=\"image\"/>\n",
        "</div>\n",
        "\n",
        "**3. Grad-Based CAM visualization**\n",
        "TODO"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## EasyDeploy deployment\n",
        "TODO\n",
        "\n",
        "This completes the transformation deployment of the trained model and checks the inference results. This is the end of the tutorial.\n",
        "\n",
        "If you encounter problems during training or testing, please check the [common troubleshooting steps](https://mmyolo.readthedocs.io/en/dev/recommended_topics/troubleshooting_steps.html) first and feel free to open an [issue](https://github.com/open-mmlab/mmyolo/issues/new/choose) if you still can't solve it."
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}