【mmdetection实践】(二)训练自己的网络

本文介绍了mmdetection框架中分布式和非分布式训练模式的使用及流程。在distributed模式下,通过dist_train.sh进行训练,而在非distributed模式下,直接调用train.py。训练过程涉及tools/train.py、mmdet/apis/train.py和mmcv/runner/runner.py。测试阶段同样分为distributed和non-distributed,主要在tools/test.py中进行。

Train

mmdetection支持多卡训练,有两种模式,分别是distributed模式和非distributed模式。官方推荐使用distributed模式。

distributed模式

那我们先讲一下distributed模式,mmdetection是使用tools/dist_train.sh来实现。其使用方法是如下:

./tools/dist_train.sh ${
   
   CONFIG_FILE} ${
   
   GPU_NUM} [optional arguments]
# CONFIG_FILE是指模型的参数文件,例如: ./configs/faster_rcnn_r50_fpn_1x.py
# GPU_NUM是指使用GPU个数
# optional arguments其中可以使用的有:“--validate”,这个表示在trian的过程中使用val数据集进行验证

其中--validate的默认值是1个epoch进行一次validation,如果需要修改,在模型参数文件中加入如下

# 例如在./configs/faster_rcnn_r50_fpn_1x.py加入如下
evaluation = dict(interval=1)

打开dist_train.sh文件,可以看到其实还是调用tools/train.py

但由于我在电脑上跑dist_train.sh总是卡住,也不知道原因,所以我就尝试了非distributed的模式。

非distributed模式

非distributed模式就直接调用tools/train.py就可以,调用格式如下:

python tools/train.py ${
   
   CONFIG_FILE}
# CONFIG_FILE是指模型的参数文件,例如: ./configs/faster_rcnn_r50_fpn_1x.py

需要注意的有如下:

  • 在官方推荐中,这个训练方式是单卡训练
  • 在官方文档中,这个训练方式没有像dist_train.sh的optional arguments

train过程的追寻

这个解释过程是要从tools/train.py → \rightarrow mmdet/apis/train.py → \rightarrow mmcv/runner/runner.py

tools/train.py

想要了解训练过程,就需要仔细地看一下train.py中的内容

# tools/train.py
def main():
    args = parse_args()
    cfg = Config.fromfile(args.config)
    # set cudnn_benchmark
    if cfg.get('cudnn_benchmark', False):
        torch.backends.cudnn.benchmark = True
    # update configs according to CLI args
    if args.work_dir is not None:
        cfg.work_dir = args.work_dir
    if args.resume_from is not None:
        cfg.resume_from = args.resume_from
    cfg.gpus = args.gpus
    if args.autoscale_lr:
        # apply the linear scaling rule (https://arxiv.org/abs/1706.02677)
        cfg.optimizer['lr'] = cfg.optimizer['lr'] * cfg.gpus / 8

    # init distributed env first, since logger depends on the dist info.
    if args.launcher == 'none':
        distributed = False
    else:
        distributed = True
        init_dist(args.launcher, **cfg.dist_params)

    # init logger before other steps
    logger = get_root_logger(cfg.log_level)
    logger.info('Distributed training: {}'.format(distributed))

    # set random seeds
    if args.seed is not None:
        logger.info('Set random seed to {}'.format(args.seed))
        set_random_seed(args.seed)
    
    #构建模型,其中cfg.model包含着模型的各种参数,加载自CONFIG_FILE
    model = build_detector(
        cfg.model, train_cfg=cfg.train_cfg, test_cfg=cfg.test_cfg)
    
    #构建训练数据集
    datasets = [build_dataset(cfg.data.train)]
    if len
### 使用 MMDetection 进行自定义数据集的语义分割训练 #### 修改配置文件 为了使 MMDetection 支持新的自定义数据集,需要创建或调整现有的配置文件。这涉及到设置数据集路径、类别数目以及可能的其他特定于数据集的信息。 对于 Pascal VOC 类型的数据集,在配置文件中指定这些细节是至关重要的[^1]。例如: ```python data_root = 'path/to/dataset/' classes = ('background', 'class1', 'class2') # 自定义分类标签列表 num_classes = len(classes) dataset_type = 'VOCDataset' 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 + 'ImageSets/Main/trainval.txt' ], img_prefix=data_root, pipeline=train_pipeline)), val=dict( type=dataset_type, ann_file=data_root + 'ImageSets/Main/test.txt', img_prefix=data_root, pipeline=test_pipeline), test=dict( type=dataset_type, ann_file=data_root + 'ImageSets/Main/test.txt', img_prefix=data_root, pipeline=test_pipeline)) ``` 需要注意的是,上述代码片段假设使用了类似于 Pascal VOC 的标注方式;如果是 COCO 或者其他格式,则需相应地改变 `type` 参数和其他字段的内容。 #### 数据预处理 MMDetection 提供了一套完整的工具用于加载并准备输入给神经网络的数据。针对不同类型的变换操作(比如随机裁剪、翻转),可以通过修改配置文件内的 `pipeline` 字段来进行定制化的预处理工作。下面是一个简单的例子展示如何添加一些常见的图像增强方法: ```python train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=False), # 如果有mask则设为True dict(type='Resize', img_scale=(1000, 600), 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']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1000, 600), 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']) ]) ] ``` 这里展示了两种不同的管道——一种适用于训练阶段 (`train_pipeline`) ,另一种则是测试时使用的 (`test_pipeline`). 特别注意 `with_mask` 参数的选择取决于是否有实例级别的掩码信息可用。 #### 模型调参最佳实践 当基于一个新的数据集微调现有模型时,除了更新配置文件中外,还需要考虑几个方面来优化性能: - 更改最后一层全连接层或其他负责预测部分组件中的输出单元数量以匹配新任务所需的类别数[^3]. - 对学习率衰减策略做出适当调整,因为较大的初始学习率可能导致过拟合现象发生. - 尝试种正则化技术如权重衰减(dropout),防止过度拟合问题. - 利用交叉验证的方法寻找最优超参数组合. 最后一点值得注意的是,在实际应用过程中应当依据具体情况进行灵活调整而不是盲目遵循固定的规则.
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值