MMDetection 快速開始,訓練自定義數據集

2021-02-20 GoCoding

本文將快速引導使用 MMDetection ,記錄了實踐中需注意的一些問題。

環境準備基礎環境

Nvidia 顯卡的主機

Ubuntu 18.04

Nvidia Driver

開發環境

下載並安裝 Anaconda ,之後於 Terminal 執行:

# 創建 Python 虛擬環境
conda create -n open-mmlab python=3.7 -y
conda activate open-mmlab

# 安裝 PyTorch with CUDA
conda install pytorch==1.6.0 torchvision==0.7.0 cudatoolkit=10.2 -c pytorch -y

# 安裝 MMCV
pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu102/torch1.6.0/index.html

# 安裝 MMDetection
git clone https://github.com/open-mmlab/mmdetection.git
cd mmdetection
pip install -r requirements/build.txt
pip install -v -e .

pytorch==1.7.0 時多卡訓練會發生問題,需參考此 Issue。命令參考:

conda install pytorch==1.7.0 torchvision==0.8.1 cudatoolkit=10.2 -c pytorch -y

pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu102/torch1.7.0/index.html

更多安裝方式,可見官方文檔:

現有模型進行推斷Faster RCNN

以 R-50-FPN 為例,先下載其 model 文件到 mmdetection/checkpoints/。之後,進行推斷,

conda activate open-mmlab

cd mmdetection/

python demo/image_demo.py \
demo/demo.jpg \
configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth

現有模型進行測試準備數據集

下載 COCO 數據集,如下放進 mmdetection/data/coco/ 目錄,

mmdetection
├── data
│   ├── coco
│   │   ├── annotations
│   │   ├── train2017
│   │   ├── val2017
│   │   ├── test2017

測試現有模型

cd mmdetection/

# single-gpu testing
python tools/test.py \
configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
--out results.pkl \
--eval bbox \
--show

# multi-gpu testing
bash tools/dist_test.sh \
configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
2 \
--out results.pkl \
--eval bbox

效果如下,

結果如下,

loading annotations into memory...
Done (t=0.33s)
creating index...
index created!
[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>] 5000/5000, 15.3 task/s, elapsed: 328s, ETA:     0s
writing results to results.pkl

Evaluating bbox...
Loading and preparing results...
DONE (t=0.89s)
creating index...
index created!
Running per image evaluation...
Evaluate annotation type *bbox*
DONE (t=26.17s).
Accumulating evaluation results...
DONE (t=4.10s).
Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.374
Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.581
Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.404
Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.212
Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.410
Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.481
Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.517
Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.517
Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.517
Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.326
Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.557
Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.648
OrderedDict([('bbox_mAP', 0.374), ('bbox_mAP_50', 0.581), ('bbox_mAP_75', 0.404), ('bbox_mAP_s', 0.212), ('bbox_mAP_m', 0.41), ('bbox_mAP_l', 0.481), ('bbox_mAP_copypaste', '0.374 0.581 0.404 0.212 0.410 0.481')])

標準數據集訓練模型準備數據集

同前一節的 COCO 數據集。

準備配置文件

配置文件為 configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py。

需要依照自己的 GPU 情況,修改 lr 學習速率參數,說明如下:

lr=0.005 for 2 GPUs * 2 imgs/gpu

lr=0.01 for 4 GPUs * 2 imgs/gpu

lr=0.02 for 8 GPUs and 2 img/gpu (batch size = 8*2 = 16), DEFAULT

lr=0.08 for 16 GPUs * 4 imgs/gpu

_base_ = [
    '../_base_/models/faster_rcnn_r50_fpn.py',
    '../_base_/datasets/coco_detection.py',
    '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001)

訓練模型

cd mmdetection/

# single-gpu training
python tools/train.py \
configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
--work-dir _train

# multi-gpu training
bash ./tools/dist_train.sh \
configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \
2 \
--work-dir _train

自定義數據集訓練模型自定義數據集

這裡從 Pascal VOC 數據集拿出 cat 作為自定義數據集來演示,

conda activate open-mmlab

# Dataset Management Framework (Datumaro)
pip install 'git+https://github.com/openvinotoolkit/datumaro'
# pip install tensorflow

datum convert --input-format voc --input-path ~/datasets/VOC2012 \
--output-format coco --output-dir ~/datasets/coco_voc2012_cat \
--filter '/item[annotation/label="cat"]'

數據集需要是 COCO 格式,以上直接用 datum 從 VOC 拿出 cat 並轉為了 COCO 格式。

準備配置文件

添加 configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py 配置文件,內容如下:

# The new config inherits a base config to highlight the necessary modification
_base_ = [
    '../_base_/models/faster_rcnn_r50_fpn.py',
    '../_base_/datasets/coco_detection.py',
    '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]

# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
    roi_head=dict(
        bbox_head=dict(num_classes=1)))

# Modify dataset related settings
dataset_type = 'COCODataset'
classes = ('cat',)
data_root = '/home/john/datasets/'
data = dict(
    train=dict(
        img_prefix=data_root + 'VOC2012/JPEGImages/',
        classes=classes,
        ann_file=data_root + 'coco_voc2012_cat/annotations/instances_train.json'),
    val=dict(
        img_prefix=data_root + 'VOC2012/JPEGImages/',
        classes=classes,
        ann_file=data_root + 'coco_voc2012_cat/annotations/instances_val.json'),
    test=dict(
        img_prefix=data_root + 'VOC2012/JPEGImages/',
        classes=classes,
        ann_file=data_root + 'coco_voc2012_cat/annotations/instances_val.json'))
evaluation = dict(interval=100)

# Modify schedule related settings
optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001)
total_epochs = 10000

# Modify runtime related settings
checkpoint_config = dict(interval=10)

# We can use the pre-trained model to obtain higher performance
# load_from = 'checkpoints/*.pth'

model 配置 num_classes=1 為類別數量

dataset 配置為準備的自定義數據集

schedule 配置訓練的 lr 及迭代輪次 total_epochs

runtime 可配置 checkpoint 間隔多少存一個。默認 1 epoch 1 個,空間不夠用😶

配置可對照 __base__ 的內容覆蓋修改,更多說明見官方文檔。

訓練模型

# single-gpu training
python tools/train.py \
configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py \
--work-dir _train_voc_cat

# multi-gpu training
bash ./tools/dist_train.sh \
configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py \
2 \
--work-dir _train_voc_cat

斷點恢復時,

bash ./tools/dist_train.sh \
configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py \
2 \
--work-dir _train_voc_cat \
--resume-from _train_voc_cat/epoch_100.pth

如發生 ModuleNotFoundError: No module named 'pycocotools' 錯誤,這樣修正:

pip uninstall pycocotools mmpycocotools
pip install mmpycocotools

查看訓練 loss

pip install seaborn

python tools/analyze_logs.py plot_curve \
_train_voc_cat/*.log.json \
--keys loss_cls loss_bbox \
--legend loss_cls loss_bbox

可用 keys 見 log.json 記錄。

測試模型

# single-gpu testing
python tools/test.py \
configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py \
_train_voc_cat/latest.pth \
--out results.pkl \
--eval bbox \
--show

# multi-gpu testing
bash tools/dist_test.sh \
configs/voc_cat/faster_rcnn_r50_fpn_1x_voc_cat.py \
_train_voc_cat/latest.pth \
2 \
--out results.pkl \
--eval bbox

相關焦點

  • MMDetection v2.0 訓練自己的數據集
    -i -t : 交互模式執行mm_det : 容器名稱/bin/bash :執行腳本2 準備自己的VOC數據集mmdetection 支持VOC數據集,還有COCO數據集格式,還可以自定義數據格式,現在我們採用VOC的數據格式,mm_det容器已經映射宿主目錄了,在宿主目錄/train_data,新建目錄存放數據集,可在容器內/mmdetection
  • Scaled-YOLOv4 快速開始,訓練自定義數據集
    usp=sharing現有模型測試準備 COCO 數據集下載 COCO 數據集 http://cocodataset.org/,coco2017├── annotations│   ├── instances_train2017.json│   └── instances_val2017.json├── test2017├──
  • 開源 | 商湯聯合港中文開源 mmdetection
    不同模型的訓練速度大約比 FAIR 的 Detectron 快 5% ~ 20%。當前最優:這是 MMDet 團隊的代碼庫,該團隊贏得了 2018 COCO 檢測挑戰賽的冠軍。除了 mmdetection,研究者們還開源了用於計算機視覺研究的 mmcv 庫,mmdetection 很多算法的實現都依賴於 mmcv 庫。
  • detectron2使用自定義的數據集
    它可以與detectron2中的許多內置功能一起使用,因此建議使用它。你的自定義數據集字典。你還可以以自己的格式返回任意字典格式,例如為新任務添加額外的鍵,然後你還需要在下遊正確處理它們。請參閱下面的更多細節。。標準數據集字典對於標準任務(實例檢測,實例/語義/全景分割,關鍵點檢測),我們將原始數據集加載到具有類似於COCO的json注釋規範的list [dict]中。這是我們對數據集的標準表示。
  • mmdetection最小復刻版(一):整體概覽
    mmdetection的最小實現版本簡稱 mmdetection-mini。主要目的是為了每天方便快速的和mmcv/mmdetection同步更新。如果我結構改變了,那麼同步會有點點麻煩。細節方面有些不同,主要是:把mmcv嵌入其中我不想同時維護兩個庫的更新,比較累。
  • mmdetection專題之詳解hook機制
    mmdetection專題旨在分析mmdetection的框架邏輯,主要從註冊器、HOOK機制等幾個非常重要的機制來看mmdetection的整體邏輯。mmdetection是一款優秀的基於PyTorch的開源目標檢測系統,由香港中文大學(CUHK)多媒體實驗室(mmlab)開發。
  • 如何在Windows系統上使用Object Detection API訓練自己的數據?
    (點擊跳轉)然後就想著把數據集換成自己的數據集進行訓練得到自己的目標檢測模型。動手之前先學習了一波別人是如何實現的,看了大多數教程都有一個小問題:用VOC2012數據集進行訓練當做用自己的數據集。然而,初心想看的是自己的數據集啊!
  • mmdetection最小復刻版(七):anchor-base和anchor-free差異分析
    貼一下框架github地址:https://github.com/hhaAndroid/mmdetection-mini歡迎star1 anchor-base和anchor-free本質差別這兩個超參在不同的數據集上面可能要重新調整,而且不一定好設置。而本文ATSS就希望消除這兩個超參,達到自適應的功能。    其定義規則也比較簡單,通俗易懂,流程為:
  • mmdetection最小復刻版(六):FCOS深入可視化分析
    貼一下github:https://github.com/hhaAndroid/mmdetection-mini歡迎star2.2 正負樣本定義    一個目標檢測算法性能的優異性,最大影響因素就是如何定義正負樣本。而fcos的定義方式非常mask sense,通俗易懂。
  • mmdetection目標檢測框架安裝與測試
    一、mmdetection簡介項目地址:https://github.com/open-mmlab/mmdetection
  • MMSkeleton 快速開始,使用 WebCam 測試
    本文將引導快速使用 MMSkeleton ,介紹用攝像頭測試實時姿態估計。
  • 輕鬆學Pytorch-實現自定義對象檢測器
    上一篇文章使用了torchvision中提供的預訓練對象檢測網絡Faster-RCNN實現了常見的對象檢測,基於COCO數據集,支持90個類型對象檢測,非常的實用。本文將介紹如何使用自定義數據集,使用Faster-RCNN預訓練模型實現遷移學習,完成自定義對象檢測。
  • KITTI數據集簡介與使用
    以Object detection為例,下圖是Object Detection Evaluation 2012標準數據集中left color images文件的目錄結構,樣本分別存儲於testing和training數據集。
  • Windows系統如何安裝Tensorflow Object Detection API
    什麼是TensorflowTensorFlow™ 是一個採用數據流圖(data flow graphs),用於數值計算的開源軟體庫
  • 使用 tf.distribute.Strategy 進行自定義訓練
    本教程演示了如何使用 tf.distribute.Strategy 來進行自定義訓練循環。
  • PaddleDetection目標檢測套件
    除了功能,再來看看性能各模型結構和骨幹網絡的代表模型在COCO數據集上精度mAP和單卡Tesla V100上預測速度(FPS)對比圖paddledetection圖中模型均可在模型庫中獲取,地址是 https://github.com/PaddlePaddle/PaddleDetection
  • 【PyTorch】人臉區域的探測和識別 | 自組織圖像數據集的製作
    因為一開始並不是用「黑人」這個例子作為最終人臉識別的示例效果(版權原因),讀者可在閱讀完本文之後復現。實踐表明,此demo模型在人數不太多的情況下,可以達到良好效果(標記準確率約75%),可以在往後提高其檢測有效性和識別準確性。下面分步展開。人臉數據從何而來?找到相關人的照片,然後一個一個把人臉摳下來嗎?這是不現實的,你沒那個精力。
  • mask rcnn訓練自己的數據集
    /blog.csdn.net/shwan_ma/article/details/77823281有關Mask-RCNN和Faster RCNN算法可以參考:https://blog.csdn.net/linolzhang/article/details/71774168https://blog.csdn.net/lk123400/article/details/54343550準備訓練數據集
  • MMDetection新版本V2.7發布,支持DETR,還有YOLOV4在路上!
    其實transformer主要適合處理的數據輸入是a set of objects,就是一坨東西然後attention。具體到目標檢測問題上,因為detection的輸出更是a set of objects,這簡直不能和transformer更契合了:
  • 訓練YOLO網絡
    基於 YouTube-8M 數據集的籃球場球員移動檢測這一次,我將向你展示如何快速地、以相對較低的代價和不那麼強大的機器創建目標檢測模型,這個模型能夠檢測任何你選擇的對象。如果你需要在工作中快速測試你的想法,或者只是有一小段時間建立在家構建你的項目,這是一個很好的方法。