swin-transform 训练自己的数据集

近transform在cv圈可谓hot到爆,记录一下之前参加比赛所用的代码swin-transform,算法来源于ICCV2020的best paper。废话少说,直接上源码
code:https://github.com/SwinTransformer/Swin-Transformer-Object-Detection
paper:https://openaccess.thecvf.com/content/ICCV2021/papers/Liu_Swin_Transformer_Hierarchical_Vision_Transformer_Using_Shifted_Windows_ICCV_2021_paper.pdf

搭建swin-transform需要的环境

1.conda create -n swin python=3.7 
2.conda activate swin
3.conda install pytorch==1.7.0 torchvision==0.8.0 torchaudio==0.7.0 cudatoolkit=11.0
4.pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu110/torch1.7.0/index.html
5.pip install mmdet
#需要注意的是pytorch版本、cuda版本与mmcv版本需搭配,否则会出错。

本教程所用的mmdetection版本:code链接https://github.com/open-mmlab/mmdetection/releases/tag/v2.18.0
1.执行mmdetection下的setup.py编译环境
至此环境的事基本上弄完了
2.由于我们目标只有一类,需要修改mmdetction下相关文件,新建一个data文件存放数据集,数据集按coco数据集格式准备。
在这里插入图片描述

找到configs文件下_base_文件、打开_base_文件下dataset文件里的coco_detection.py
对应code
train_pipeline = [
    dict(type='LoadImageFromFile'),
    dict(type='LoadAnnotations', with_bbox=True),
    dict(type='Resize', img_scale=(1333, 800), 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=(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']),
        ])
]
#修改img_scale大小,图像尺寸太大吃设备。要做其他任务:语义分割的话在对应的文件下修改一下图像尺寸

在这里插入图片描述

找到configs文件下_base_文件、打开_base_文件下models如图所示:本文选用mask_rcnn_r50_fpn.py作为backbone。修改mask_rcnn_r50_fpn.py里的num_class

对应code

model = dict(
    type='MaskRCNN',
    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',
        init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')),
    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],
            ratios=[0.5, 1.0, 2.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='L1Loss', loss_weight=1.0)),
    roi_head=dict(
        type='StandardRoIHead',
        bbox_roi_extractor=dict(
            type='SingleRoIExtractor',
            roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=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,
            bbox_coder=dict(
                type='DeltaXYWHBBoxCoder',
                target_means=[0., 0., 0., 0.],
                target_stds=[0.1, 0.1, 0.2, 0.2]),
            reg_class_agnostic=False,
            loss_cls=dict(
                type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
            loss_bbox=dict(type='L1Loss', loss_weight=1.0)),
        mask_roi_extractor=dict(
            type='SingleRoIExtractor',
            roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),
            out_channels=256,
            featmap_strides=[4, 8, 16, 32]),
        mask_head=dict(
            type='FCNMaskHead',
            num_convs=4,
            in_channels=256,
            conv_out_channels=256,
            num_classes=80,
            loss_mask=dict(
                type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))),
 #coco数据集有80个类、需要根据你自己的检测类别数进行修改。说人话就是把80改成1(你自己数据的类别数)或其他

修改mmdet

找到mmdet下core里的evaluation文件。打开找到class_names.py 修改数据集的label

在这里插入图片描述

对应code
def coco_classes():
    return [
        'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train',
        'truck', 'boat', 'traffic_light', 'fire_hydrant', 'stop_sign',
        'parking_meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep',
        'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella',
        'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
        'sports_ball', 'kite', 'baseball_bat', 'baseball_glove', 'skateboard',
        'surfboard', 'tennis_racket', 'bottle', 'wine_glass', 'cup', 'fork',
        'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange',
        'broccoli', 'carrot', 'hot_dog', 'pizza', 'donut', 'cake', 'chair',
        'couch', 'potted_plant', 'bed', 'dining_table', 'toilet', 'tv',
        'laptop', 'mouse', 'remote', 'keyboard', 'cell_phone', 'microwave',
        'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase',
        'scissors', 'teddy_bear', 'hair_drier', 'toothbrush'
    ]
   #coco数据集有80个类对应80个label,改成你自己的label。如有一个类:直接改成
   def coco_classes():
   return['你自己的label',]
找到mmdet下datasets下的coco.py,如图

在这里插入图片描述

对应code
class CocoDataset(CustomDataset):

    CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
               'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
               'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
               'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
               'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
               'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
               'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
               'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
               'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
               'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
               'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
               'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
               'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',
               'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush')
   #修改label,同上
至此,基本上就完成了

开始训练

python tools/train.py configs/swin/mask_rcnn_swin-t-p4-w7_fpn_fp16_ms-crop-3x_coco.py
#默认一张卡,多卡就添加上卡的个数

在这里插入图片描述

跑起来了,开始训练后,训练日志在mmdetection下work_dir里。

调用训练好的模型测试

# Copyright (c) OpenMMLab. All rights reserved.
import asyncio
from argparse import ArgumentParser

from mmdet.apis import (async_inference_detector, inference_detector,
                        init_detector, show_result_pyplot)


def parse_args():
    parser = ArgumentParser()
    parser.add_argument('img', default='image root', help='Image file')
    parser.add_argument('config',default='config root', help='Config file')
    parser.add_argument('checkpoint',default='save model root', help='Checkpoint file')
    parser.add_argument(
        '--device', default='cuda:0', help='Device used for inference')
    parser.add_argument(
        '--score-thr', type=float, default=0.3, help='bbox score threshold')
    parser.add_argument(
        '--async-test',
        action='store_true',
        help='whether to set async options for async inference.')
    args = parser.parse_args()
    return args


def main(args):
    # build the model from a config file and a checkpoint file
    model = init_detector(args.config, args.checkpoint, device=args.device)
    # test a single image
    result = inference_detector(model, args.img)
    # show the results
    show_result_pyplot(model, args.img, result, score_thr=args.score_thr)


async def async_main(args):
    # build the model from a config file and a checkpoint file
    model = init_detector(args.config, args.checkpoint, device=args.device)
    # test a single image
    tasks = asyncio.create_task(async_inference_detector(model, args.img))
    result = await asyncio.gather(tasks)
    # show the results
    show_result_pyplot(model, args.img, result[0], score_thr=args.score_thr)


if __name__ == '__main__':
    args = parse_args()
    if args.async_test:
        asyncio.run(async_main(args))
    else:
        main(args)
### 回答1: 要使用Swin Transformer训练自己的数据集,需要进行以下步骤: 1. 准备数据集:将自己的数据集准备好,并将其划分为训练集、验证集和测试集。 2. 安装Swin Transformer:在本地或云端安装Swin Transformer,可以使用PyTorch框架进行安装。 3. 配置训练参数:根据自己的数据集和需求,配置训练参数,如学习率、批次大小、训练轮数等。 4. 定义模型:根据自己的数据集和需求,定义Swin Transformer模型,可以使用预训练模型进行fine-tuning。 5. 训练模型:使用定义好的模型和训练参数,对数据集进行训练。 6. 评估模型:使用验证集和测试集对训练好的模型进行评估,可以计算准确率、召回率、F1值等指标。 7. 预测新数据:使用训练好的模型对新数据进行预测,可以得到分类结果或回归结果。 以上是使用Swin Transformer训练自己的数据集的基本步骤,具体实现需要根据自己的需求进行调整。 ### 回答2: 总体来说,针对个人数据集进行Swin Transformer模型的训练需要遵循以下步骤: 1. 数据集准备:首先,需要准备好数据集数据集的准备需要注意的是要有标签数据集,保持数据集的质量高,数据集中的类别要明确,数量要充足。同时,对于数据集中的图像,可以进行预处理操作如裁剪、缩放、翻转等,以适应模型的要求。 2. 划分训练集和测试集:在准备数据集的时候,要将数据集按照训练集和测试集进行划分。通常,可将数据集中的70%作为训练集,30%作为测试集。 3. 数据集加载与预处理:在PyTorch中,可以使用DataLoader来将数据集加载到模型中,并进行数据预处理如归一化等操作,同时还可以设置batch_size、shuffle等参数。 4. 定义模型:使用PyTorch中的Swin Transformer模型,并进行自定义修改以适应自己数据集的处理任务。 5. 定义损失函数与优化器:根据任务目标不同,选择不同的损失函数如交叉熵、均方误差等,并结合优化器如Adam、SGD等进行模型训练。 6. 训练模型:使用DataLoader加载数据集,应用损失函数和优化器,训练模型。可以设置迭代次数、学习率等参数,并进行学习率衰减等技巧来提高模型效果。 7. 模型评估:在训练模型过程中,需要了解模型的表现,可以使用测试集数据集进行模型评估。常用指标如准确率、精确率、召回率、F1值等。 8. 模型调参与优化:根据测试集的表现调整模型参数,如学习率、batch_size等,同时还可以进行模型结构的优化等操作以提高模型的性能。 总的来说,这些步骤有助于构建适用于自己数据集的Swin Transformer模型,并可以及时了解模型的表现及进行调优,从而提高模型的性能。当然,虽然操作流程有些繁琐,但是得到高质量的模型肯定值得一试。 ### 回答3: Swin Transformer是近期提出的一种先进的图像分类模型,在多个视觉领域的任务中都取得了最佳效果。在使用Swin Transformer之前,我们需要准备一个自己的数据集,并利用该数据集对Swin Transformer进行训练以实现图像分类任务。 下面是使用Swin Transformer训练自己的数据集的步骤: 1. 数据预处理:收集并准备数据集,对图片进行裁剪、缩放、旋转等增强操作,同时保证标签信息准确无误。 2. 安装并配置Swin Transformer:在训练之前,需要安装Swin Transformer的相关包并配置环境,例如PyTorch,Torchvision,Pillow等。 3. 训练模型:Swin Transformer是深度神经网络,因此需要大量的计算资源和时间才能完成模型训练。我们需要选择合适的GPU,设置合适的参数,使用训练集进行模型训练。 4. 模型评估:训练完成之后,我们需要将测试集输入到模型中,并计算模型的准确率和损失等指标,以评估模型的性能。 5. 调整模型参数:如果模型性能不理想,我们可以尝试调整模型参数,例如修改Swin Transformer的网络层数、神经元数目等,直到获得最佳的结果。 6. 应用模型:最后,我们可以使用Swin Transformer模型对新的图片进行分类预测,对图像进行分类。 总之,Swin Transformer是一种先进的图像分类模型,能够有效地识别和分类图像。对于训练自己的数据集,我们需要按照上述步骤进行操作,以获得最佳的模型性能。
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VisionX Lab

你的鼓励将是我更新的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值