MMdetection解读系列之backbone-resnet

本文深入解析ResNet网络结构,包括ResNet的BasicBlock和Bottleneck Block,参数解读,初始化方法,如何添加额外操作,冻结网络stage的技巧以及前向传播过程。此外,还提供了在实际应用中改造和训练ResNet的参考指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

科普知识

ResNet

Resnet
mmdetection中实现此结构

   arch_settings = {
        18: (BasicBlock, (2, 2, 2, 2)),
        34: (BasicBlock, (3, 4, 6, 3)),
        50: (Bottleneck, (3, 4, 6, 3)),
        101: (Bottleneck, (3, 4, 23, 3)),
        152: (Bottleneck, (3, 8, 36, 3))
    }
    # 注意BasicBlock Bottleneck均为一个类

RestNet 18/34采用BasicBlock作为基本单元,而ResNet 50/101/152采用Bottlenet Block作为基本单元
Block
Basic Block就是左边的图,包括两个3×3的卷积操作。bollteneck是右边的图,为了减少参数,它采用了两个1×1的卷积。

参数解读

""ResNet backbone.

    Args:
        depth (int): Depth of resnet, from {18, 34, 50, 101, 152}. ResNet深度,总所周知,常用的为50,101
        stem_channels (int | None): Number of stem channels. If not specified,
            it will be the same as `base_channels`. Default: None.
        base_channels (int): Number of base channels of res layer. Default: 64. 众所周知,这个为64详情见Resnet Conv1
        in_channels (int): Number of input image channels. Default: 3.众所周知
        num_stages (int): Resnet stages. Default: 4.众所周知 详情见conv1_x conv2_x .......称为一个stage
        strides (Sequence[int]): Strides of the first block of each stage.众所周知  每个stage第一个block的步长
        dilations (Sequence[int]): Dilation of each stage.众所周知,用于空洞卷积
        out_indices (Sequence[int]): Output from which stages. 众所周知,每个stage的输出
        style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two ##使用的是pytorch/caffe关系到使用3*3/1*1的卷积
            layer is the 3x3 conv layer, otherwise the stride-two layer is ##在步长为2时
            the first 1x1 conv layer.
        deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv ##在初始的时候即conv1使用3*3的卷积替代7*7的卷积
        avg_down (bool): Use AvgPool instead of stride conv when
            downsampling in the bottleneck.## 使用平均池化替代卷积下采样 H=ceil((H-F+2*P)/S+1)
        frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
            -1 means not freezing any parameters. ##从stage4开始冻结几个stage拒绝梯度传播更新参数
        norm_cfg (dict): Dictionary to construct and config norm layer.## 正则化方式
        norm_eval (bool): Whether to set norm layers to eval mode, namely,## 用于测试模型时,将正则化设置为false,
            freeze running stats (mean and var). Note: Effect on Batch Norm
            and its variants only.
        plugins (list[dict]): List of plugins for stages, each dict contains: ##扩展模块

            - cfg (dict, required): Cfg dict to build plugin.## 需要扩展哪些操作,比如说dfn
            - position (str, required): Position inside block to insert ##在那里插入这个操作,参数为opsName
              plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.
            - stages (tuple[bool], optional): Stages to apply plugin, length ## 在哪一个stage使用这个操作
              should be same as 'num_stages'.
        with_cp (bool): Use checkpoint or not. Using checkpoint will save some
            memory while slowing down the training speed. ## 众所周知checkpoint,看个人需求。
        zero_init_residual (bool): Whether to use zero init for last norm layer
            in resblocks to let them behave as identity.## 不知道

Resnet初始化

    def __init__(self,
                 depth,
                 in_channels
### 如何使用 MMDetection 3.0 训练 Faster R-CNN 模型 #### 安装依赖环境 为了确保能够顺利安装并运行 MMDetection,建议先创建一个新的虚拟环境来管理所需的 Python 包版本。可以采用 Conda 或者 virtualenv 工具完成这一步骤。 接着按照官方文档说明安装 PyTorch 及其对应的 CUDA 版本[^1]。之后通过 pip 命令安装 MMDetection: ```bash pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu113/torch1.9/index.html git clone https://github.com/open-mmlab/mmdetection.git cd mmdetection pip install -e . ``` 上述命令会下载最新版的 MMDetection 并将其设置为可编辑模式以便于后续修改配置文件或其他操作。 #### 配置数据集路径 对于自定义的数据集来说,通常需要调整默认配置中的 dataset 字段指向本地存储位置。假设已经准备好 COCO 格式的标注文件,则可以在 config 文件里指定如下参数: ```yaml data_root = 'path/to/your/dataset/' classes = ('nodule',) dataset_type = 'CocoDataset' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ ... ] test_pipeline = [ ... ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type='RepeatDataset', times=3, dataset=dict( type=dataset_type, ann_file=data_root + 'annotations/train.json', img_prefix=data_root + 'images/', pipeline=train_pipeline)), val=dict( type=dataset_type, ann_file=data_root + 'annotations/val.json', img_prefix=data_root + 'images/', pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'annotations/test.json', img_prefix=data_root + 'images/', pipeline=test_pipeline)) evaluation = dict(interval=1, metric='bbox') ``` 这段 YAML 文档展示了如何设定训练、验证以及测试阶段使用的图片目录和 JSON 注解文件的位置,并指定了图像预处理方式和其他超参选项[^4]。 #### 修改模型结构与初始化权重 如果打算沿用 Faster R-CNN 的标准设计而仅替换骨干网络或者其他组件的话,可以直接继承现有的配置模板并做适当改动即可。比如要加载 ResNet-50 作为特征提取器时,只需简单更改 backbone 和 pretrained 属性值就可以实现这一点。 另外值得注意的是,在实际实验过程中往往还需要考虑迁移学习的因素——即利用 ImageNet 上面预训练好的权值来进行微调从而加速收敛过程并提高泛化能力。因此一般会在配置项中加入 `pretrained` 参数以指示从何处导入这些初始参数。 ```python model = dict( type='FasterRCNN', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=-1, norm_eval=False, style='pytorch'), neck=dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=0, add_extra_convs='on_output', num_outs=5), rpn_head=dict(...), roi_head=dict(...) ) load_from = "https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth" ``` 这里给出了一个完整的 Faster R-CNN 构建方案,其中包含了 FPN(Feature Pyramid Network)模块用于多尺度融合;同时也提供了具体的 checkpoint URL 地址供下载官方提供的预训练模型进行热启动。 #### 启动训练流程 当所有的准备工作都完成后,便可以通过 shell 脚本来触发整个训练周期。下面给出了一条典型的指令用来启动单卡或多卡分布式训练作业: ```shell ./tools/dist_train.sh configs/faster_rcnn/faster_rcnn_r50_fpn_1x_lung_nodules.py 1 --validate --work-dir work_dirs/faster_rcnn_r50_fpn_1x_lung_nodules/ ``` 这条命令将会读取位于 `configs/faster_rcnn/faster_rcnn_r50_fpn_1x_lung_nodules.py` 下保存的具体配置信息,并分配给编号为 0 的 GPU 来负责计算任务。同时开启了中间验证环节并且设置了工作空间存放日志记录及其他输出产物。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值