当前位置:   article > 正文

旋转框目标检测mmrotate v1.0.0rc1 之RTMDet训练DOTA(二)_cspnext_pafpn

cspnext_pafpn

1、模型rotated_rtmdet的论文链接与配置文件

注意

我们按照 DOTA 评测服务器的最新指标,原来的 voc 格式 mAP 现在是 mAP50。

IN表示ImageNet预训练,COCO表示COCO预训练

与报告不同的是,这里的推理速度是在 NVIDIA 2080Ti GPU 上测量的,配备 TensorRT 8.4.3、cuDNN 8.2.0、FP16、batch size=1 和 NMS。

2、修改RTMDet-tiny的配置文件

  1. 基础配置文件:rotated_rtmdet_l-3x-dota.py

  1. _base_ = [
  2. './_base_/default_runtime.py', './_base_/schedule_3x.py',
  3. './_base_/dota_rr.py'
  4. ]
  5. checkpoint = 'https://download.openmmlab.com/mmdetection/v3.0/rtmdet/cspnext_rsb_pretrain/cspnext-l_8xb256-rsb-a1-600e_in1k-6a760974.pth' # noqa
  6. angle_version = 'le90'
  7. model = dict(
  8. type='mmdet.RTMDet',
  9. data_preprocessor=dict(
  10. type='mmdet.DetDataPreprocessor',
  11. mean=[103.53, 116.28, 123.675],
  12. std=[57.375, 57.12, 58.395],
  13. bgr_to_rgb=False,
  14. boxtype2tensor=False,
  15. batch_augments=None),
  16. backbone=dict(
  17. type='mmdet.CSPNeXt',
  18. arch='P5',
  19. expand_ratio=0.5,
  20. deepen_factor=1,
  21. widen_factor=1,
  22. channel_attention=True,
  23. norm_cfg=dict(type='SyncBN'),
  24. act_cfg=dict(type='SiLU'),
  25. init_cfg=dict(
  26. type='Pretrained', prefix='backbone.', checkpoint=checkpoint)),
  27. neck=dict(
  28. type='mmdet.CSPNeXtPAFPN',
  29. in_channels=[256, 512, 1024],
  30. out_channels=256,
  31. num_csp_blocks=3,
  32. expand_ratio=0.5,
  33. norm_cfg=dict(type='SyncBN'),
  34. act_cfg=dict(type='SiLU')),
  35. bbox_head=dict(
  36. type='RotatedRTMDetSepBNHead',
  37. num_classes=15,
  38. in_channels=256,
  39. stacked_convs=2,
  40. feat_channels=256,
  41. angle_version=angle_version,
  42. anchor_generator=dict(
  43. type='mmdet.MlvlPointGenerator', offset=0, strides=[8, 16, 32]),
  44. bbox_coder=dict(
  45. type='DistanceAnglePointCoder', angle_version=angle_version),
  46. loss_cls=dict(
  47. type='mmdet.QualityFocalLoss',
  48. use_sigmoid=True,
  49. beta=2.0,
  50. loss_weight=1.0),
  51. loss_bbox=dict(type='RotatedIoULoss', mode='linear', loss_weight=2.0),
  52. with_objectness=False,
  53. exp_on_reg=True,
  54. share_conv=True,
  55. pred_kernel_size=1,
  56. use_hbbox_loss=False,
  57. scale_angle=False,
  58. loss_angle=None,
  59. norm_cfg=dict(type='SyncBN'),
  60. act_cfg=dict(type='SiLU')),
  61. train_cfg=dict(
  62. assigner=dict(
  63. type='mmdet.DynamicSoftLabelAssigner',
  64. iou_calculator=dict(type='RBboxOverlaps2D'),
  65. topk=13),
  66. allowed_border=-1,
  67. pos_weight=-1,
  68. debug=False),
  69. test_cfg=dict(
  70. nms_pre=2000,
  71. min_bbox_size=0,
  72. score_thr=0.05,
  73. nms=dict(type='nms_rotated', iou_threshold=0.1),
  74. max_per_img=2000),
  75. )
  76. # batch_size = (2 GPUs) x (4 samples per GPU) = 8
  77. train_dataloader = dict(batch_size=4, num_workers=4)
  1. 修改数据集路径信息——'./_base_/dota_rr.py'

更改数据集基础路径及训练、验证和测试路径、以及影像切片的大小

  1. 修改训练数据的类别数——rotated_rtmdet_l-3x-dota.py

  1. 修改线程和batch_size('./_base_/dota_rr.py')

'./_base_/dota_rr.py'

rotated_rtmdet_l-3x-dota.py

4.修改训练epoches('./_base_/schedule_3x.py')

5.修改模型训练的日志打印和load from 加载与训练模型(configs_base_/default_runtime.py)

6.修改模型model的与训练模型路径

7.修改数据集的类别名称(mmrotate\datasets\dota.py)

8、修改图像数据集的后缀和图片大小(修改mmrotate/mmrotate/datasets/dota.py)

  1. 整个配置文件

  1. default_scope = 'mmrotate'
  2. default_hooks = dict(
  3. timer=dict(type='IterTimerHook'),
  4. logger=dict(type='LoggerHook', interval=50),
  5. param_scheduler=dict(type='ParamSchedulerHook'),
  6. checkpoint=dict(type='CheckpointHook', interval=12, max_keep_ckpts=3),
  7. sampler_seed=dict(type='DistSamplerSeedHook'),
  8. visualization=dict(type='mmdet.DetVisualizationHook'))
  9. env_cfg = dict(
  10. cudnn_benchmark=False,
  11. mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
  12. dist_cfg=dict(backend='nccl'))
  13. vis_backends = [dict(type='LocalVisBackend')]
  14. visualizer = dict(
  15. type='RotLocalVisualizer',
  16. vis_backends=[dict(type='LocalVisBackend')],
  17. name='visualizer')
  18. log_processor = dict(type='LogProcessor', window_size=50, by_epoch=True)
  19. log_level = 'INFO'
  20. load_from = '/media/lhy/mmrotate-1.0.0rc1/checkpoints/RTMDet/rotated_rtmdet_tiny-3x-dota-9d821076.pth'
  21. resume = False
  22. custom_hooks = [
  23. dict(type='mmdet.NumClassCheckHook'),
  24. dict(
  25. type='EMAHook',
  26. ema_type='mmdet.ExpMomentumEMA',
  27. momentum=0.0002,
  28. update_buffers=True,
  29. priority=49)#在训练时对模型进行指数移动平均运算,目的是提高模型的鲁棒性
  30. ]
  31. max_epochs = 36
  32. base_lr = 0.00025
  33. interval = 12
  34. train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=36, val_interval=12)
  35. val_cfg = dict(type='ValLoop')
  36. test_cfg = dict(type='TestLoop')
  37. param_scheduler = [
  38. dict(
  39. type='LinearLR', start_factor=1e-05, by_epoch=False, begin=0,
  40. end=1000),
  41. dict(
  42. type='CosineAnnealingLR',
  43. eta_min=1.25e-05,
  44. begin=18,
  45. end=36,
  46. T_max=18,
  47. by_epoch=True,
  48. convert_to_iter_based=True)
  49. ]
  50. optim_wrapper = dict(
  51. type='OptimWrapper',#标准的单精度训练
  52. optimizer=dict(type='AdamW', lr=0.00025, weight_decay=0.05),
  53. paramwise_cfg=dict(
  54. norm_decay_mult=0, bias_decay_mult=0, bypass_duplicate=True))
  55. #paramwise_cfg可以设置参数
  56. #lr_mult:所有参数的学习率。
  57. #decay_mult:所有参数的衰减系数。
  58. #bias_lr_mult:偏置的学习率系数(不包括归一化层的偏置和可变形卷积的偏置)。
  59. #bias_decay_mult:偏差的权重衰减系数(不包括归一化层的偏差和可变形卷积的偏移量)。
  60. #norm_decay_mult:归一化层的权重和偏差的权重衰减系数。
  61. #flat_decay_mult:一维参数的权重衰减系数。
  62. #dwconv_decay_mult:深度卷积的衰减系数。
  63. #bypass_duplicate: 是否跳过重复参数,默认为False.
  64. #dcn_offset_lr_mult:可变形卷积的学习率。
  65. dataset_type = 'DOTADataset'
  66. data_root = 'data/DOTA/optship1280/'
  67. file_client_args = dict(backend='disk')
  68. train_pipeline = [
  69. dict(
  70. type='mmdet.LoadImageFromFile', file_client_args=dict(backend='disk')),
  71. dict(type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
  72. dict(type='ConvertBoxType', box_type_mapping=dict(gt_bboxes='rbox')),
  73. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  74. dict(
  75. type='mmdet.RandomFlip',
  76. prob=0.75,
  77. direction=['horizontal', 'vertical', 'diagonal']),
  78. dict(
  79. type='RandomRotate',
  80. prob=0.5,
  81. angle_range=180,
  82. rect_obj_labels=[9, 11]),
  83. dict(
  84. type='mmdet.Pad', size=(1280, 1280),
  85. pad_val=dict(img=(114, 114, 114))),
  86. dict(type='mmdet.PackDetInputs')
  87. ]
  88. val_pipeline = [
  89. dict(
  90. type='mmdet.LoadImageFromFile', file_client_args=dict(backend='disk')),
  91. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  92. dict(type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
  93. dict(type='ConvertBoxType', box_type_mapping=dict(gt_bboxes='rbox')),
  94. dict(
  95. type='mmdet.Pad', size=(1280, 1280),
  96. pad_val=dict(img=(114, 114, 114))),
  97. dict(
  98. type='mmdet.PackDetInputs',
  99. meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
  100. 'scale_factor'))
  101. ]
  102. test_pipeline = [
  103. dict(
  104. type='mmdet.LoadImageFromFile', file_client_args=dict(backend='disk')),
  105. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  106. dict(
  107. type='mmdet.Pad', size=(1280, 1280),
  108. pad_val=dict(img=(114, 114, 114))),
  109. dict(
  110. type='mmdet.PackDetInputs',
  111. meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
  112. 'scale_factor'))
  113. ]
  114. train_dataloader = dict(
  115. batch_size=8,
  116. num_workers=8,
  117. persistent_workers=True,
  118. sampler=dict(type='DefaultSampler', shuffle=True),
  119. batch_sampler=None,
  120. pin_memory=False,
  121. dataset=dict(
  122. type='DOTADataset',
  123. data_root='data/DOTA/optship1280/',
  124. ann_file='trainval/obb_annfiles/',
  125. data_prefix=dict(img_path='trainval/images/'),
  126. img_shape=(1280, 1280),
  127. filter_cfg=dict(filter_empty_gt=True),
  128. pipeline=[
  129. dict(
  130. type='mmdet.LoadImageFromFile',
  131. file_client_args=dict(backend='disk')),
  132. dict(
  133. type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
  134. dict(
  135. type='ConvertBoxType',
  136. box_type_mapping=dict(gt_bboxes='rbox')),
  137. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  138. dict(
  139. type='mmdet.RandomFlip',
  140. prob=0.75,
  141. direction=['horizontal', 'vertical', 'diagonal']),
  142. dict(
  143. type='RandomRotate',
  144. prob=0.5,
  145. angle_range=180,
  146. rect_obj_labels=[9, 11]),
  147. dict(
  148. type='mmdet.Pad',
  149. size=(1280, 1280),
  150. pad_val=dict(img=(114, 114, 114))),
  151. dict(type='mmdet.PackDetInputs')
  152. ]))
  153. val_dataloader = dict(
  154. batch_size=1,
  155. num_workers=2,
  156. persistent_workers=True,
  157. drop_last=False,
  158. sampler=dict(type='DefaultSampler', shuffle=False),
  159. dataset=dict(
  160. type='DOTADataset',
  161. data_root='data/DOTA/optship1280/',
  162. ann_file='trainval/obb_annfiles/',
  163. data_prefix=dict(img_path='trainval/images/'),
  164. img_shape=(1280, 1280),
  165. test_mode=True,
  166. pipeline=[
  167. dict(
  168. type='mmdet.LoadImageFromFile',
  169. file_client_args=dict(backend='disk')),
  170. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  171. dict(
  172. type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
  173. dict(
  174. type='ConvertBoxType',
  175. box_type_mapping=dict(gt_bboxes='rbox')),
  176. dict(
  177. type='mmdet.Pad',
  178. size=(1280, 1280),
  179. pad_val=dict(img=(114, 114, 114))),
  180. dict(
  181. type='mmdet.PackDetInputs',
  182. meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
  183. 'scale_factor'))
  184. ]))
  185. test_dataloader = dict(
  186. batch_size=1,
  187. num_workers=2,
  188. persistent_workers=True,
  189. drop_last=False,
  190. sampler=dict(type='DefaultSampler', shuffle=False),
  191. dataset=dict(
  192. type='DOTADataset',
  193. data_root='data/DOTA/optship1280/',
  194. ann_file='val/obb_annfiles/',
  195. data_prefix=dict(img_path='val/images/'),
  196. img_shape=(1280, 1280),
  197. test_mode=True,
  198. pipeline=[
  199. dict(
  200. type='mmdet.LoadImageFromFile',
  201. file_client_args=dict(backend='disk')),
  202. dict(type='mmdet.Resize', scale=(1280, 1280), keep_ratio=True),
  203. dict(
  204. type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
  205. dict(
  206. type='ConvertBoxType',
  207. box_type_mapping=dict(gt_bboxes='rbox')),
  208. dict(
  209. type='mmdet.Pad',
  210. size=(1280, 1280),
  211. pad_val=dict(img=(114, 114, 114))),
  212. dict(
  213. type='mmdet.PackDetInputs',
  214. meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
  215. 'scale_factor'))
  216. ]))
  217. val_evaluator = dict(type='DOTAMetric', metric='mAP')#评估数据类型与指标
  218. test_evaluator = dict(type='DOTAMetric', metric='mAP')
  219. checkpoint = '/media/lhy/mmrotate-1.0.0rc1/work_dirs/pretrain/cspnext-tiny_imagenet_600e.pth'
  220. angle_version = 'le90'
  221. model = dict(
  222. type='mmdet.RTMDet',
  223. data_preprocessor=dict(
  224. type='mmdet.DetDataPreprocessor',
  225. mean=[103.53, 116.28, 123.675],
  226. std=[57.375, 57.12, 58.395],
  227. bgr_to_rgb=False,
  228. boxtype2tensor=False,
  229. batch_augments=None),
  230. backbone=dict(
  231. type='mmdet.CSPNeXt',
  232. arch='P5',
  233. expand_ratio=0.5,
  234. deepen_factor=0.167,
  235. widen_factor=0.375,
  236. channel_attention=True,
  237. norm_cfg=dict(type='SyncBN'),
  238. act_cfg=dict(type='SiLU'),
  239. init_cfg=dict(
  240. type='Pretrained',
  241. prefix='backbone.',
  242. checkpoint=
  243. '/media/lhy/mmrotate-1.0.0rc1/work_dirs/pretrain/cspnext-tiny_imagenet_600e.pth'
  244. )),
  245. neck=dict(
  246. type='mmdet.CSPNeXtPAFPN',
  247. in_channels=[96, 192, 384],
  248. out_channels=96,
  249. num_csp_blocks=1,
  250. expand_ratio=0.5,
  251. norm_cfg=dict(type='SyncBN'),
  252. act_cfg=dict(type='SiLU')),
  253. bbox_head=dict(
  254. type='RotatedRTMDetSepBNHead',
  255. num_classes=22,
  256. in_channels=96,
  257. stacked_convs=2,
  258. feat_channels=96,
  259. angle_version='le90',
  260. anchor_generator=dict(
  261. type='mmdet.MlvlPointGenerator', offset=0, strides=[8, 16, 32]),
  262. bbox_coder=dict(type='DistanceAnglePointCoder', angle_version='le90'),
  263. loss_cls=dict(
  264. type='mmdet.QualityFocalLoss',
  265. use_sigmoid=True,
  266. beta=2.0,
  267. loss_weight=1.0),
  268. loss_bbox=dict(type='RotatedIoULoss', mode='linear', loss_weight=2.0),
  269. with_objectness=False,
  270. exp_on_reg=False,
  271. share_conv=True,
  272. pred_kernel_size=1,
  273. use_hbbox_loss=False,
  274. scale_angle=False,
  275. loss_angle=None,
  276. norm_cfg=dict(type='SyncBN'),
  277. act_cfg=dict(type='SiLU')),
  278. train_cfg=dict(
  279. assigner=dict(
  280. type='mmdet.DynamicSoftLabelAssigner',
  281. iou_calculator=dict(type='RBboxOverlaps2D'),
  282. topk=13),
  283. allowed_border=-1,
  284. pos_weight=-1,
  285. debug=False),
  286. test_cfg=dict(
  287. nms_pre=2000,
  288. min_bbox_size=0,
  289. score_thr=0.05,
  290. nms=dict(type='nms_rotated', iou_threshold=0.1),
  291. max_per_img=2000))
  292. launcher = 'none'
  293. work_dir = 'work_dirs/runs/train/rtmdet_tiny_rrship/'

3、模型训练

1、Train with a single GPU

python tools/train.py ${CONFIG_FILE} [optional arguments]
如果你想在命令中指定工作目录,你可以添加一个参数–work_dir $[YOUR_WORK_DIR]。

2、Train with multiple GPUs

./tools/dist_train.sh ${CONFIG_FILE} ${GPU_NUM} [optional arguments]
Optional arguments are:
–no-validate (not suggested): By default, the codebase will perform evaluation during the training. To disable this behavior, use --no-validate.
–work-dir ${WORK_DIR}: Override the working directory specified in the config file.
–resume-from ${CHECKPOINT_FILE}: Resume from a previous checkpoint file.
Difference between resume-from and load-from: resume-from loads both the model weights and optimizer status, and the epoch is also inherited from the specified checkpoint. It is usually used for resuming the training process that is interrupted accidentally. load-from only loads the model weights and the training epoch starts from 0. It is usually used for finetuning.

3、Train with multiple machines

•如果你启动了多台连接以太网的机器,你可以简单地运行以下命令:

On the first machine:

NNODES=2 NODE_RANK=0 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS

On the second machine:

NNODES=2 NODE_RANK=1 PORT=$MASTER_PORT MASTER_ADDR=$MASTER_ADDR sh tools/dist_train.sh $CONFIG $GPUS

如果你没有像InfiniBand这样的高速网络,通常会很慢。

4、Manage jobs with Slurm

如果在由slurm管理的集群上运行MMRotate,可以使用脚本slurm_train.sh。(此脚本也支持单机训练。)

[GPUS=${GPUS}] ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} ${CONFIG_FILE} ${WORK_DIR}

如果您有多台机器与以太网连接,您可以参考PyTorch启动实用程序添加链接描述。如果你没有像InfiniBand这样的高速网络,通常会很慢

5、在一台机器上启动多个作业

如果您在一台机器上启动多个作业,例如,在一台有8个gpu的机器上启动2个4-GPU训练的作业,您需要为每个作业指定不同的端口(默认为29500),以避免通信冲突。

If you use dist_train.sh to launch training jobs, you can set the port in commands.

  1. CUDA_VISIBLE_DEVICES=0,1,2,3 PORT=29500 ./tools/dist_train.sh ${CONFIG_FILE} 4
  2. CUDA_VISIBLE_DEVICES=4,5,6,7 PORT=29501 ./tools/dist_train.sh ${CONFIG_FILE} 4

如果使用Slurm启动培训作业,则需要修改配置文件(通常是配置文件中倒数第6行)以设置不同的通信端口。

In config1.py,

dist_params = dict(backend=‘nccl’, port=29500)

In config2.py,

dist_params = dict(backend=‘nccl’, port=29501)

Then you can launch two jobs with config1.py and config2.py.

  1. CUDA_VISIBLE_DEVICES=0,1,2,3 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config1.py ${WORK_DIR}
  2. CUDA_VISIBLE_DEVICES=4,5,6,7 GPUS=4 ./tools/slurm_train.sh ${PARTITION} ${JOB_NAME} config2.py ${WORK_DIR}

6、开始启动模型训练

1、启动模型训练命令

python tools/train.py  configs/rotated_rtmdet/rotated_rtmdet_tiny-3x-dota.py --work-dir work_dirs/runs/train/rtmdet_tiny_rrship/

2、模型训练结果


模型验证发现模型检测的目标远远多于真实的目标,我们修改配置文件的训练数据集路径为trainval,扩大训练样本。

4、mmrotate模型测试

修改模型测试评估的域值map(mmrotate/evaluation/metrics/dota_metric.py)

模型默认的iou阈值为0.5,可以修改为0.75等。

single GPU

single node multiple GPU

multiple node

可以使用以下命令推断数据集。

  1. # single-gpu
  2. python tools/test.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [optional arguments]
  3. # multi-gpu
  4. ./tools/dist_test.sh ${CONFIG_FILE} ${CHECKPOINT_FILE} ${GPU_NUM} [optional arguments]
  5. # multi-node in slurm environment
  6. python tools/test.py ${CONFIG_FILE} ${CHECKPOINT_FILE} [optional arguments] --launcher slurm

例子:

在DOTA-1.0数据集上推理RotatedRetinaNet,可以生成压缩文件在线提交。(请先更改data_root。)

  1. python ./tools/test.py \
  2. configs/rotated_retinanet/rotated-retinanet-rbox-le90_r50_fpn_1x_dota.py \
  3. checkpoints/SOME_CHECKPOINT.pth --format-only \
  4. --eval-options submission_dir=work_dirs/Task1_results

或者

  1. ./tools/dist_test.sh \
  2. configs/rotated_retinanet/rotated-retinanet-rbox-le90_r50_fpn_1x_dota.py \
  3. checkpoints/SOME_CHECKPOINT.pth 1 --format-only \
  4. --eval-options submission_dir=work_dirs/Task1_results

您可以将data_root中的test set路径改为val set或trainval set进行离线评估。

  1. python ./tools/test.py \
  2. configs/rotated_retinanet/rotated-retinanet-rbox-le90_r50_fpn_1x_dota.py \
  3. checkpoints/SOME_CHECKPOINT.pth --eval mAP

或者

  1. ./tools/dist_test.sh \
  2. configs/rotated_retinanet/rotated-retinanet-rbox-le90_r50_fpn_1x_dota.py \
  3. checkpoints/SOME_CHECKPOINT.pth 1 --eval mAP

您还可以可视化结果。

  1. python ./tools/test.py \
  2. configs/rotated_retinanet/rotated-retinanet-rbox-le90_r50_fpn_1x_dota.py \
  3. checkpoints/SOME_CHECKPOINT.pth \
  4. --show-dir work_dirs/vis

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/509449
推荐阅读
相关标签
  

闽ICP备14008679号