手把手教你如何配置mmdetection并训练(win10环境)

该教程详细介绍了如何在Windows10系统下配置mmdetection的环境,包括下载Anaconda3创建虚拟环境、配置深度学习环境、使用PyCharm设置虚拟环境、安装CUDA和CUDNN,以及安装和测试mmdetection所需的各个模块。最后,文章提到了如何修改配置文件进行训练,并以CenterNet为例展示了训练过程。

目录

前言

一、mmdetection下载

二、mmdetection环境配置

1.下载安装Anaconda3

2.配置深度学习基本环境

3.PyChram设置虚拟环境

4.配置mmdetection环境

三、使用mmdetection训练

总结


前言

本文在win10环境下对mmdetection工具箱进行一个详细的配置教程,表中为创建的虚拟环境核心模块版本号。

       Name       版本
python3.7
torch1.8
CUDA11.1
cudnn8.2.0
mmcv2.0.0


一、mmdetection下载

github:open-mmlab/mmdetection: OpenMMLab Detection Toolbox and Benchmark (github.com)

下载完成之后使用pychram打开如下图所示:

接下来对mmdetection的基本环境进行配置 ,采用Anaconda3新建虚拟环境。

二、mmdetection环境配置

1.下载安装Anaconda3

参考我之前发布的一篇文章,只需要跟进到三、安装Tensorflow2.0版本之前的内容即可:(130条消息) windows环境下tensorflow2.0安装(避坑指南)_conda安装tensorflow2.0_PolarisFTL的博客-CSDN博客

2.配置深度学习基本环境

打开

使用下方命令(注:demo为虚拟环境名称可以任意设置),输入完成之后敲击回车

conda create -n demo python==3.7

 

如果与图中显示一致说明虚拟环境配置成功,使用指令进入虚拟环境,demo为自己设置的虚拟环境的名称,进入虚拟环境之后左侧括号中的内容会与虚拟环境名称保持一致。

activate demo

使用GPU进行训练时可以不用安装CUDA,只需要用下面的指令在虚拟环境中安装cudatoolkit和cudnn即可,这是一个小技巧。

conda install cudatoolkit==11.1.1
conda install cudnn==8.2.0.53

安装torch1.8GPU版本

conda install pytorch==1.8.0 torchvision==0.9.0 torchaudio==0.8.0 -c pytorch -c conda-forge

3.PyChram设置虚拟环境

基本步骤:File--Setting--Project:mmdetection-main--Python Interpreter--show all中点击+ --Conda Environment--Existing environment,图片步骤比较详细,可以按照图中顺序进行配置。

 

 

 

 

 

配置完成之后在目录下新建一个py文件来测试torch是否可用

import torch

print(torch.__version__)
print(torch.version.cuda)
print(torch.cuda.is_available())

这里显示True说明配置成功。

4.配置mmdetection环境

mmdetection官方文档: 开始你的第一步 — MMDetection 3.0.0 文档,下面内容参照官方文档进行配置。使用 MIM 安装 MMEngine 和 MMCV

pip install -U openmim
mim install mmengine
mim install "mmcv>=2.0.0"

基本环境配置完成我们就可以直接使用PyCharm中的Terminal进行安装其他模块了。注:直接安装会比较慢可以采用镜像来进行安装,在输入指令的后面加入下方镜像源。

-i https://pypi.tuna.tsinghua.edu.cn/simple

 如果安装mmengine时候遇到下面错误需要降低urllib3版本

pip install urllib3==1.26.6 -i https://pypi.tuna.tsinghua.edu.cn/simple

 

核心模块安装完成之后需要安装mmdetection工具箱中常用模块才可以进行训练,依次安装下面的模块。

pip install terminaltables -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pycocotools -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install shapely -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install scipy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install cython -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install imagecorruptions -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install cityscapesscripts -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple

安装完成之后进行测试demo,在测试之前我们需要下载预训练权重,这里我用的的CenterNet网络,链接可以打开mmdetection下载预训练权重页面:mmdetection/configs/centernet at main · open-mmlab/mmdetection · GitHub

下载好之后新建文件夹weights,将权重存放文件夹中,配置文件configs可以根据图中的路径进行寻找

在目录下新建一个py,命名为predict,下面的这段代码是我根据官方的测试代码进行了一个修改,能够批量预测文件夹中的图片,新建目录images,在里面存放一些图片用于预测(注:下载的预训练权重要与配置文件configs对应才行代码中注释的config_file是当训练完成之后会生成一个work_dir文件夹,里面会存放训练时的模型参数,在预测时候直接调用即可

如果在images文件夹中预测结果能够显示出来,说明mmdetection的环境已经配置成功,可以进行修改并训练。

三、使用mmdetection训练

本文以CenterNet为例,首先打开configs中的centernet目录下的网络文件,将base中的coco注释掉修改为图中所示,训练voc数据集,下面的dataset_type和data_root也需要进行修改,与目录对应,代码33行的num_classes需要修改为20,这与voc数据集类别保持一致。

 

全部代码如下,可以对比进行修改,关于配置文件的学习可以看官方文档:学习配置文件 — MMDetection 3.0.0 文档

_base_ = [
    # '../_base_/datasets/coco_detection.py',
    '../_base_/datasets/voc0712.py',
    '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py',
    './centernet_tta.py'
]

dataset_type = 'VOCDataset'
data_root = 'data/VOCdevkit'

# model settings
model = dict(
    type='CenterNet',
    data_preprocessor=dict(
        type='DetDataPreprocessor',
        mean=[123.675, 116.28, 103.53],
        std=[58.395, 57.12, 57.375],
        bgr_to_rgb=True),
    backbone=dict(
        type='ResNet',
        depth=18,
        norm_eval=False,
        norm_cfg=dict(type='BN'),
        init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet18')),
    neck=dict(
        type='CTResNetNeck',
        in_channels=512,
        num_deconv_filters=(256, 128, 64),
        num_deconv_kernels=(4, 4, 4),
        use_dcn=True),
    bbox_head=dict(
        type='CenterNetHead',
        num_classes=20,
        in_channels=64,
        feat_channels=64,
        loss_center_heatmap=dict(type='GaussianFocalLoss', loss_weight=1.0),
        loss_wh=dict(type='L1Loss', loss_weight=0.1),
        loss_offset=dict(type='L1Loss', loss_weight=1.0)),
    train_cfg=None,
    test_cfg=dict(topk=100, local_maximum_kernel=3, max_per_img=100))

train_pipeline = [
    dict(type='LoadImageFromFile', backend_args={{_base_.backend_args}}),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(
        type='PhotoMetricDistortion',
        brightness_delta=32,
        contrast_range=(0.5, 1.5),
        saturation_range=(0.5, 1.5),
        hue_delta=18),
    dict(
        type='RandomCenterCropPad',
        # The cropped images are padded into squares during training,
        # but may be less than crop_size.
        crop_size=(512, 512),
        ratios=(0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3),
        mean=[0, 0, 0],
        std=[1, 1, 1],
        to_rgb=True,
        test_pad_mode=None),
    # Make sure the output is always crop_size.
    dict(type='Resize', scale=(512, 512), keep_ratio=True),
    dict(type='RandomFlip', prob=0.5),
    dict(type='PackDetInputs')
]
test_pipeline = [
    dict(
        type='LoadImageFromFile',
        backend_args={{_base_.backend_args}},
        to_float32=True),
    # don't need Resize
    dict(
        type='RandomCenterCropPad',
        ratios=None,
        border=None,
        mean=[0, 0, 0],
        std=[1, 1, 1],
        to_rgb=True,
        test_mode=True,
        test_pad_mode=['logical_or', 31],
        test_pad_add_pix=1),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(
        type='PackDetInputs',
        meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape', 'border'))
]

# Use RepeatDataset to speed up training
train_dataloader = dict(
    batch_size=4,
    num_workers=1,
    persistent_workers=True,
    sampler=dict(type='DefaultSampler', shuffle=True),
    dataset=dict(
        _delete_=True,
        type='RepeatDataset',
        times=5,
        dataset=dict(
            type=dataset_type,
            data_root=data_root,
            ann_file='VOC2007/ImageSets/Main/trainval.txt',
            data_prefix=dict(sub_data_root='VOC2007/'),
            filter_cfg=dict(filter_empty_gt=True, min_size=32),
            pipeline=train_pipeline,
            backend_args={{_base_.backend_args}},
        )))

val_dataloader = dict(dataset=dict(pipeline=test_pipeline))
test_dataloader = val_dataloader

# optimizer
# Based on the default settings of modern detectors, the SGD effect is better
# than the Adam in the source code, so we use SGD default settings and
# if you use adam+lr5e-4, the map is 29.1.
optim_wrapper = dict(clip_grad=dict(max_norm=35, norm_type=2))

max_epochs = 28
# learning policy
# Based on the default settings of modern detectors, we added warmup settings.
param_scheduler = [
    dict(
        type='LinearLR', start_factor=0.001, by_epoch=False, begin=0,
        end=1000),
    dict(
        type='MultiStepLR',
        begin=0,
        end=max_epochs,
        by_epoch=True,
        milestones=[18, 24],  # the real step is [18*5, 24*5]
        gamma=0.1)
]
train_cfg = dict(max_epochs=max_epochs)  # the real epoch is 28*5=140

# NOTE: `auto_scale_lr` is for automatically scaling LR,
# USER SHOULD NOT CHANGE ITS VALUES.
# base_batch_size = (8 GPUs) x (16 samples per GPU)
auto_scale_lr = dict(base_batch_size=128)

配置文件修改完成之后在目录下新建data文件夹,需要下载VOC2007数据集可以通过百度网盘下载:链接:https://pan.baidu.com/s/1MXOUk938yZlLFm0GUXvxZw 提取码:xust 

下面打开Terminal输入指令即可训练,如果代码没有报错并出现了第二张图中损失函数的变化说明模型正在训练。

python tools/train.py configs/centernet/centernet_r18-dcnv2_8xb16-crop512-140e_coco.py

总结

制作不易,喜欢的小伙伴可以收藏点赞,有什么问题都可以在评论区留言。

评论 23
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PolarisFTL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值