ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

MMDetection网络结构讲解

2021-11-19 11:04:28  阅读:684  来源: 互联网

标签:pipeline img True mask dict 讲解 MMDetection 网络结构 type


前言
MMDetection2中大部分模型都是通过配置4个基础的组件来构造的,本篇博客主要是介绍MMDetection中的配置文件,主要内容是按照MMDetection文档进行中文翻译的,有兴趣的话建议去看原版的英文文档。

一、配置文件结构
在config/_base_文件夹下面总共有4个基础的组件,它们分别是:dataset、model、schedule、default_runtime。

许多的方法都可以被这些基础组件轻松的构造,我们将由_base_中的组件构成的配置称之为primitive。

为了方便于理解,我们推荐使用者去继承已有的方法,例如,如果你想要去基于Faster-RCNN做一些更改,你首先需要在你的配置文件中去继承Faster-RCNN的基础结构(加入_base_ = ../faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py这行代码就行),然后在配置文件中更改必要的组件。

如果你要构造一个和其他方法没有关系的全新的方法,那么你应该在configs文件夹下面创建一个xxx_rcnn的文件。

二、配置文件名称风格
我们是按照下面这种风格来命名配置文件的,我们也建议使用者也这样来命名你们自己的配置文件。

{model}_[model setting]_{backbone}_{neck}_[norm setting]_[misc]_[gpu x batch_per_gpu]_{schedule}_{dataset}
{xxx}是必选项,[yyy]是可选项

{model}:模型的类型 ,例如faster_rcnn、mask_rcnn, 等等.
[model setting]: 给模型一些指定设置, 例如without_semantic for htc、moment for reppoints, 等等.
{backbone}: backbone 的类型 r50 (ResNet-50), x101 (ResNeXt-101)。(相当于特征提取网络)
{neck}: neck 的类型选择,例如fpn, pafpn, nasfpn, c4.
[norm_setting]: 如果没有指定,那就默认为bn (Batch Normalization) , 还有其他可选的norm layer类型,比如 gn (Group Normalization)、syncbn (Synchronized Batch Normalization). gn-head/gn-neck 表示 GN 仅仅被用在head/neck模块上, gn-all 表示 GN 被用在整个模型上, 例如:backbone, neck, head这些模块。
[misc]: 一些比较杂的模型设置或者插件,例如 dconv, gcb, attention, albu, mstrain.
[gpu x batch_per_gpu]: GPU的个数以及每块GPU上的batch size大小,默认为8*2(8块GPU,每块GPU上2个batch size,相当于batch size为16)。
{schedule}: 训练的 schedule, 可选择的有1x, 2x, 20e等等. 1x 和 2x 分别表示 12 个epochs 和 24个epochs。 20e 被用在 cascade models中,它表示20个epochs. 对于1x/2x而言, 初始的学习率分别在第8/16个epeochs和第11/22个epochs以10的倍率递减。对于20e而言,初始的学习率在第16个epeochs和第19个epochs以10的倍率。
{dataset}: 数据集有 coco, cityscapes, voc_0712, wider_face这些选项。
三、 一个Mask-RCNN的例子
为了帮助使用者对这个检测模型的配置和模块有一个基本的理解,我们对以ResNet50为backbone,FPN为neck的Mask-RCNN模型的配置文件进行了简单的注释。更多和模块与配置相关的信息请参照我们相应的API文档。

下面将官网提供的例子分成3个部分来讲:

1、model
model = dict(
    type='MaskRCNN',                      # 检测器的名称
    pretrained=
    'torchvision://resnet50',             # ImageNet的预训练模型
    backbone=dict(  # backbone的配置
        type='ResNet',                    # backbone的类型, 请参照 https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/backbones/resnet.py#L288 查看更多的细节.
        depth=50,                         # backbone网络的深度, 对于ResNet and ResNext的backbone而言,通常是使用50或者101的深度
        num_stages=4,                     # backbone中stage的个数(应该是相当于ResNet网络中block的个数).
        out_indices=(0, 1, 2, 3),         # backbone中每一个stage过程输出的feature的下标
        frozen_stages=1,                  # 1 stage 的权重被冻结
        norm_cfg=dict(                    # normalization layers的配置.
            type='BN',                    # norm layer的类型, 通常是 BN or GN
            requires_grad=True),          # 是否训练BN中的gamma and beta参数
        norm_eval=True,                   # 是否冻结BN中的统计信息(相当于模型eval的过程,不进行统计数据)
        style='pytorch'),                 # backbone的类型, 'pytorch' means that stride 2 layers are in 3x3 conv, 'caffe' means stride 2 layers are in 1x1 convs.(感觉这句直接看英文还方便些)
    
    neck=dict(                                #neck模块的配置
        type='FPN',                       # 该detection的neck为FPN. 我们还提供了 'NASFPN', 'PAFPN'等neck类型. 具体请参照 https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/necks/fpn.py#L10 查看更多的细节。
        in_channels=[256, 512, 1024, 2048],  # 输入的channels,这个地方和backbone的output channels保持一直。
        out_channels=256,                 # 特征金字塔(pyramid feature map)的每一层输出的channel数
        num_outs=5),                      # output 输出的个数
    
    rpn_head=dict(                        # RPN模块的配置
        type='RPNHead',                   # RPN head 的类型为'RPNHead', 我们还支持 'GARPNHead'等等. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/dense_heads/rpn_head.py#L12.
        in_channels=256,  # 每一个输入的feature的input channels, 这个地方需要和neck模块的output channels保持一致。
        feat_channels=256,                # Feature channels of convolutional layers in the head(应该是指RPN模块头部的卷积操作,输出channel为256,它的输入为上面FPN得到的多尺度feature map).
        anchor_generator=dict(            # 生成anchor的配置
            type='AnchorGenerator',       # 绝大多数都是用AnchorGenerator, SSD 检测器(单阶段的目标检测算法)使用的是`SSDAnchorGenerator`. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/anchor/anchor_generator.py#L10.
            scales=[8],                   # anchor的生成个数, 特征图上每一个位置所生成的anchor个数为scale * base_sizes
            ratios=[0.5, 1.0, 2.0],       # anchor中height 和width的比率.
            strides=[4, 8, 16, 32, 64]),  # The strides of the anchor generator. 这个需要和FPN feature strides保持一致. 如果base_sizes没有设置的话,这个strides 将会被当作base_sizes.
        bbox_coder=dict(                  # Config of box coder to encode and decode the boxes during training and testing
            type='DeltaXYWHBBoxCoder',    # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of methods. Refer to https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/coder/delta_xywh_bbox_coder.py#L9 for more details.
            target_means=[0.0, 0.0, 0.0, 0.0],  # The target means used to encode and decode boxes
            target_stds=[1.0, 1.0, 1.0, 1.0]),  # The standard variance used to encode and decode boxes
        loss_cls=dict(                    # 分类分支的损失函数配置
            type='CrossEntropyLoss',      # 分类分支的损失函数类型, 我们也提供FocalLoss等损失函数
            use_sigmoid=True,             # RPN 过程通常是一个二分类,所以它通常使用sigmoid函数。
            loss_weight=1.0),             # 分类损失分支所占的权重。
        loss_bbox=dict(                   # box回归分支的损失函数配置.
            type='L1Loss',                # loss的类型, 我们还提供了许多IoU Losses and smooth L1-loss 等. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/smooth_l1_loss.py#L56.
            loss_weight=1.0)),            # 回归分支损失所占的权重.
 
    roi_head=dict(                        # RoIHead 封装了二阶段检测器的第二阶段的模块
        type='StandardRoIHead',           # RoI head的类型. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/roi_heads/standard_roi_head.py#L10.
        bbox_roi_extractor=dict(          # RoI feature extractor 用于 bbox regression.
            type='SingleRoIExtractor',    # RoI feature extractor的类型, 绝大多少方法都使用 SingleRoIExtractor. 具体实现细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/roi_heads/roi_extractors/single_level.py#L10.
            roi_layer=dict(               # RoI Layer的配置
                type='RoIAlign',          # RoI Layer的类型, 同时还支持DeformRoIPoolingPack 和 ModulatedDeformRoIPoolingPack这两种类型. 具体实现细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/ops/roi_align/roi_align.py#L79.
                output_size=7,            # feature maps的输出尺度,相当于输出7*7.
                sampling_ratio=0),        # Sampling ratio when extracting the RoI features. 0 means adaptive ratio.(这个参数我还不太明白orz)
            out_channels=256,             # 提取特征的输出channels数.
            featmap_strides=[4, 8, 16, 32]),  # Strides of multi-scale feature maps. It should be consistent to the architecture of the backbone.(这个地方还不太清楚)
        bbox_head=dict(                   # RoIHead中的 bbox head的配置.
            type='Shared2FCBBoxHead',     # bbox head的类型, 具体细节请参照 https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py#L177.
            in_channels=256,              # bbox head的输入channels数. 这个地方需要和roi_extractor的out_channels保持一致。
            fc_out_channels=1024,         # FC layers的输出维度.
            roi_feat_size=7,              # RoI features的尺寸
            num_classes=80,               # 分类类别数
            bbox_coder=dict(              # Box coder used in the second stage.
                type='DeltaXYWHBBoxCoder',  # Type of box coder. 'DeltaXYWHBBoxCoder' is applied for most of methods.
                target_means=[0.0, 0.0, 0.0, 0.0],  # Means used to encode and decode box
                target_stds=[0.1, 0.1, 0.2, 0.2]),  # Standard variance for encoding and decoding. It is smaller since the boxes are more accurate. [0.1, 0.1, 0.2, 0.2] is a conventional setting.
            reg_class_agnostic=False,     # Whether the regression is class agnostic.
            loss_cls=dict(                # 分类分支的损失函数配置
                type='CrossEntropyLoss',  # 分类分支损失函数的类型, 我们还提供了FocalLoss 等.
                use_sigmoid=False,        # 是否使用sigmoid.
                loss_weight=1.0),         # 分类分支损失所占的权重.
            loss_bbox=dict(               # 回归分支损失函数配置.
                type='L1Loss',            # 损失函数类型, 我们还提供了许多IoU Losses和smooth L1-loss等.
                loss_weight=1.0)),        # 回归分支损失所占的权重.
 
        mask_roi_extractor=dict(          # RoI feature extractor 用于 mask regression.
            type='SingleRoIExtractor',    # RoI feature extractor的类型, 绝大多数方法都是使用SingleRoIExtractor.
            roi_layer=dict(               # RoI Layer 的配置,提取特征用于实例分割。
                type='RoIAlign',          # RoI Layer的类型,我们还提供了DeformRoIPoolingPack and ModulatedDeformRoIPoolingPack.
                output_size=14,           # feature maps的输出size.
                sampling_ratio=0),        # Sampling ratio when extracting the RoI features.(这个参数还没太弄明白)
            out_channels=256,             # extracted feature的输出channels.
            featmap_strides=[4, 8, 16, 32]),  # Strides of multi-scale feature maps.(这个参数没太弄明白)
        mask_head=dict(                   # Mask 的预测模块
            type='FCNMaskHead',           # mask head的类型, 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/roi_heads/mask_heads/fcn_mask_head.py#L21.
            num_convs=4,                  # mask head中卷积层的个数.
            in_channels=256,              # mask head输入的channels数, 应该和mask roi extractor的输出channel数保持一致。
            conv_out_channels=256,        # convolutional layer输出的channel数.
            num_classes=80,               # 分割任务的类别数
            loss_mask=dict(               # mask 分支的损失函数配置.
                type='CrossEntropyLoss',  # 用于分割的损失函数类型
                use_mask=True,            # Whether to only train the mask in the correct class(是否训练仅仅是正确类别的mask).
                loss_weight=1.0))))       # mask分支损失所占的权重.
 
train_cfg = dict(                         # 训练过程中rpn and rcnn和模块的超参数设置
    rpn=dict(                             # 训练过程中rpn的超参数配置
        assigner=dict(                    # assigner的配置(assigner是个什么东西?可以理解为一个超参配置的字典吧)
            type='MaxIoUAssigner',        # assigner的类型, MaxIoUAssigner被用在许多常见的detectors. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/max_iou_assigner.py#L10.
            pos_iou_thr=0.7,              # IoU >= threshold 0.7 将会被当作一个正样本
            neg_iou_thr=0.3,              # IoU < threshold 0.3 将会被当作一个负样本
            min_pos_iou=0.3,              # The minimal IoU threshold to take boxes as positive samples
            match_low_quality=True,       # Whether to match the boxes under low quality (see API doc for more details).
            ignore_iof_thr=-1),           # IoF threshold for ignoring bboxes
        sampler=dict(                     # positive/negative sampler的配置
            type='RandomSampler',         # sampler的类型, 同时还提供有PseudoSampler和其他类型的samplers.具体实现细节请参照Refer to https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/samplers/random_sampler.py#L8.
            num=256,  # samples的个数
            pos_fraction=0.5,  # 正样本占总样本的比例。
            neg_pos_ub=-1,  # The upper bound of negative samples based on the number of positive samples.
            add_gt_as_proposals=False),  # Whether add GT as proposals after sampling.
        allowed_border=-1,  # The border allowed after padding for valid anchors.
        pos_weight=-1,  # The weight of positive samples during training.
        debug=False),  # 是否设置debug 模式
    rpn_proposal=dict(  # 在训练过程中生成proposals的配置
        nms_across_levels=False,  # Whether to do NMS for boxes across levels
        nms_pre=2000,  # 在NMS之前的box个数
        nms_post=1000,  # NMS处理后保留的box个数
        max_num=1000,  # NMS处理之后所使用的box个数
        nms_thr=0.7,  # NMS过程所使用的阈值
        min_bbox_size=0),  # 允许的最小的box尺寸
 
    rcnn=dict(  # roi heads的超参数配置
        assigner=dict(  # 第二阶段的assigner配置, 这个和上面rpn中用到的assigner有所不同
            type='MaxIoUAssigner',  # assigner的类型, MaxIoUAssigner被用于所有的roi_heads. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/assigners/max_iou_assigner.py#L10.
            pos_iou_thr=0.5,  # IoU >= threshold 0.5 被当作正样本
            neg_iou_thr=0.5,  # IoU >= threshold 0.5 被当作正样本
            min_pos_iou=0.5,  # 最小的IoU 阈值来判断 boxes 是否为正样本。
            match_low_quality=False,  # Whether to match the boxes under low quality (see API doc for more details).
            ignore_iof_thr=-1),  # IoF threshold for ignoring bboxes
        sampler=dict(
            type='RandomSampler',  # sampler的类型, 还提供PseudoSampler和其他的samplers类型. 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/bbox/samplers/random_sampler.py#L8.
            num=512,  # 样例的个数
            pos_fraction=0.25,  # 正样例占总样例的比例。
            neg_pos_ub=-1,  # The upper bound of negative samples based on the number of positive samples.
            add_gt_as_proposals=True
        ),  #在sample过程之后,是否将ground trueth当作proposals.
        mask_size=28,  # mask的size大小
        pos_weight=-1,  # The weight of positive samples during training(不太明白).
        debug=False))  # 是否设置debug mode
 
test_cfg = dict(  #rpn and rcnn在测试过程的超参数配置
    rpn=dict(  #在测试过程rpn生成proposals的配置(相当于第一阶段)
        nms_across_levels=False,  # Whether to do NMS for boxes across levels
        nms_pre=1000,  # NMS之前的boxs个数
        nms_post=1000,  # NMS所保留的boxs个数
        max_num=1000,  # NMS处理之后最多被使用的boxs个数
        nms_thr=0.7,  # 在NMS处理过程中所使用的阈值
        min_bbox_size=0),  # 允许的最小的box尺寸
    rcnn=dict(  # roi heads的配置
        score_thr=0.05,  # 用来过滤boxes的阈值
        nms=dict(  # nms 在第二阶段的配置
            type='nms',  # nms的类型
            iou_thr=0.5),  # NMS的阈值
        max_per_img=100,  # Max number of detections of each image
        mask_thr_binary=0.5))  # mask 预测的阈值
dataset_type = 'CocoDataset'  # Dataset的类型, 将用于定义数据集
data_root = 'data/coco/'  # 数据集的存放路径
img_norm_cfg = dict(  # 对输入图片进行标准化处理的配置
    mean=[123.675, 116.28, 103.53],  # 用于预训练backbone模型的均值
    std=[58.395, 57.12, 57.375],  # 用于预训练backbone模型的标准差
    to_rgb=True
)  # The channel orders of image used to pre-training the pre-trained backbone models
2、datasets的配置
train_pipeline = [  # 训练的pipeline
    dict(type='LoadImageFromFile'),  # First pipeline用于从文件存放路径中导入图片
    dict(
        type='LoadAnnotations',  # Second pipeline用于给图片导入对应的标签
        with_bbox=True,  # 是否使用bounding box标签数据, 如果用于检测任务,则为True
        with_mask=True,  # 是否使用instance mask标签数据, 如果用于实例分割任务,则为True
        poly2mask=False),  # 是否将polygon mask转化为instance mask, 设置为False将会加速和减少内存
    dict(
        type='Resize',  # Augmentation pipeline resize图片和图片所对应的标签
        img_scale=(1333, 800),  # 图片的最大尺寸
        keep_ratio=True
    ),  # 是否保存宽高比例
    dict(
        type='RandomFlip',  # Augmentation pipeline flip图片和图片所对应的标签
        flip_ratio=0.5),  # flip的比率
    dict(
        type='Normalize',  # Augmentation pipeline 对输入的图片进行标准化
        mean=[123.675, 116.28, 103.53],  # 均值
        std=[58.395, 57.12, 57.375],  # 标准差
        to_rgb=True),
    dict(
        type='Pad',  # Padding 的配置
        size_divisor=32),  # 填充图像的数目应该可以被整除
    dict(type='DefaultFormatBundle'),  # Default format bundle to gather data in the pipeline
    dict(
        type='Collect',  # 决定数据中哪些key可以被传入pipeline中
        keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
]
test_pipeline = [
    dict(type='LoadImageFromFile'),  # First pipeline 从文件路径中导入图片
    dict(
        type='MultiScaleFlipAug',  # An encapsulation that encapsulates the testing augmentations
        img_scale=(1333, 800),  # 用于Resize pipeline的最大图片尺寸
        flip=False,  # 是否在test过程flip images
        transforms=[
            dict(type='Resize',  # Use resize augmentation
                 keep_ratio=True),  # 是否保持宽高的比例.
            dict(type='RandomFlip'),  # 由于flip=False这个RandomFlio将不会被使用。
            dict(
                type='Normalize',  # 标准化操作的配置, 从img_norm_cfg文件中取相应的值
                mean=[123.675, 116.28, 103.53],
                std=[58.395, 57.12, 57.375],
                to_rgb=True),
            dict(
                type='Pad',  # padding图片使其能够被12整除.
                size_divisor=32),
            dict(
                type='ImageToTensor',  # 将图片转化为tensor
                keys=['img']),
            dict(
                type='Collect',  # Collect pipeline 收集在test过程中必要的key.
                keys=['img'])
        ])
]
 
data = dict(
    # 学习率lr和总的batch size数目成正比,例如:8卡GPU  samples_per_gpu = 2的情况(相当于总的batch size = 8*2),学习率lr = 0.02
    # 如果我是单卡GPU samples_per_gpu = 4的情况,学习率lr应该设置为:0.02*(4/16) = 0.005    
    samples_per_gpu=2,  # 每个GPU上的batch size    
    workers_per_gpu=2,  # 每个GPU上的workers数目
    train=dict(  # 训练数据集的配置
        type='CocoDataset',  # 数据集的类型, 具体信息请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/datasets/coco.py#L19.
        ann_file='data/coco/annotations/instances_train2017.json',  # 标注文件的路径
        img_prefix='data/coco/train2017/',  # 图片文件的前缀
        pipeline=[  # pipeline, this is passed by the train_pipeline created before.(这个地方应该可以直接写成pipeline = train_pipeline,因为上面有定义train_pipeline这个中间变量)
            dict(type='LoadImageFromFile'),
            dict(
                type='LoadAnnotations',
                with_bbox=True,
                with_mask=True,
                poly2mask=False),
            dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
            dict(type='RandomFlip', flip_ratio=0.5),
            dict(
                type='Normalize',
                mean=[123.675, 116.28, 103.53],
                std=[58.395, 57.12, 57.375],
                to_rgb=True),
            dict(type='Pad', size_divisor=32),
            dict(type='DefaultFormatBundle'),
            dict(
                type='Collect',
                keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
        ]),
    val=dict(  # 验证集的配置
        type='CocoDataset',
        ann_file='data/coco/annotations/instances_val2017.json',
        img_prefix='data/coco/val2017/',
        pipeline=[  # Pipeline is passed by test_pipeline created before
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1333, 800),
                flip=False,
                transforms=[
                    dict(type='Resize', keep_ratio=True),
                    dict(type='RandomFlip'),
                    dict(
                        type='Normalize',
                        mean=[123.675, 116.28, 103.53],
                        std=[58.395, 57.12, 57.375],
                        to_rgb=True),
                    dict(type='Pad', size_divisor=32),
                    dict(type='ImageToTensor', keys=['img']),
                    dict(type='Collect', keys=['img'])
                ])
        ]),
    test=dict(  # Test dataset config, modify the ann_file for test-dev/test submission
        type='CocoDataset',
        ann_file='data/coco/annotations/instances_val2017.json',
        img_prefix='data/coco/val2017/',
        pipeline=[  # Pipeline is passed by test_pipeline created before
            dict(type='LoadImageFromFile'),
            dict(
                type='MultiScaleFlipAug',
                img_scale=(1333, 800),
                flip=False,
                transforms=[
                    dict(type='Resize', keep_ratio=True),
                    dict(type='RandomFlip'),
                    dict(
                        type='Normalize',
                        mean=[123.675, 116.28, 103.53],
                        std=[58.395, 57.12, 57.375],
                        to_rgb=True),
                    dict(type='Pad', size_divisor=32),
                    dict(type='ImageToTensor', keys=['img']),
                    dict(type='Collect', keys=['img'])
                ])
        ],
        samples_per_gpu=2  # 测试过程中每张GPU上的batch size
        ))
evaluation = dict(  # 这个配置是创建一个evaluation hook, 具体细节请查看https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/evaluation/eval_hooks.py#L7.
    interval=1,  # 隔多少个epoch进行evaluation一次
    metric=['bbox', 'segm'])  # evaluation所用的评价指标
3、schedule
optimizer = dict(  # 构造optimizer的配置, 支持PyTorch中所有的优化器,并且参数名称也和PyTorch中提供的一样。
    type='SGD',  # optimizers的类型, 具体细节请参照https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/optimizer/default_constructor.py#L13.
    lr=0.02,  # optimizers的学习率, 请到PyTorch的文档中查看相关参数的具体用法。
    momentum=0.9,  # SGD优化器的超参数:Momentum
    weight_decay=0.0001)  # SGD优化器的超参数:Weight decay
optimizer_config = dict(  # 构造optimizer hook的配置, 具体细节请参照 https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/optimizer.py#L8.
    grad_clip=None)  # 绝大多少方法都不会使用gradient clip
lr_config = dict(  # Learning rate scheduler config used to register LrUpdater hook
    policy='step',  # The policy of scheduler, also support CosineAnnealing, Cyclic, etc. Refer to details of supported LrUpdater from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/lr_updater.py#L9.
    warmup='linear',  # warmup的策略, 还支持 `exp` 和 `constant`.
    warmup_iters=500,  # warmup的迭代次数
    warmup_ratio=
    0.001,  # 用于warmup的起始学习比率
    step=[8, 11])  # 学习率进行衰减的step位置
total_epochs = 12  # model训练的总epoch数
 
checkpoint_config = dict(  # 设置checkpoint hook, 具体细节请参照https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/hooks/checkpoint.py 的实现.
    interval=1)  # 每隔几个epoch保存一下checkpoint
 
log_config = dict(  # logger文件的配置
    interval=50,  # 每隔多少个epoch输出一个log文件
    hooks=[
        # dict(type='TensorboardLoggerHook')  # MMDetection支持Tensorboard logger
        dict(type='TextLoggerHook')
    ])  # logger 被用来记录训练过程.
dist_params = dict(backend='nccl')  # 设置分布式训练的参数,也可以设置端口。
log_level = 'INFO'  # The level of logging.
load_from = None  # 给出之前预训练模型checkpoint的路径,这个不会resume training(resume training会按照上次的记录接着训练,而这个参数应该只是导入之前预训练模型参数,重新训练)
resume_from = None  # 给出需要Resume 的checkpoints的路径, 它将会接着上次被保存的地方进行训练。
workflow = [('train', 1)]  # Workflow for runner. [('train', 1)] means there is only one workflow and the workflow named 'train' is executed once. The workflow trains the model by 12 epochs according to the total_epochs.(这个workflow具体是干什么的我不是很清楚orz)
work_dir = 'work_dir'  # 保存模型的文件夹路径(checkpoints和log文件都会保存在其中)。
FAQ
1、忽略基础配置文件中的部分字段
有些时候,你可以在配置文件中设置_delete_=True来忽略基础配置文件中的部分字段。在MMDetection中,我们以更改Mask-RCNN的backbone为例:

# 原配置文件
model = dict(
    type='MaskRCNN',
    pretrained='torchvision://resnet50',
    backbone=dict(
        type='ResNet',
        depth=50,
        num_stages=4,
        out_indices=(0, 1, 2, 3),
        frozen_stages=1,
        norm_cfg=dict(type='BN', requires_grad=True),
        norm_eval=True,
        style='pytorch'),
    neck=dict(...),
    rpn_head=dict(...),
    roi_head=dict(...))
在backbone中以HRNet来替换ResNet,因为HRNet的keywords结构和ResNet的有所不同,所以需要设置_delete_=True来忽略ResNet中的部分字段:

# 继承父类配置文件
_base_ = '../mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py'
model = dict(
    pretrained='open-mmlab://msra/hrnetv2_w32',
    backbone=dict(
        # 忽略父类配置文件中的keywords    _delete_=True将会使用新的keys取代backbone中的旧keys
        _delete_=True,
        type='HRNet',
        # 设置自己定义的keywords
        extra=dict(
            stage1=dict(
                num_modules=1,
                num_branches=1,
                block='BOTTLENECK',
                num_blocks=(4, ),
                num_channels=(64, )),
            stage2=dict(
                num_modules=1,
                num_branches=2,
                block='BASIC',
                num_blocks=(4, 4),
                num_channels=(32, 64)),
            stage3=dict(
                num_modules=4,
                num_branches=3,
                block='BASIC',
                num_blocks=(4, 4, 4),
                num_channels=(32, 64, 128)),
            stage4=dict(
                num_modules=3,
                num_branches=4,
                block='BASIC',
                num_blocks=(4, 4, 4, 4),
                num_channels=(32, 64, 128, 256)))),
    neck=dict(...))
2、在配置文件中使用中间变量
有些时候在配置文件中会使用一些中间变量,比如datasets配置中的train_pipeline/test_pipeline。值得注意的是,当在子配置中修改中间变量时,使用者需要再次将中间变量传递到相应的字段中。我们以多尺度策略训练Mask-RCNN为例。train_pipeline/test_pipeline是我们需要改的中间变量。

_base_ = './mask_rcnn_r50_fpn_1x_coco.py'
img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
# 更改中间变量train_pipeline
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True, with_mask=True),
    dict(
        type='Resize',
        img_scale=[(1333, 640), (1333, 672), (1333, 704), (1333, 736),
                   (1333, 768), (1333, 800)],
        multiscale_mode="value",
        keep_ratio=True),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size_divisor=32),
    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks']),
]
# 更改中间变量test_pipeline
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        img_scale=(1333, 800),
        flip=False,
        transforms=[
            dict(type='Resize', keep_ratio=True),
            dict(type='RandomFlip'),
            dict(type='Normalize', **img_norm_cfg),
            dict(type='Pad', size_divisor=32),
            dict(type='ImageToTensor', keys=['img']),
            dict(type='Collect', keys=['img']),
        ])
]
data = dict(
    # 这个地方直接使用中间变量赋值
    train=dict(pipeline=train_pipeline),
    val=dict(pipeline=test_pipeline),
    test=dict(pipeline=test_pipeline))
这是我自己在看MMDetection2的英文文档过程中,根据自己的理解进行翻译的,后续再对一些细节进行补充。(反正需要自己过一遍英文文档,不如写篇博客记录一下Ծ‸Ծ)。如有问题,欢迎大家在评论区拍砖!
原文链接:https://blog.csdn.net/foolishpeng/article/details/109802096

转载自:https://blog.csdn.net/foolishpeng/article/details/109802096?spm=1001.2014.3001.5501

标签:pipeline,img,True,mask,dict,讲解,MMDetection,网络结构,type
来源: https://blog.csdn.net/qq_39328536/article/details/121417786

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有