MMDetectionV2 + Colab
MMDetectionV2 + Colab 超詳細教程及踩坑實錄
文章目錄
-
- 前言
- 一、環境配置
- 二、準備自己的數據集
- Aug.14更新
- 三:修改config文件
- 3.1 文件結構
- 3.2 (本地)修改config文件
- 3.2.1 (本地)構造自己模型的權重文件
- 3.2.2 (本地)修改配置文件
- 3.3 在colab上修改config
- 3.5 在線訓練
- 3.6 在線可視化模型效果
- 3.7 在線inference
- 4. 延伸思考
- 5. 總結
前言
為了參加訊飛的X光目標檢測競賽,我們組研究了目前通用的幾種框架。包括Detectron2, Maskrcnn Benchmark和mmdetectionV2,最后決定采用MMDetectonV2,因為他有以下的幾個特性:
- 相比較來說非常豐富的模型庫可供選擇。基礎模型包括:
- Faster rcnn
- Mask rcnn
- Rpn rcnn
- Cascade mask rcnn
- Cascade rcnn
- Retinanet (據說精度差不多的情況下,inference速度最快,可以以后再多了解一下。
- 較多參考資料
- 安全的License,Apache License 2.0
先說明下,為什么我要這么執著的使用Colab:
However, 為了獲得以上的好處,我嘗試在mmdetection官網提供的tutorial 中更改,結果一言難盡。同時,目前絕大多數的mmdetection的筆記都是基于1.x版本,而且幾乎沒有在Colab環境的配置教程。基本所有能踩的坑我全部踩了個遍,為了紀念一下也為了給其他的目標檢測學習者提供一下參考,就有了這篇筆記。
在主體上我將采用colab tutorial的框架來介紹,但是仍然強烈建議在本地安裝配置好mmdetectionV2,能省下大把力氣。
一、環境配置
# Check nvcc version !nvcc -V # Check GCC version !gcc --version編寫時間:2020.8.11,colab預設為pytorch1.6.0 Cuda 10.1 gcc 7.5.0
# install dependencies: (use cu101 because colab has CUDA 10.1) # 目前mmdetection只支持pytorch1.5.1及以下版本,使用1.6版本會報各種錯。 !pip install -U torch==1.5.1+cu101 torchvision==0.6.1+cu101 -f https://download.pytorch.org/whl/torch_stable.html # !pip install -U torch==1.6+cu101 torchvision==0.7.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html# install mmcv-full thus we could use CUDA operators,此步需要花費大量時間,be patient !pip install mmcv-full # 在2020二月份pycocotools api有更新,而colab沒有配置最新的包,需要在這里重新安裝,看情況需不需要重啟runtime # install albumentations !pip install -U git+https://github.com/albu/albumentations --no-cache-dir !pip install "git+https://github.com/open-mmlab/cocoapi.git#subdirectory=pycocotools"# Install mmdetection !rm -rf mmdetection !git clone https://github.com/open-mmlab/mmdetection.git %cd mmdetection!pip install -e .# install Pillow 7.0.0 back in order to avoid bug in colab !pip install Pillow==7.0.0 # Check Pytorch installation import torch, torchvisionprint(torch.__version__, torch.cuda.is_available())# Check MMDetection installation import mmdetprint(mmdet.__version__)# Check mmcv installation from mmcv.ops import get_compiling_cuda_version, get_compiler_versionprint(get_compiling_cuda_version()) print(get_compiler_version())Output:
1.5.1+cu101
True 2.3.0
10.1
GCC 7.5
掛載在自己的drive上:
from google.colab import drivedrive.mount('/content/drive')在colab上,使用%cd或os.chdir(’…’)來切換工作目錄
import os os.chdir('../content/drive/My Drive/mmdetection') !pwd !lsoutput:
/content/drive/My Drive/mmdetection/mmdetection
configs docs mmdet.egg-info requirements setup.cfg tools
demo LICENSE pytest.ini requirements.txt setup.py
docker mmdet README.md resources tests
二、準備自己的數據集
這是非常重要的一步,請務必按照以下的Tree準備自己的數據集,能給自己省下大量的麻煩。
mmdetection ├── mmdet ├── tools ├── configs ├── data │ ├── coco │ │ ├── annotations │ │ ├── train2017 │ │ ├── val2017 │ │ ├── test2017 │ ├── cityscapes │ │ ├── annotations │ │ ├── leftImg8bit │ │ │ ├── train │ │ │ ├── val │ │ ├── gtFine │ │ │ ├── train │ │ │ ├── val │ ├── VOCdevkit │ │ ├── VOC2007 │ │ ├── VOC2012這次任務中,提供給我們的是voc格式的數據。第一步需要做轉化,voc2coco.ipynb.
具體操作在這里不詳細展開,我將來會詳細寫一篇各數據集轉化到VOC,COCO數據集格式的文章。
Aug.14更新
本地做了mixup strategy數據增廣,具體實現見后續博客。
每次做完本地的數據增廣后,需要轉化成COCO再重新上傳。因為COCO的格式需要所有注釋放在同一個json文件中,所以需要重新生成。
三:修改config文件
這里是我花了最多時間的地方,在tutorial中,官方是載入了一個config和它對應的模型,之后在colab即ipython 中用命令一行一行修改,這種方法在你非常明確MMDetectionV2的config結構和訓練方式的情況下,是有一定靈活性的。但是如果不了解config的搭建方法,這會讓你非常懵逼,多達一百多行的config命令實在非常難以輕松上手。這里我會介紹兩種方法,一種是在本地修改好config文件上傳,同時會介紹如何在colab cells中用命令修改。
3.1 文件結構
. ├── coco_exps ├── configs #configs主要修改的部分在這里,訓練config也是從這里繼承的 │ ├── albu_example │ ├── atss │ ├── _base_ #最根本的繼承 │ │ ├── datasets #存在著不同數據集的訓練方法,包含train_pipeline(augmentation), test_pipeline(TTA), data(batch_size, data root)等信息 │ │ ├── models #保存著基礎模型,需要在這里修改num_classes來適配自己的任務 │ │ └── schedules #保存著lr_schedule:1x, 2x, 20e,每x意味著12個epochs │ ├── carafe │ ├── cascade_rcnn │ ├── cityscapes │ ├── cornernet │ ├── dcn │ ├── deepfashion │ ├── detectors │ ├── double_heads │ ├── dynamic_rcnn │ ├── empirical_attention │ ├── faster_rcnn │ ├── fast_rcnn │ ├── fcos │ ├── foveabox │ ├── fp16 │ ├── free_anchor │ ├── fsaf │ ├── gcnet │ ├── gfl │ ├── ghm │ ├── gn │ ├── gn+ws │ ├── grid_rcnn │ ├── groie │ ├── guided_anchoring │ ├── hrnet │ ├── htc │ ├── instaboost │ ├── legacy_1.x │ ├── libra_rcnn │ ├── lvis │ ├── mask_rcnn │ ├── ms_rcnn │ ├── nas_fcos │ ├── nas_fpn │ ├── pafpn │ ├── pascal_voc │ ├── pisa │ ├── point_rend │ ├── regnet │ ├── reppoints │ ├── res2net │ ├── retinanet │ ├── rpn │ ├── scratch │ ├── ssd │ └── wider_face ├── data │ └── coco #把整理好的coco數據集放在這里 │ ├── annotations │ ├── test2017 │ ├── train2017 │ └── val2017 ├── mmdet #這里存放著mmdet的一些內部構件 │ ├── datasets #需要在這里的coco.py更改CLASSES,相當于Detectron2注冊數據集 │ │ ├── pipelines │ │ │ └── __pycache__ │ │ ├── __pycache__ │ │ └── samplers │ │ └── __pycache__ │ ├── core │ │ ├── evaluation #在這里修改evaluation相關的config。如在coco_classes中修改return的classes_names3.2 (本地)修改config文件
這里非常建議在本地修改config文件再上傳到drive上,或者在colab提供的文件目錄中修改。如圖所示:
因為colab使用的ipython shell,每個參數的修改都需要使用cfg的api去修改,很容易漏項或lose track,而且mmdetection V2有一個非常精密的inherit config系統,不用結構化的IDE修改實在有點可惜。最后一點,在后期inference testset的時候,必須從.py文件中讀取test_config,為什么不一勞永逸呢?
3.2.1 (本地)構造自己模型的權重文件
這里有爭議,我在線訓練并不需要修改權重,使用的預訓練.pth模型在num_classes不匹配時會提示,然后自動適配cascade_rcnn_r50_1x.py中的num_classes。
不過修改后肯定不會錯。
其中num_class為你要訓練數據的類別數?(不用加1)?V2已經修改了,num_classes不再包含背景。
3.2.2 (本地)修改配置文件
在這里修改類別。
在train pipeline修改Data Augmentation在train
其中,batch_size和路徑等頻繁修改的參數在colab中可以快速修改:
# 舉例 cfg.samples_per_gpu = 4 cfg.data.train.ann_file = '...' cfg.data.train.img_prefix = '...' cfg.data.train.pipeline = train_pipeline我們選用的是dcn/cascade_rcnn_r101_20e.py模型進行訓,mmdetectionV2的繼承比較復雜,但是可維護性較好。一路到底,最根本的繼承還是base model中的cascade_rcnn_r50_fpn.py,主要的改動也是在這里進行。
這里比較簡單,我是為了要用Tensorboard查看訓練,所以在這里解掉注釋。
可以從官網下載預訓練模型,放在checkpoint/…文件夾中,在這里的load_from中寫入路徑就可以加載權重訓練了。
這里,load_from和resume_from都可以在colab上在線設置
cfg.load_from = ’...' cfg.resume_from = '...'這里是調整學習率的schedule的位置,可以設置warmup schedule和衰減策略。
1x, 2x分別對應12epochs和24epochs,20e對應20epochs,這里注意配置都是默認8塊gpu的訓練,如果用一塊gpu訓練,需要在lr/8
這里把coco_classes改成自己對應的class名稱,不然在evaluation的時候返回的名稱不對應。
總結一下,需要在本地修改的參數有(以使用dcn/cascade_rcnn_r101_20e.py為例):
1. mmdet/datasets/coco.py 2. configs/\_base_/default_runtime.py 3. configs/\_base_/datasets/coco_detection.py 4. configs/\_base_/models/cascade_rcnn_r50_20e.py 5. mmdet/core/evaluation/class_names.py當把這些修改好的文件上傳后,有時需要等待1分鐘左右讓colab與drive同步。
3.3 在colab上修改config
如果有在default_runtime中解除注釋tensorboard,鍵入下面的命令可以開啟實時更新的tensorboard可視化模塊。
3.5 在線訓練
如果以上的configs都做了正確的修改,直接運行下面的代碼就可以開始訓練了。
import mmcv import matplotlib.pyplot as plt import copy import os.path as ospfrom mmdet.datasets import build_dataset from mmdet.models import build_detector from mmdet.apis import train_detector# Build dataset datasets = [build_dataset(cfg.data.train)]# Build the detector model = build_detector(cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg) # Add an attribute for visualization convenience model.CLASSES = datasets[0].CLASSES# Create work_dir mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir)) print(model) train_detector(model, datasets, cfg, distributed=False, validate=True)這里的validate其實很玄學,有些時候運行完第一個epoch后的validate過程會中斷報錯。以下是我碰到的報錯和解決辦法:
Error: List range out of index.一般報這個錯,就要求你檢查num_classes到底有沒有修改正確。一定要在選用的模型的base model中修改所有的num_classes,并且注意MMDV2開始不需要num_classes+1(背景類)了。
ValueError: Expected x_max for bbox(0.94, 0.47, 1.003, 0.637, 0) to be in range[0,1], got 1.003.這個錯誤是Albumentation報的錯,需要檢查的是configs/_base_/coco_detection.py中的數據增廣albu部分是否正確,我的這個任務雖然是COCO格式的數據集但是不知道為什么需要在這里用pascal_voc格式的轉化。從Coco改回pascal_voc就不報錯了。
dict(type='Albu',transforms=albu_train_transforms,bbox_params=dicttype='BboxParams',format='pascal_voc',.......}另外還有一個可能是在其他數據集轉化到CoCo格式數據集的過程中代碼出錯,w,h需要xmax-xmin-1來轉化,仔細檢查一下。
OSError: Can't read data (file read failed: time = Mon May 20 00:34:07 2019 , filename = '/content/drive/My Drive/train/trainX_file1', file descriptor = 83, errno = 5, error message = 'Input/output error', buf = 0xc71d3864, total read size = 42145, bytes this sub-read = 42145, bytes actually read = 18446744073709551615, offset = 119840768)這個是colab的bug,一般這個情況下先檢查是不是指向的文件corrupt了,如果不是的話,可以試著重啟runtime。如果還是不能load,可以用重新force remount,一般就會解決了。
Cuda out of memory經典爆顯存錯誤。需要注意的是中途停止訓練后需要重啟runtime才可以重置顯存的占用量。所以碰到很多奇怪的錯誤第一件事可以嘗試重新runtime。
...."Acyclic'追溯可以看到,lr_schedule是一個pop的函數讀取的,也就是說讀取一次就沒了。所以每次終止訓練后,需要從config重新導入一次。
3.6 在線可視化模型效果
在模型訓練完之后,除了看tensorboard或者log的可視化結果,也可以自己選出幾個圖片看看效果。
from mmdet.apis import init_detector, inference_detector, show_result_pyplot import mmcv import random# Use your modified config file config_file = './configs/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_20e_coco.py' # Use your trained model checkpoint_file = './coco_exps_v4/latest.pth' # build the model from a config file and a checkpoint file model = init_detector(config_file, checkpoint_file, device='cuda:0') # get random test image and visualize it with model images = os.listdir('data/coco/test2017') rand_num = random.randint(0, len(images)) image = 'data/coco/test2017/'+images[rand_num] result = inference_detector(model, image)# show the results show_result_pyplot(model, image, result)可以看到20個epoch的效果還可以,檢出率和準確率都還可以接受。
3.7 在線inference
時間原因我們沒有做出一個在線inference的腳本。采取的方案是下載下來到本地,在本地進行inference。代碼如下
from argparse import ArgumentParserfrom mmdet.apis import inference_detector, init_detector, show_result_pyplotfrom glob import glob import os from tqdm import tqdmdef get_single_out(result,score_thr):tmp=[i.tolist() for i in result]res=[i.tolist() for i in result]# print(res)for cls_idx,item in enumerate(tmp):if(len(item)!=0):res[cls_idx]=[i for i in item if i[4]>score_thr]# print(res)return resdef main():parser = ArgumentParser()parser.add_argument('--imgdir',default='./data/coco/test2017', help='Image file')parser.add_argument('--config',default='./configs/dcn/cascade_rcnn_r101_fpn_dconv_c3-c5_20e_coco.py', help='Config file')parser.add_argument('--checkpoint',default='coco_exps_v4/epoch_7.pth', help='Checkpoint file')parser.add_argument('--device', default='cuda:0', help='Device used for inference')parser.add_argument('--score-thr', type=float, default=0.01, help='bbox score threshold')args = parser.parse_args()imgdir=args.imgdirimgs=glob(os.path.join(imgdir,"*.jpg"))imgs.sort()out=[]# build the model from a config file and a checkpoint filemodel = init_detector(args.config, args.checkpoint, device=args.device)for imgpath in tqdm(imgs):print(imgpath)# # test a single imageresult = inference_detector(model, imgpath)single_out=get_single_out(result,args.score_thr)out.append(single_out)# # show the results# show_result_pyplot(model, imgpath, result, score_thr=args.score_thr)#將結果寫入到文件中f=open('coco_exps_v4/output_8_softnms.json','w')f.write(str(out))f.close()if __name__ == '__main__':main()最后的結果是本次比賽要求的格式,讀者可以根據需要修改成適合自己的任務。
4. 延伸思考
基礎的訓練任務到這里就告一段落了,但是對于一個項目或者一個比賽來說,只掌握基礎的訓練技巧是遠遠不夠的。比如我簡短涉及到的soft_nms,多尺度訓練,TTA,這些tricks可以一定程度上提高成績,但我認為相比較聚焦于tricks,一個highlevel的視角更重要。以下是我認為完成一個任務需要具備的幾個條件:
1. 對于數據的深入了解。包括但不限于:w、h的分布,分辨率的分布,目標物體的w/h比(用來確定anchor shape) 2. 整體的思路要清晰:選用不同的baseline model測試,加tricks,怎么對數據集做處理,以及實驗記錄。 3. 有時候算力確實是決定一個隊伍能走多遠的瓶頸。5. 總結
作為一個只了解目標檢測原理的小白,經過幾十個小時的摸索,我能夠掌握mmdetection+colab的基礎操作和相關error的debug,這個過程還是比較有成就感的。中間參考了許多CSDN和知乎的大佬的博客,讓我受益良多,也讓我覺得有必要整理一下自己的踩坑實錄,這篇文章權當做拋磚引玉,給其他大佬們一些啟發。中間如果有不正確和不efficient的部分歡迎探討。
我今后會發表更多的與目標檢測相關的工具的詳細教程以及論文筆記,有興趣的朋友歡迎關注。
都看到這里了,點個贊唄。
本文鏈接http://smartadmin.com.cn/smartadmin/show-1159.html
總結
以上是生活随笔為你收集整理的MMDetectionV2 + Colab的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows系统修改Docker镜像下
- 下一篇: 原生JS实现登录功能,本地Cookie保