1. 环境准备搭建PaddleDetection开发环境第一次接触PaddleDetection时我最头疼的就是环境配置。这里分享一个实测稳定的方案帮你避开我踩过的坑。首先需要明确PaddleDetection依赖Python 3.6和CUDA 10.2以上版本如果用GPU的话。我建议直接使用conda创建虚拟环境避免与其他项目冲突conda create -n paddle python3.8 conda activate paddle接下来安装PaddlePaddle基础框架。这里有个关键细节一定要根据你的CUDA版本选择对应的安装包。我常用的是CUDA 11.2对应的安装命令是python -m pip install paddlepaddle-gpu2.4.2.post112 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html验证安装是否成功时别像我当初那样只简单import paddle就完事了。正确的验证姿势是import paddle paddle.utils.run_check()看到PaddlePaddle is installed successfully!才算真正搞定。这时候再安装PaddleDetection就简单了git clone https://github.com/PaddlePaddle/PaddleDetection.git cd PaddleDetection pip install -r requirements.txt我强烈建议在安装完成后跑个demo测试下环境。PaddleDetection提供了现成的测试脚本python tools/infer.py -c configs/ppyolo/ppyolo_r50vd_dcn_1x_coco.yml -o weightshttps://paddledet.bj.bcebos.com/models/ppyolo_r50vd_dcn_1x_coco.pdparams --infer_imgdemo/000000014439.jpg如果能看到检测结果图片说明环境配置完全正确。这里有个小技巧把常用模型权重下载到本地目录比如新建一个pretrained_models文件夹存放这样下次训练时就不用重复下载了。2. 数据准备构建自己的训练数据集实际项目中我们通常需要训练自己的数据集。PaddleDetection支持VOC和COCO两种主流格式我个人更推荐COCO格式因为它的标注信息更丰富。假设你有一批标注好的图片下面这个脚本可以帮你转换成COCO格式import json import os import cv2 def convert_to_coco(image_dir, label_dir, output_path): images [] annotations [] categories [{id: 1, name: object}] annotation_id 0 for image_id, image_name in enumerate(os.listdir(image_dir)): image_path os.path.join(image_dir, image_name) label_path os.path.join(label_dir, os.path.splitext(image_name)[0] .txt) img cv2.imread(image_path) height, width img.shape[:2] images.append({ id: image_id, file_name: image_name, height: height, width: width }) with open(label_path) as f: for line in f.readlines(): class_id, x_center, y_center, w, h map(float, line.strip().split()) # 转换YOLO格式到COCO格式 x_min (x_center - w/2) * width y_min (y_center - h/2) * height w w * width h h * height annotations.append({ id: annotation_id, image_id: image_id, category_id: int(class_id)1, bbox: [x_min, y_min, w, h], area: w * h, iscrowd: 0 }) annotation_id 1 coco_dict { images: images, annotations: annotations, categories: categories } with open(output_path, w) as f: json.dump(coco_dict, f)使用这个脚本时要注意几点图片和标注文件要放在不同文件夹标注文件要是YOLO格式class_id x_center y_center width height生成的COCO json文件需要放在annotations文件夹内数据集准备好后建议按照8:1:1的比例划分训练集、验证集和测试集。PaddleDetection提供了数据集划分工具python tools/split_coco_dataset.py --json_path annotations/instances_default.json --save_dir split_annotations --val_ratio 0.1 --test_ratio 0.13. 模型选择与配置调优PaddleDetection提供了丰富的预训练模型从轻量级的PP-PicoDet到高精度的PP-YOLOE。新手常见误区是盲目选择大模型其实应该根据实际场景选择移动端部署PP-PicoDet5MB平衡型PP-YOLO tiny/s10-30MB高精度PP-YOLOE100MB选定模型后需要修改配置文件。以PP-YOLO tiny为例配置文件通常位于configs/ppyolo/ppyolo_tiny_650e_coco.yml。关键配置项包括_BASE_: [ ../datasets/coco_detection.yml, ../runtime.yml, _base_/optimizer_650e.yml, _base_/ppyolo_tiny_reader.yml, _base_/ppyolo_tiny_model.yml ] pretrain_weights: https://paddledet.bj.bcebos.com/models/ppyolo_tiny_650e_coco.pdparams weights: output/ppyolo_tiny_650e_coco/model_final TrainDataset: !COCODataSet image_dir: train2017 anno_path: annotations/instances_train2017.json dataset_dir: dataset/coco EvalDataset: !COCODataSet image_dir: val2017 anno_path: annotations/instances_val2017.json dataset_dir: dataset/coco TestDataset: !ImageFolder anno_path: annotations/instances_val2017.json dataset_dir: dataset/coco LearningRate: base_lr: 0.005 schedulers: - !PiecewiseDecay milestones: [400, 500] gamma: 0.1 - !LinearWarmup start_factor: 0. steps: 1000几个必须修改的参数pretrain_weights预训练模型路径TrainDataset/EvalDataset下的路径LearningRate中的base_lr建议从0.001开始尝试对于数据增强新手可以先用默认配置等模型跑通后再调整。常见的数据增强包括随机翻转RandomFlip随机裁剪RandomCrop色彩抖动ColorDistort4. 模型训练与评估配置完成后就可以开始训练了。PaddleDetection提供了非常方便的训练命令python -u tools/train.py \ -c configs/ppyolo/ppyolo_tiny_650e_coco.yml \ --eval \ -o pretrain_weightshttps://paddledet.bj.bcebos.com/models/ppyolo_tiny_650e_coco.pdparams这里有几个实用技巧加上--eval参数可以在训练过程中定期评估模型使用--use_vdl启动VisualDL可视化训练过程添加--resume可以从上次中断的地方继续训练训练过程中要关注几个关键指标loss应该逐渐下降并趋于稳定mAP验证集上的平均精度速度每秒处理的图片数FPS如果发现loss不下降可能是学习率太大或太小数据标注有问题模型复杂度与数据量不匹配训练完成后可以用以下命令评估模型python -u tools/eval.py \ -c configs/ppyolo/ppyolo_tiny_650e_coco.yml \ -o weightsoutput/ppyolo_tiny_650e_coco/best_model.pdparams对于实际项目我建议导出为推理模型再评估python tools/export_model.py \ -c configs/ppyolo/ppyolo_tiny_650e_coco.yml \ --output_dirinference_model \ -o weightsoutput/ppyolo_tiny_650e_coco/best_model.pdparams导出的模型会包含三个文件model.pdmodel模型结构model.pdiparams模型参数infer_cfg.yml推理配置5. 模型部署与实战技巧训练好的模型可以部署到各种环境。最简单的Python推理代码如下import paddle from ppdet.core.workspace import load_config from ppdet.engine import Trainer from ppdet.metrics import get_infer_results # 加载模型 cfg load_config(inference_model/infer_cfg.yml) trainer Trainer(cfg, modetest) trainer.load_weights(inference_model/model.pdparams) # 准备数据 image cv2.imread(test.jpg) image cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 推理 outputs trainer.predict([image]) # 解析结果 boxes outputs[0][bbox][0].numpy() scores outputs[0][score][0].numpy() classes outputs[0][category_id][0].numpy()对于生产环境我推荐使用Paddle Inference加速import paddle.inference as paddle_infer # 创建配置 config paddle_infer.Config(inference_model/model.pdmodel, inference_model/model.pdiparams) # 创建预测器 predictor paddle_infer.create_predictor(config) # 获取输入输出句柄 input_names predictor.get_input_names() input_handle predictor.get_input_handle(input_names[0]) output_names predictor.get_output_names() output_handle predictor.get_output_handle(output_names[0]) # 准备输入数据 input_data np.array([image]).astype(float32) input_handle.reshape([1, 3, 608, 608]) input_handle.copy_from_cpu(input_data) # 执行预测 predictor.run() # 获取输出 output_data output_handle.copy_to_cpu()在实际项目中有几个经验值得分享小目标检测困难尝试减小anchor尺寸或使用FPN结构类别不平衡试试Focal Loss或OHEM推理速度慢考虑模型剪枝或量化部署到移动端使用Paddle Lite转换模型最后提醒一点PaddleDetection更新很快建议定期查看官方文档获取最新特性。遇到问题时可以先搜索GitHub Issues大部分常见问题都有解决方案。