写点什么

Yolo 模型训练的第一个 Step

作者:Jason黄
  • 2025-09-18
    广东
  • 本文字数:2804 字

    阅读完需:约 9 分钟

Yolo模型训练的第一个Step

参考 ultralytics 进行 yolo 11 模型的训练。


yolo 模型的训练已经比较成熟了,只要提供好经过标注的数据集,就可以开始训练了。


我们学习 yolo 训练,可以使用官方提供的预训练的模型以及 coco 数据集的下载,让我们开始第一个简单的 yolo 模型训练。

使用 coco8 数据集认识 yolo 训练

Ultralytics COCO8 数据集是一个紧凑而强大的目标检测数据集,由 COCO train 2017 数据集中的前 8 张图像组成——4 张用于训练,4 张用于验证。该数据集专门设计用于使用 YOLO 模型和训练管道进行快速测试、调试和实验。它体积小巧,易于管理,同时其多样性确保了在扩展到更大的数据集之前,它可以作为有效的完整性检查。


训练脚本:


from ultralytics import YOLO
# Load a pretrained modelmodel = YOLO("yolo11n.pt")
# Train the model with GPU supportresults = model.train( data="coco8.yaml", epochs=100, imgsz=640, device="cuda", # For NVIDIA GPU (use "cuda:0" for specific GPU) # device="mps", # For Apple Silicon (M1/M2/M3/M4) # device="cpu", # For CPU only batch=1, # Can increase batch size with GPU patience=5, save_period=1)
复制代码


执行训练之前记得在 python 环境中安装 pip install ultralytics .


# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# COCO8 dataset (first 8 images from COCO train2017) by Ultralytics# Documentation: https://docs.ultralytics.com/datasets/detect/coco8/# Example usage: yolo train data=coco8.yaml# parent# ├── ultralytics# └── datasets# └── coco8 ← downloads here (1 MB)
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]path: coco8 # dataset root dirtrain: images/train # train images (relative to 'path') 4 imagesval: images/val # val images (relative to 'path') 4 imagestest: # test images (optional)
# Classesnames: 0: person 1: bicycle 2: car 3: motorcycle 4: airplane 5: bus 6: train 7: truck 8: boat 9: traffic light 10: fire hydrant 11: stop sign 12: parking meter 13: bench 14: bird 15: cat 16: dog 17: horse 18: sheep 19: cow 20: elephant 21: bear 22: zebra 23: giraffe 24: backpack 25: umbrella 26: handbag 27: tie 28: suitcase 29: frisbee 30: skis 31: snowboard 32: sports ball 33: kite 34: baseball bat 35: baseball glove 36: skateboard 37: surfboard 38: tennis racket 39: bottle 40: wine glass 41: cup 42: fork 43: knife 44: spoon 45: bowl 46: banana 47: apple 48: sandwich 49: orange 50: broccoli 51: carrot 52: hot dog 53: pizza 54: donut 55: cake 56: chair 57: couch 58: potted plant 59: bed 60: dining table 61: toilet 62: tv 63: laptop 64: mouse 65: remote 66: keyboard 67: cell phone 68: microwave 69: oven 70: toaster 71: sink 72: refrigerator 73: book 74: clock 75: vase 76: scissors 77: teddy bear 78: hair drier 79: toothbrush
# Download script/URL (optional)download: https://github.com/ultralytics/assets/releases/download/v0.0.0/coco8.zip
复制代码


直接运行 python3 train.py 程序会自动下载数据集和模型。


  ......  self.nt_per_image = np.bincount(stats["target_img"].astype(int), minlength=len(self.names))                   all          4         14          0          0          0          0
Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size 3/3 0.515G 0.7281 7.598 0.9811 5 640: 100% ━━━━━━━━━━━━ 4/4 2.0it/s 2.0s Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 2/2 1.2it/s 1.6s all 4 12 0.266 0.5 0.465 0.326
3 epochs completed in 0.006 hours.Optimizer stripped from /Users/xxx/go/src/xxx.net/myyolo/runs/detect/train3/weights/last.pt, 5.5MBOptimizer stripped from /Users/xxx/go/src/xxx.net/myyolo/runs/detect/train3/weights/best.pt, 5.5MB
Validating /Users/xxx/go/src/xxx.net/myyolo/runs/detect/train3/weights/best.pt...Ultralytics 8.3.201 🚀 Python-3.10.16 torch-2.8.0 MPS (Apple M1 Pro)YOLO11n summary (fused): 100 layers, 2,616,248 parameters, 0 gradients, 6.5 GFLOPs Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 2/2 2.4it/s 0.8s all 4 11 0.267 0.533 0.452 0.321 person 1 6 0.21 0.667 0.269 0.111 horse 1 1 0.215 1 0.995 0.597 elephant 1 2 0 0 0 0 umbrella 1 1 0 0 0 0 potted plant 1 1 0.912 1 0.995 0.895Speed: 0.1ms preprocess, 155.2ms inference, 0.0ms loss, 33.8ms postprocess per image
复制代码


训练完成后,会得到新的权重文件:


runs/detect/train3/weights/last.ptruns/detect/train3/weights/best.pt
复制代码


使用新的模型权重进行推理:


from ultralytics import YOLO
# 加载训练好的模型model = YOLO("runs/detect/train3/weights/best.pt")
# 简单推理示例print("开始推理...")
# 对图片进行推理并保存结果results = model.predict( source="datasets/coco8/images/val", # 输入源(图片/文件夹/视频) save=True, # 保存结果图片 conf=0.5, # 置信度阈值 iou=0.45, # NMS的IoU阈值 show_labels=True, # 显示标签 show_conf=True, # 显示置信度 line_thickness=2 # 边框线条粗细)
print(f"推理完成!处理了 {len(results)} 张图片")print("结果保存在 runs/detect/predict/ 目录中")
复制代码


用户头像

Jason黄

关注

还未添加个人签名 2018-10-18 加入

云原生、AI Infra领域从业者

评论

发布
暂无评论
Yolo模型训练的第一个Step_yolo_Jason黄_InfoQ写作社区