File size: 43,413 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 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 |
{
"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> </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",
" \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> </div>\n",
"\n",
"<a href=\"https://colab.research.google.com/github/open-mmlab/mmyolo/blob/dev/demo/15_minutes_object_detection.ipynb\"><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 object detection\n",
"\n",
"Object detection task refers to that given a picture, the network predicts all the categories of objects included in the picture and the corresponding boundary boxes\n",
"\n",
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220232979-fffa480b-9ae6-4601-8af6-4116265dc650.png\" alt=\"object detection\" width=\"800\"/>\n",
"</div>\n",
"\n",
"Take the small dataset of cat as an example, you can easily learn MMYOLO object detection in 15 minutes. The whole process consists of 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 take YOLOv5-s as an example. For the rest of the YOLO series algorithms, please see 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 Cat dataset is a single-category dataset consisting of 144 pictures (the original pictures are provided by @RangeKing, and cleaned by @PeterH0323), which contains the annotation information required for training. The sample image is shown below:\n",
"\n",
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/25873202/205423220-c4b8f2fd-22ba-4937-8e47-1b3f6a8facd8.png\" alt=\"cat 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 cat --save-dir ./data/cat --unzip --delete"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "covQskXXw2ul"
},
"source": [
"This dataset is automatically downloaded to the `./data/cat` dir with the following directory structure:\n",
"\n",
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220072078-48b88a08-6179-483e-b8d3-0549e1b465de.png\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"The cat dataset is located in the mmyolo project dir, and `data/cat/annotations` stores annotations in COCO format, and `data/cat/images` stores all images\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",
"- The default training epoch is 300. Change it to 40 epoch\n",
"- Given the small size of the dataset, we opted to use fixed backbone weights\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",
"Create a `yolov5_s-v61_fast_1xb12-40e_cat.py` config file in the `configs/yolov5` folder (we have provided this config for you to use directly) and copy the following into the config file.\n",
"\n",
"```python\n",
"# Inherit and overwrite part of the config based on this config\n",
"_base_ = 'yolov5_s-v61_syncbn_fast_8xb16-300e_coco.py'\n",
"\n",
"data_root = './data/cat/' # dataset root\n",
"class_name = ('cat', ) # dataset category name\n",
"num_classes = len(class_name) # dataset category number\n",
"# metainfo is a configuration that must be passed to the dataloader, otherwise it is invalid\n",
"# palette is a display color for category at visualization\n",
"# The palette length must be greater than or equal to the length of the classes\n",
"metainfo = dict(classes=class_name, palette=[(20, 220, 60)])\n",
"\n",
"# Adaptive anchor based on tools/analysis_tools/optimize_anchors.py\n",
"anchors = [\n",
" [(68, 69), (154, 91), (143, 162)], # P3/8\n",
" [(242, 160), (189, 287), (391, 207)], # P4/16\n",
" [(353, 337), (539, 341), (443, 432)] # P5/32\n",
"]\n",
"# Max training 40 epoch\n",
"max_epochs = 40\n",
"# bs = 12\n",
"train_batch_size_per_gpu = 12\n",
"# dataloader num workers\n",
"train_num_workers = 4\n",
"\n",
"# load COCO pre-trained weight\n",
"load_from = 'https://download.openmmlab.com/mmyolo/v0/yolov5/yolov5_s-v61_syncbn_fast_8xb16-300e_coco/yolov5_s-v61_syncbn_fast_8xb16-300e_coco_20220918_084700-86e02187.pth' # noqa\n",
"\n",
"model = dict(\n",
" # Fixed the weight of the entire backbone without training\n",
" backbone=dict(frozen_stages=4),\n",
" bbox_head=dict(\n",
" head_module=dict(num_classes=num_classes),\n",
" prior_generator=dict(base_sizes=anchors)\n",
" ))\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",
" # Dataset annotation file of json path\n",
" ann_file='annotations/trainval.json',\n",
" # Dataset prefix\n",
" data_prefix=dict(img='images/')))\n",
"\n",
"val_dataloader = dict(\n",
" dataset=dict(\n",
" metainfo=metainfo,\n",
" data_root=data_root,\n",
" ann_file='annotations/test.json',\n",
" data_prefix=dict(img='images/')))\n",
"\n",
"test_dataloader = val_dataloader\n",
"\n",
"_base_.optim_wrapper.optimizer.batch_size_per_gpu = train_batch_size_per_gpu\n",
"\n",
"val_evaluator = dict(ann_file=data_root + 'annotations/test.json')\n",
"test_evaluator = val_evaluator\n",
"\n",
"default_hooks = dict(\n",
" # Save weights every 10 epochs and a maximum of two weights can be saved.\n",
" # The best model is saved automatically during model evaluation\n",
" checkpoint=dict(interval=10, max_keep_ckpts=2, save_best='auto'),\n",
" # The warmup_mim_iter parameter is critical.\n",
" # The default value is 1000 which is not suitable for cat datasets.\n",
" param_scheduler=dict(max_epochs=max_epochs, warmup_mim_iter=10),\n",
" # The log printing interval is 5\n",
" logger=dict(type='LoggerHook', interval=5))\n",
"# The evaluation interval is 10\n",
"train_cfg = dict(max_epochs=max_epochs, val_interval=10)\n",
"```\n",
"\n",
"The above config is inherited from `yolov5_s-v61_syncbn_fast_8xb16-300e_coco.py`. According to the characteristics of cat dataset updated `data_root`, `metainfo`, `train_dataloader`, `val_dataloader`, `num_classes` and other config.\n",
"\n",
"## Training"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python tools/train.py configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "TQ0h6sv_rJxq"
},
"source": [
"Run the above training command, `work_dirs/yolov5_s-v61_fast_1xb12-40e_cat` folder will be automatically generated, the checkpoint file and the training config file will be saved in this folder. On a low-end 1660 GPU, the entire training process takes about eight minutes.\n",
"\n",
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220236361-bd113606-248e-4a0e-a484-c0dc9e355b5b.png\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"The performance on `test.json` is as follows:\n",
"\n",
"```text\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.631\n",
" Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.909\n",
" Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.747\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = -1.000\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000\n",
" Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.631\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.627\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.703\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.703\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = -1.000\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = -1.000\n",
" Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.703\n",
"```\n",
"\n",
"The above properties are printed via the COCO API, where -1 indicates that no object exists for the scale. According to the rules defined by COCO, the Cat dataset contains all large sized objects, and there are no small or medium-sized objects.\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",
"- The model and loaded state dict do not match exactly\n",
"\n",
"Neither of these warnings will have any impact on performance. The first 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. The second warning is because we are currently training in fine-tuning mode, we load the COCO pre-trained weights for 80 classes,\n",
"This will lead to the final Head module convolution channel number does not correspond, resulting in this part of the weight can not be loaded, which is also 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/yolov5_s-v61_fast_1xb12-40e_cat.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/yolov5_s-v61_fast_1xb12-40e_cat.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/yolov5_s-v61_fast_1xb12-40e_cat.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/yolov5_s-v61_fast_1xb12-40e_cat.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/yolov5_s-v61_fast_1xb12-40e_cat.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_s-v61_fast_1xb12-40e_cat/{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_s-v61_fast_1xb12-40e_cat"
]
},
{
"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/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --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_s-v61_fast_1xb12-40e_cat/{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/17425982/220251677-6c7e5c8f-9417-4803-97fc-a968d0172ab7.png\" 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 modify the `test_pipeline` of `configs/yolov5/yolov5_s-v61_syncbn_8xb16-300e_coco.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/cat/images/IMG_20221020_112705.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/cat/images/IMG_20221020_112705.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --target-layers backbone \\\n",
" --channel-reduction squeeze_mean"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220292217-b343a6f4-0c88-4fdb-9680-35d0ff8e5bdb.png\" 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. As the backbone of this training is not actually involved in training, it can be seen from the above figure that the big object cat is predicted on the small feature map, which is in line with the idea of hierarchical detection of object detection.\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/cat/images/IMG_20221020_112705.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.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/17425982/220293382-0a241415-e717-4688-a718-5f6d5c844785.png\" width=\"800\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"As can be seen from the above figure, because neck is involved in training, and we also reset anchor, the three output feature maps are forced to simulate the same scale object, resulting in the three output maps of neck are similar, which destroys the original pre-training distribution of backbone. At the same time, it can also be seen that 40 epochs are not enough to train the above dataset, and the feature maps do not perform well.\n",
"\n",
"**3. Grad-Based CAM visualization**\n",
"\n",
"Based on the above feature map visualization, we can analyze Grad CAM at the feature layer of bbox level.\n",
"\n",
"Install `grad-cam` package:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install \"grad-cam\""
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"(a) View Grad CAM of the minimum output feature map of the neck"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --target-layer neck.out_layers[2]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "9v-dMkePvHMg"
},
"source": [
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220298462-b0631f27-2366-4864-915a-a4ee21acd4b9.png\" width=\"800\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"(b) View Grad CAM of the medium output feature map of the neck"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "p9H9u0A-3KAD",
"outputId": "32ca5a56-052f-4930-f53c-41cc3a9dc619"
},
"outputs": [],
"source": [
"!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --target-layer neck.out_layers[1]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"(c) View Grad CAM of the maximum output feature map of the neck"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "MrKan1U43uUY",
"outputId": "690f8414-a76b-4fa6-e600-7cc874ce1914"
},
"outputs": [],
"source": [
"!python demo/boxam_vis_demo.py data/cat/images/IMG_20221020_112705.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --target-layer neck.out_layers[0]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/17425982/220297905-e23369db-d383-48f9-b15e-528a70ec7b23.png\" width=\"800\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"## EasyDeploy deployment\n",
"\n",
"Here we'll use MMYOLO's [EasyDeploy](../../../projects/easydeploy/) to demonstrate the transformation deployment and basic inference of model.\n",
"\n",
"First you need to follow EasyDeploy's [basic documentation](../../../projects/easydeploy/docs/model_convert.md) controls own equipment installed for each library.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install onnx\n",
"%pip install onnx-simplifier # Install if you want to use simplify\n",
"%pip install tensorrt # If you have GPU environment and need to output TensorRT model you need to continue execution"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Once installed, you can use the following command to transform and deploy the trained model on the cat dataset with one click. The current ONNX version is 1.13.0 and TensorRT version is 8.5.3.1, so keep the `--opset` value of 11. The remaining parameters need to be adjusted according to the config used. Here we export the CPU version of ONNX with the `--backend` set to 1."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 534
},
"id": "YsRFEecU5C0w",
"outputId": "c26011d4-2836-4715-cd6b-68836294db33"
},
"outputs": [],
"source": [
"!python projects/easydeploy/tools/export.py \\\n",
"\t configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
"\t work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
"\t --work-dir work_dirs/yolov5_s-v61_fast_1xb12-40e_cat \\\n",
" --img-size 640 640 \\\n",
" --batch 1 \\\n",
" --device cpu \\\n",
" --simplify \\\n",
"\t --opset 11 \\\n",
"\t --backend 1 \\\n",
"\t --pre-topk 1000 \\\n",
"\t --keep-topk 100 \\\n",
"\t --iou-threshold 0.65 \\\n",
"\t --score-threshold 0.25\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "q1EY415x3Idx"
},
"source": [
"On success, you will get the converted ONNX model under `work-dir`, which is named `end2end.onnx` by default.\n",
"\n",
"Let's use `end2end.onnx` model to perform a basic image inference:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python projects/easydeploy/tools/image-demo.py \\\n",
" data/cat/images/IMG_20210728_205312.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.onnx \\\n",
" --device cpu"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "IrjiBa5YwDQM"
},
"source": [
"After successful inference, the result image will be generated in the `output` folder of the default MMYOLO root directory. If you want to see the result without saving it, you can add `--show` to the end of the above command. For convenience, the following is the generated result.\n",
"\n",
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/7219519/221061210-b91e0b5b-652d-4dfc-8451-86a9a36f7d04.png\" width=\"800\" alt=\"image\"/>\n",
"</div>\n",
"\n",
"Let's go on to convert the engine file for TensorRT, because TensorRT needs to be specific to the current environment and deployment version, so make sure to export the parameters, here we export the TensorRT8 file, the `--backend` is 2."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d8zxczqiBLoB"
},
"outputs": [],
"source": [
"!python projects/easydeploy/tools/export.py \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/epoch_40.pth \\\n",
" --work-dir work_dirs/yolov5_s-v61_fast_1xb12-40e_cat \\\n",
" --img-size 640 640 \\\n",
" --batch 1 \\\n",
" --device cuda:0 \\\n",
" --simplify \\\n",
" --opset 11 \\\n",
" --backend 2 \\\n",
" --pre-topk 1000 \\\n",
" --keep-topk 100 \\\n",
" --iou-threshold 0.65 \\\n",
" --score-threshold 0.25"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"The resulting `end2end.onnx` is the ONNX file for the TensorRT8 deployment, which we will use to complete the TensorRT engine transformation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"id": "QFh8rIsX_kVw",
"outputId": "c5bd6929-03a8-400e-be1e-581f32b23f61"
},
"outputs": [],
"source": [
"!python projects/easydeploy/tools/build_engine.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.onnx \\\n",
" --img-size 640 640 \\\n",
" --device cuda:0"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Successful execution will generate the `end2end.engine` file under `work-dir`:\n",
"\n",
"```shell\n",
"work_dirs/yolov5_s-v61_fast_1xb12-40e_cat\n",
"βββ 202302XX_XXXXXX\n",
"β βββ 202302XX_XXXXXX.log\n",
"β βββ vis_data\n",
"β βββ 202302XX_XXXXXX.json\n",
"β βββ config.py\n",
"β βββ scalars.json\n",
"βββ best_coco\n",
"β βββ bbox_mAP_epoch_40.pth\n",
"βββ end2end.engine\n",
"βββ end2end.onnx\n",
"βββ epoch_30.pth\n",
"βββ epoch_40.pth\n",
"βββ last_checkpoint\n",
"βββ yolov5_s-v61_fast_1xb12-40e_cat.py\n",
"```\n",
"\n",
"Let's continue use `image-demo.py` for image inference:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 1000
},
"id": "rOqXEi-jAI7Y",
"outputId": "2a21aaaa-d4ba-498a-f985-2a6a2b8d348f"
},
"outputs": [],
"source": [
"!python projects/easydeploy/tools/image-demo.py \\\n",
" data/cat/images/IMG_20210728_205312.jpg \\\n",
" configs/yolov5/yolov5_s-v61_fast_1xb12-40e_cat.py \\\n",
" work_dirs/yolov5_s-v61_fast_1xb12-40e_cat/end2end.engine \\\n",
" --device cuda:0"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "ocHGUUEA_TjI"
},
"source": [
"<div align=center>\n",
"<img src=\"https://user-images.githubusercontent.com/7219519/221061291-e7490bb6-5f0c-45ab-9fc4-caf2b62419d6.png\" width=\"800\" alt=\"image\"/>\n",
"</div>\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.\n"
]
}
],
"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
}
|