1. 环境搭建与依赖安装第一次接触Swin-Transformer做目标检测时我花了两天时间才把环境配好。这里分享几个关键点帮你避开我踩过的坑。首先明确环境要求Linux系统推荐Ubuntu 18.04、Python 3.7、PyTorch 1.8、CUDA 11.1。实测在RTX 3090上这套组合最稳定。安装mmcv-full是个技术活不同CUDA版本对应不同的安装命令。比如CUDA 11.3应该用pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu113/torch1.10.0/index.html而CUDA 11.1则需要换成pip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.9.0/index.html有个小技巧先用nvidia-smi查看CUDA版本再对照MMCV官方文档选择对应命令。我遇到过mmcv和torch版本不兼容的问题后来发现用conda创建虚拟环境最省心conda create -n swin python3.8 conda install pytorch1.10.0 torchvision0.11.0 cudatoolkit11.3 -c pytorch2. 数据准备与格式转换2.1 VOC格式详解VOC数据集的标准结构是这样的VOCdevkit/ └── VOC2007/ ├── Annotations/ # XML标注文件 ├── JPEGImages/ # 原始图片 ├── ImageSets/ │ └── Main/ # 训练/验证集划分文件 └── labels/ # YOLO格式标签可选自定义数据集时最容易出错的是XML标注。我写了个检查脚本可以验证标注是否合规from lxml import etree def validate_xml(xml_path): try: etree.parse(xml_path) print(f{xml_path} 验证通过) except Exception as e: print(f{xml_path} 错误{str(e)})2.2 非标准数据转换当你的数据是COCO或YOLO格式时需要先转换。我整理了个转换脚本# COCO转VOC from pycocotools.coco import COCO coco COCO(annotations/instances_train2017.json) for img_id in coco.imgs: # 转换逻辑... pass # YOLO转VOC def yolo_to_voc(yolo_label, img_w, img_h): x_center, y_center, w, h map(float, yolo_label.split()[1:]) xmin (x_center - w/2) * img_w xmax (x_center w/2) * img_w ymin (y_center - h/2) * img_h ymax (y_center h/2) * img_h return [xmin, ymin, xmax, ymax]3. 模型配置实战3.1 关键参数调整在configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_3x_coco.py中这几个参数必须改原参数修改建议作用num_classes80改为实际类别数输出层维度img_scale(1333, 800)根据显存调整输入图像尺寸samples_per_gpu2显存小就改1batch大小我常用的显存占用估算公式显存(MB) ≈ (img_w × img_h × 3 × batch_size × 4) / 1024 / 1024 × 安全系数(通常取3)3.2 类别定义修改需要修改两处代码文件mmdet/datasets/voc.py中的CLASSES元组mmdet/core/evaluation/class_names.py中的voc_classes函数建议用这个脚本自动生成类别映射classes [cat, dog, person] # 你的类别 with open(class_map.txt, w) as f: for i, cls in enumerate(classes): f.write(f{i1}: {cls}\n)4. 训练技巧与调优4.1 学习率设置Swin-Tiny的初始学习率建议设为0.0001我用这个公式动态调整base_lr 0.0001 actual_lr base_lr * (batch_size / 16) # 16是参考batch大小在config文件中这样配置optimizer dict( typeAdamW, lractual_lr, weight_decay0.05)4.2 早停策略修改configs/_base_/schedules/schedule_1x.pyevaluation dict( interval1, metricmAP, save_bestmAP, rulegreater)配合这个回调函数custom_hooks [ dict( typeEarlyStoppingHook, patience10, # 连续10次不提升就停止 min_delta0.001) ]5. 常见问题解决5.1 报错Not in backbone registry这是因为用了错误的预训练模型。应该下载图像分类模型而非检测模型wget https://github.com/microsoft/Swin-Transformer/releases/download/v1.0.0/swin_tiny_patch4_window7_224.pth5.2 内存泄漏问题在config中添加内存监控log_config dict( interval50, hooks[ dict(typeTextLoggerHook), dict(typeTensorboardLoggerHook), dict(typeMemoryProfilerHook) # 新增 ])6. 部署优化技巧训练完成后用这个命令导出ONNX模型python tools/deployment/pytorch2onnx.py \ configs/swin/mask_rcnn_swin_tiny_patch4_window7_mstrain_480-800_adamw_3x_coco.py \ work_dirs/latest.pth \ --output-file model.onnx \ --shape 800 1333实测发现动态轴设置能提升推理速度torch.onnx.export( model, dummy_input, model.onnx, dynamic_axes{ input: {0: batch}, output: {0: batch} })