pytorch 华为云杯垃圾分类总结(目标检测)

摘要

我们队伍名称冲冲冲,A榜第八,B榜第11,决赛榜第16,决赛服务器评分出现问题和恰巧我们的模型速度在增加了200多张照片的情况下又超时了,直接就出局了。接下来就分享一些常用的提分点。数据下载链接链接:https://pan.baidu.com/s/1aCh_fIVsRBjKXQkFIpdvRQ
提取码:1234

baseline

前二十基本全是mmdetection。竞赛必备,里面包含了很多算法,目前2.0版本主要使用cascade——rcnn系列,
第一名使用的是res2net前置网络,当时我们并没有使用这个网络,res2net的基础多分就有70分,我们使用的cascade——rfp的resnet50作为前置网络,基础得分只有67左右,基础分就低了很多。使用senet154基础分有75.不同的前置网络分数差距很大,需要在训练前都测试,找出最好的baseline,使用senet154的前置得分很高但是在进行提分就困难很多了,第四名选手说多尺度加上都没涨点。很多策略使用之后都不会涨点,上分变的困难了一些。
所以学会使用mmdetection,和能够灵活运用前置网络是重点。找到适合的网络就在起步领先其他人。后面再加上trick也不会那么费力了。

trick

目前常用的mixup和mosic。和mmdet里面使用albu自带的各种增强需要自己去组合使用。不同的trick可能会有不同的影响,比如我最进训练mixup和cutout同时使用效果大幅度降低。单独测试都可以提升2个点。还有类别平衡,标签平滑。其中类别平衡在mmdet里面自带一种和自己进行线下增强,将类别少的进行随机变换扩充。第一名的代码里面的使用的有atss特征提取。是结合了atss下面的代码自己构造的新网络。需要对mmdet的代码编写十分熟悉才行。mmdet本身就将各个网络写的组件形式,所以需要花很大功夫去学习源码。最终要的一点是机器配置。有些trick加上去很难收敛。所以有时候需要你去预训练权重在coco数据集上(玩不起)。或者使用学习率退火一般来说也会更好一点,或者mmdet自带的分布式训练。

部分代码

模型修剪,上传文件只需要参数信息

import torch
yuan=torch.load('./rs_cut_mix_pafpn_box.pth')
new = {'meta': yuan['meta'],'state_dict': yuan['state_dict']}
torch.save(new,'./rs_cu4_4_min.pth')

coco_detection

# dataset settings
dataset_type = 'VOCDataset'
data_root = '/home/jmy/hjc/code/rubbish_classification/datasets/VOCdevkit/'
img_norm_cfg = dict(
    mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)

# TODO: augmentation from github
albu_train_transforms = [
    dict(
        type='MotionBlur',
        blur_limit=(3, 7),
        p=0.2),
    #add two albu
    dict(
        type='ShiftScaleRotate',
        shift_limit=0.0625,
        scale_limit=0.0,
        rotate_limit=[-10, 10],
        interpolation=1,
        p=0.5),
]

train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True),

    # TODO: augmentation from github
    dict(type='Mixup', prob=0.4, lambd=0.5, mixup=True,
         trainval_path='/home/jmy/hjc/code/rubbish_classification/mmdetection/augmentation_zx/ap_05_id_in_all.txt',
         #trainval_path='/home/jmy/hjc/code/rubbish_classification/mmdetection/augmentation_zx/ap_05_id_in_trainset.txt',
         img_path='/home/jmy/hjc/code/rubbish_classification/datasets/VOCdevkit/VOC2007/JPEGImages',
         annotation_path='/home/jmy/hjc/code/rubbish_classification/datasets/VOCdevkit/VOC2007/Annotations'),

    #dict(type='Resize', img_scale=(800, 480), keep_ratio=True),
    dict(type='Resize', img_scale=[(800, 600), (800, 360)], keep_ratio=True, multiscale_mode='range'),
    dict(type='RandomFlip', flip_ratio=0.5),
    dict(type='Normalize', **img_norm_cfg),
    dict(type='Pad', size_divisor=32),

    # TODO: augmentation from github
    dict(
        type='Albu',
        transforms=albu_train_transforms,
        bbox_params=dict(
            type='BboxParams',
            format='pascal_voc',
            label_fields=['gt_labels'],
            min_visibility=0.0,
            filter_lost_elements=True),
        keymap={
            'img': 'image',
            'gt_masks': 'masks',
            'gt_bboxes': 'bboxes'
        },
        update_pad_shape=False,
        skip_img_without_anno=True),

    dict(type='DefaultFormatBundle'),
    dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(
        type='MultiScaleFlipAug',
        #img_scale=(1000, 600),
        img_scale=(800, 480),
        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(
    #The default learning rate in config files is for 8 GPUs and 2 img/gpu (batch size = 8*2 = 16)
    #e.g., lr=0.01 for 4 GPUs * 2 img/gpu and lr=0.08 for 16 GPUs * 4 img/gpu.
    # samples_per_gpu=2,
    # workers_per_gpu=2,
    samples_per_gpu=4,
    workers_per_gpu=0,
    train=dict(
        type='RepeatDataset',
        #hjc:The VOC dataset uses 3 times the size of dataset during training
        #times=3,
        times=1,
        dataset=dict(
            type=dataset_type,
            # ann_file=[
            #     data_root + 'VOC2007/ImageSets/Main/trainval.txt',
            #     #data_root + 'VOC2012/ImageSets/Main/trainval.txt'
            # ],
            ann_file=[
                data_root + 'VOC2007/ImageSets/Main/train.txt'
                #'/home/jmy/hjc/code/rubbish_classification/mmdetection/data/lowap2000_grid/VOCdevkit/VOC2007/ImageSets/Main/train.txt'
            ],
            img_prefix=[data_root + 'VOC2007/', data_root + 'VOC2012/'],
            #img_prefix=[data_root + 'VOC2007/', '/home/jmy/hjc/code/rubbish_classification/mmdetection/data/lowap2000_grid/VOCdevkit/VOC2007'],
            pipeline=train_pipeline)),
    val=dict(
        type=dataset_type,
        # ann_file=data_root + 'VOC2007/ImageSets/Main/test.txt',
        ann_file=data_root + 'VOC2007/ImageSets/Main/val.txt',
        img_prefix=data_root + 'VOC2007/',
        pipeline=test_pipeline),
    test=dict(
        type=dataset_type,
        #ann_file=data_root + 'VOC2007/ImageSets/Main/trainval.txt',
        ann_file=data_root + 'VOC2007/ImageSets/Main/val.txt',
        img_prefix=data_root + 'VOC2007/',
        pipeline=test_pipeline))
evaluation = dict(interval=1, metric='mAP')

cascade_rcnn_r50_fpn

# model settings
model = dict(
    type='CascadeRCNN',
    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(
        type='FPN',
        in_channels=[256, 512, 1024, 2048],
        out_channels=256,
        num_outs=5),
    rpn_head=dict(
        type='RPNHead',
        in_channels=256,
        feat_channels=256,
        anchor_generator=dict(
            type='AnchorGenerator',
            #scales=[8],
            scales=[7],
            ratios=[0.5, 1.0, 2.0],
            #ratios=[0.2, 0.4, 0.5, 0.6, 0.75, 17/20, 1.0, 20/17, 4/3, 5/3, 2.0, 2.5, 5.0],
            strides=[4, 8, 16, 32, 64]),
        bbox_coder=dict(
            type='DeltaXYWHBBoxCoder',
            target_means=[.0, .0, .0, .0],
            target_stds=[1.0, 1.0, 1.0, 1.0]),
        loss_cls=dict(
            type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
        loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
    roi_head=dict(
        type='CascadeRoIHead',
        num_stages=3,
        stage_loss_weights=[1, 0.5, 0.25],
        bbox_roi_extractor=dict(
            type='SingleRoIExtractor',
            roi_layer=dict(type='RoIAlign', out_size=7, sample_num=0),
            out_channels=256,
            featmap_strides=[4, 8, 16, 32]),
        bbox_head=[
            dict(
                type='Shared2FCBBoxHead',
                in_channels=256,
                fc_out_channels=1024,
                roi_feat_size=7,
                #num_classes=80,
                #V2.0 donot need N + 1 classes count. just N
                num_classes=44,
                bbox_coder=dict(
                    type='DeltaXYWHBBoxCoder',
                    target_means=[0., 0., 0., 0.],
                    target_stds=[0.1, 0.1, 0.2, 0.2]),
                reg_class_agnostic=True,
                loss_cls=dict(
                    type='CrossEntropyLoss',
                    use_sigmoid=False,
                    loss_weight=1.0),
                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
                               loss_weight=1.0)),
            dict(
                type='Shared2FCBBoxHead',
                in_channels=256,
                fc_out_channels=1024,
                roi_feat_size=7,
                #num_classes=80,
                num_classes=44,
                bbox_coder=dict(
                    type='DeltaXYWHBBoxCoder',
                    target_means=[0., 0., 0., 0.],
                    target_stds=[0.05, 0.05, 0.1, 0.1]),
                reg_class_agnostic=True,
                loss_cls=dict(
                    type='CrossEntropyLoss',
                    use_sigmoid=False,
                    loss_weight=1.0),
                loss_bbox=dict(type='SmoothL1Loss', beta=1.0,
                               loss_weight=1.0)),
            dict(
                type='Shared2FCBBoxHead',
                in_channels=256,
                fc_out_channels=1024,
                roi_feat_size=7,
                #num_classes=80,
                num_classes=44,
                bbox_coder=dict(
                    type='DeltaXYWHBBoxCoder',
                    target_means=[0., 0., 0., 0.],
                    target_stds=[0.033, 0.033, 0.067, 0.067]),
                reg_class_agnostic=True,
                loss_cls=dict(
                    type='CrossEntropyLoss',
                    use_sigmoid=False,
                    loss_weight=1.0),
                loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))
        ]))
# model training and testing settings
train_cfg = dict(
    rpn=dict(
        assigner=dict(
            type='MaxIoUAssigner',
            pos_iou_thr=0.7,
            neg_iou_thr=0.3,
            min_pos_iou=0.3,
            match_low_quality=True,
            ignore_iof_thr=-1),
        sampler=dict(
            type='RandomSampler',
            num=256,
            pos_fraction=0.5,
            neg_pos_ub=-1,
            add_gt_as_proposals=False),
        allowed_border=0,
        pos_weight=-1,
        debug=False),
    rpn_proposal=dict(
        nms_across_levels=False,
        nms_pre=2000,
        nms_post=2000,
        max_num=2000,
        nms_thr=0.7,
        min_bbox_size=0),
    rcnn=[
        dict(
            assigner=dict(
                type='MaxIoUAssigner',
                pos_iou_thr=0.5,
                neg_iou_thr=0.5,
                min_pos_iou=0.5,
                match_low_quality=False,
                ignore_iof_thr=-1),
            sampler=dict(
                type='RandomSampler',
                num=512,
                pos_fraction=0.25,
                neg_pos_ub=-1,
                add_gt_as_proposals=True),
            pos_weight=-1,
            debug=False),
        dict(
            assigner=dict(
                type='MaxIoUAssigner',
                pos_iou_thr=0.6,
                neg_iou_thr=0.6,
                min_pos_iou=0.6,
                match_low_quality=False,
                ignore_iof_thr=-1),
            sampler=dict(
                type='RandomSampler',
                num=512,
                pos_fraction=0.25,
                neg_pos_ub=-1,
                add_gt_as_proposals=True),
            pos_weight=-1,
            debug=False),
        dict(
            assigner=dict(
                type='MaxIoUAssigner',
                pos_iou_thr=0.7,
                neg_iou_thr=0.7,
                min_pos_iou=0.7,
                match_low_quality=False,
                ignore_iof_thr=-1),
            sampler=dict(
                type='RandomSampler',
                num=512,
                pos_fraction=0.25,
                neg_pos_ub=-1,
                add_gt_as_proposals=True),
            pos_weight=-1,
            debug=False)
    ])
test_cfg = dict(
    rpn=dict(
        nms_across_levels=False,
        nms_pre=1000,
        nms_post=1000,
        max_num=1000,
        nms_thr=0.7,
        min_bbox_size=0),
    rcnn=dict(
        score_thr=0.05, nms=dict(type='nms', iou_thr=0.5), max_per_img=100))
        #score_thr=0.001, nms=dict(type='nms', iou_thr=0.5), max_per_img=100))

schedule_lr

# optimizer
#optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
##note!:lr = 0.00125*batch_size 
optimizer = dict(type='SGD', lr=0.005, momentum=0.9, weight_decay=0.0001)
# optimizer_config = dict(grad_clip=None)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
#learning policy
lr_config = dict(
    policy='step',
    warmup='linear',
    warmup_iters=500,
    #warmup_iters=4000,
    warmup_ratio=0.001,
    #step=[8, 11])
    step=[9, 12])
total_epochs = 14

default_runtime

checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
    #interval=50,
    interval=50,
    hooks=[
        dict(type='TextLoggerHook'),
        # dict(type='TensorboardLoggerHook')
    ])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
#load_from = None
#load_from = '/home/jmy/hjc/code/rubbish_classification/mmdetection/checkpoints/cascade_rcnn/cascade_rcnn_r50_fpn_1x_coco_20200316-3dc56deb.pth'
#load_from = '/home/jmy/hjc/code/rubbish_classification/mmdetection/checkpoints/cascade_rcnn/cascade_rcnn_r50_coco_pretrained_weights_classes_45.pth'
#load_from = '/home/jmy/hjc/code/rubbish_classification/mmdetection/checkpoints/cascade_rcnn/cascade_rcnn_r101_coco_pretrained_weights_classes_45.pth'
load_from = '/home/jmy/hjc/code/rubbish_classification/mmdetection/checkpoints/cascade_rcnn/cascade_rcnn_x101_32x4d_coco_pretrained_weights_classes_45.pth'

resume_from = None
workflow = [('train', 1)]


总结

这是前期部分代码,主要是作为一个新手学习点。更多的策略合数据增强都是自己去mmdet下自己书写代码。比赛最中要的是有足够好的设备。和掌握大部分的mmdet的源码即可,就我们队伍而言。就有10张卡差不多。排名前几的,有的设备是64张卡。或者8张32显存的v100,足够支撑训练coco预训练权重的,一个模型三天即可。更多的还是要自己学会改代码。利用mmdet提供的组件进行修改。可以自己观看configs下的全部文件进行学习。

你可能感兴趣的:(pytorch 华为云杯垃圾分类总结(目标检测))