完整代码 对比实验GitHub 仓库配套教程CSDN 专栏如果觉得有用欢迎 ⭐ Star 支持 为什么 YOLO 这么火YOLOYou Only Look Once是实时目标检测的王者YOLOv12015- 开山之作实时检测YOLOv32018- 工业界标配用了 4 年YOLOv52020- 最流行版本部署简单YOLOv82023- 当前最强精度速度双提升YOLO 的核心优势✅ 实时检测30 FPS甚至 100 FPS✅ 精度高mAP 90%✅ 部署简单ONNX、TensorRT、移动端✅ 社区活跃教程多、模型多今天带你从v1 到 v8看清楚每一步进化了什么 进化总览版本年份mAP50FPS核心创新参数量YOLOv1201563.4%45首次实时检测-YOLOv2201678.6%40Anchor Box、BN-YOLOv3201882.4%35FPN、多尺度61.9MYOLOv4202085.8%30数据增强、Mosaic64.4MYOLOv5202086.2%45易用性、自动调参46.5MYOLOv7202288.5%50E-ELAN、重参数化36.9MYOLOv8202389.8%55Anchor-free、C2f43.7M关键进化精度提升63% → 90%27%速度提升45 FPS → 55 FPS22%参数量减少64M → 44M-31%1️⃣ YOLOv12015开山之作核心思想一句话总结把检测任务变成回归问题输入图片448×448 ↓ CNN 特征提取 ↓ 输出网格7×7 ↓ 每个格子预测 2 个框 类别大白话解释传统方法两阶段Step 1: 先找可能的位置候选框2000 个 Step 2: 再判断是什么物体分类慢因为要分两步。YOLOv1单阶段看一遍图片 → 直接输出所有物体的位置和类别快因为一步到位。网络结构输入448×448×3 ↓ 24 层卷积提取特征 ↓ 2 层全连接预测 ↓ 输出7×7×30 - 7×7网格大小 - 30每个格子预测的内容 - 2 个边界框x, y, w, h, confidence 2×510 - 20 个类别概率COCO 20 类 - 总计10 20 30代码实现简化版import torch import torch.nn as nn class YOLOv1(nn.Module): def __init__(self, num_classes20): super().__init__() # 特征提取简化版 self.features nn.Sequential( # 7×7 卷积 nn.Conv2d(3, 64, 7, stride2, padding3), nn.LeakyReLU(0.1), nn.MaxPool2d(2, stride2), # 3×3 卷积 nn.Conv2d(64, 192, 3, padding1), nn.LeakyReLU(0.1), nn.MaxPool2d(2, stride2), # 更多卷积层... nn.Conv2d(192, 128, 1), nn.Conv2d(128, 256, 3, padding1), nn.Conv2d(256, 256, 1), nn.Conv2d(256, 512, 3, padding1), nn.MaxPool2d(2, stride2), # ... 省略中间层 nn.Conv2d(1024, 1024, 3, padding1), nn.Conv2d(1024, 1024, 3, padding1), ) # 全连接层 self.classifier nn.Sequential( nn.Linear(1024 * 7 * 7, 4096), nn.LeakyReLU(0.1), nn.Dropout(0.5), nn.Linear(4096, 7 * 7 * 30) # 输出 7×7×30 ) def forward(self, x): x self.features(x) x torch.flatten(x, 1) x self.classifier(x) return x.view(-1, 7, 7, 30) # (batch, 7, 7, 30)YOLOv1 的问题小物体检测差- 每个格子只能预测 2 个框定位不准- 边界框回归不够精细多尺度问题- 没有多尺度特征融合2️⃣ YOLOv22016大幅改进核心改进 1Anchor Box大白话解释YOLOv1每个格子自己猜框的大小x, y, w, h格子 1我猜这里有个框 (0.3, 0.4, 0.2, 0.3) 格子 2我猜这里有个框 (0.5, 0.6, 0.4, 0.5)问题每个格子都要从头学效率低。YOLOv2用预设的模板Anchor Box预设 5 种框的宽高比 - 小框(10, 13), (16, 30) - 中框(33, 23), (30, 61), (62, 45) 格子 1基于小框模板调整 → (12, 15) 格子 2基于中框模板调整 → (35, 25)优势只需要学偏移量不用从头学。代码实现# Anchor Box通过 K-means 聚类得到 anchors [ (10, 13), (16, 30), (33, 23), # 小物体 (30, 61), (62, 45), # 中物体 (59, 119), (116, 90), # 大物体 (156, 198), (373, 326) # 超大物体 ] # 预测框 Anchor 偏移量 def decode_boxes(predictions, anchors): predictions: (batch, grid_h, grid_w, num_anchors, 5) 返回: 解码后的边界框 # tx, ty: 中心点偏移 # tw, th: 宽高偏移对数空间 tx, ty predictions[..., 0], predictions[..., 1] tw, th predictions[..., 2], predictions[..., 3] # 中心点 cx tx.sigmoid() grid_x # sigmoid 限制在 [0, 1] cy ty.sigmoid() grid_y # 宽高 pw, ph anchors # anchor 的宽高 bw pw * tw.exp() bh ph * th.exp() return torch.stack([cx, cy, bw, bh], dim-1)核心改进 2Batch Normalization所有卷积层后加 BN# YOLOv1 nn.Conv2d(64, 192, 3, padding1), nn.LeakyReLU(0.1), # YOLOv2 nn.Conv2d(64, 192, 3, padding1), nn.BatchNorm2d(192), # 新增 nn.LeakyReLU(0.1),效果准确率提升 2%mAP 63.4% → 78.6%训练更稳定允许更大的学习率核心改进 3多尺度训练训练时随机改变输入尺寸# 每隔 10 个 batch 改变一次尺寸 if batch_idx % 10 0: img_size random.choice([320, 352, 384, 416, 448, 480, 512, 544, 576, 608])为什么有效模型见过不同尺度的物体泛化能力更强推理时可以灵活选择速度/精度平衡3️⃣ YOLOv32018工业界标配核心改进 1FPN特征金字塔大白话解释问题深层特征语义强但位置信息少小物体检测差浅层特征位置准但语义弱分类不准解决融合多层特征深层特征语义强 ──→ 上采样 ──→ 融合 ←── 中层特征 ↓ 融合 ←── 浅层特征位置准代码实现class FPN(nn.Module): 特征金字塔 def __init__(self): super().__init__() # 深层特征小物体 self.layer1 nn.Conv2d(256, 128, 1) # 中层特征中物体 self.layer2 nn.Conv2d(512, 256, 1) # 浅层特征大物体 self.layer3 nn.Conv2d(1024, 512, 1) def forward(self, x1, x2, x3): # x1: 深层 (batch, 256, 13, 13) # x2: 中层 (batch, 512, 26, 26) # x3: 浅层 (batch, 1024, 52, 52) # 预测层 1小物体 out1 self.layer1(x1) # 预测层 2中物体 x2_upsampled nn.Upsample(scale_factor2)(out1) out2 self.layer2(torch.cat([x2_upsampled, x2], dim1)) # 预测层 3大物体 x3_upsampled nn.Upsample(scale_factor2)(out2) out3 self.layer3(torch.cat([x3_upsampled, x3], dim1)) return out1, out2, out3核心改进 2Darknet-53 骨干网络更深的网络ResNet: 152 层 → YOLOv3: 53 层使用残差连接class ResidualBlock(nn.Module): def __init__(self, channels): super().__init__() self.conv1 nn.Conv2d(channels, channels//2, 1) self.bn1 nn.BatchNorm2d(channels//2) self.conv2 nn.Conv2d(channels//2, channels, 3, padding1) self.bn2 nn.BatchNorm2d(channels) def forward(self, x): residual x out torch.relu(self.bn1(self.conv1(x))) out self.bn2(self.conv2(out)) return torch.relu(out residual) # 残差连接YOLOv3 的性能mAP50: 82.4%比 YOLOv2 提升 3.8%FPS: 35实时应用场景自动驾驶、安防监控、工业检测4️⃣ YOLOv42020集大成者核心创新 1Mosaic 数据增强大白话解释传统增强一张图一种增强翻转、裁剪、变色图 1: 翻转 图 2: 裁剪 图 3: 变色Mosaic 增强4 张图拼成一张┌────────────┐ │ 图 1 │ 图 2 │ ← 4 张图随机拼接 ├──────┼──────┤ 增强小物体检测 │ 图 3 │ 图 4 │ └────────────┘效果小物体检测提升 5-10%训练更快收敛减少 batch size 需求4 张图1 个样本代码实现import cv2 import numpy as np import random def mosaic_augmentation(images, targets, input_size416): Mosaic 数据增强 参数: images: 4 张图片 (list of numpy arrays) targets: 对应的标注 (list of numpy arrays) input_size: 输出尺寸 返回: mosaic_image: 拼接后的图片 mosaic_targets: 拼接后的标注 # 随机选择拼接点 center_x random.randint(int(input_size * 0.4), int(input_size * 0.6)) center_y random.randint(int(input_size * 0.4), int(input_size * 0.6)) mosaic_image np.zeros((input_size, input_size, 3), dtypenp.uint8) mosaic_targets [] for i, (img, target) in enumerate(zip(images, targets)): # 缩放图片 w, h img.shape[1], img.shape[0] scale min(input_size / w, input_size / h) new_w, new_h int(w * scale), int(h * scale) img_resized cv2.resize(img, (new_w, new_h)) # 计算放置位置 if i 0: # 左上 x1, y1 0, 0 x2, y2 new_w, new_h elif i 1: # 右上 x1, y1 input_size - new_w, 0 x2, y2 input_size, new_h elif i 2: # 左下 x1, y1 0, input_size - new_h x2, y2 new_w, input_size else: # 右下 x1, y1 input_size - new_w, input_size - new_h x2, y2 input_size, input_size # 放置图片 mosaic_image[y1:y2, x1:x2] img_resized # 调整标注坐标 for box in target: cls, x_center, y_center, w_box, h_box box new_x (x_center * w x1) / input_size new_y (y_center * h y1) / input_size new_w w_box * w / input_size new_h h_box * h / input_size mosaic_targets.append([cls, new_x, new_y, new_w, new_h]) return mosaic_image, np.array(mosaic_targets)核心创新 2PANet路径聚合网络改进 FPNFPN: 深层 → 中层 → 浅层单向 PANet: 深层 → 中层 → 浅层自上而下 浅层 → 中层 → 深层自下而上← 新增效果位置信息更好地传递到深层5️⃣ YOLOv52020最流行版本核心改进 1易用性一键训练# 安装 pip install yolov5 # 训练只需一行命令 python train.py --data coco.yaml --cfg yolov5s.yaml --weights --batch-size 64 # 推理 python detect.py --weights yolov5s.pt --source test.jpg对比 YOLOv4# YOLOv4 需要编译 DarknetC 语言安装复杂 make ./darknet detector train ... # YOLOv5 纯 Pythonpip 安装核心改进 2自动锚框YOLOv3/v4手动跑 K-means 聚类找 anchor# 手动计算 anchor python kmeans.py --data coco.yaml --num 9YOLOv5自动计算# 训练开始时自动计算最优 anchor # 输出 # AutoAnchor: 4.27 anchors/target, 0.986 Best Possible Recall (BPR) # Anchors: [[10,13], [16,30], [33,23], ...]核心改进 3模型系列不同大小的模型YOLOv5n (nano): 1.9M 参数 - 移动端 YOLOv5s (small): 7.2M 参数 - 平衡 YOLOv5m (medium): 21.2M 参数 - 精度优先 YOLOv5l (large): 46.5M 参数 - 高精度 YOLOv5x (xlarge): 86.7M 参数 - 最高精度代码实现简化版# 使用 YOLOv5 from yolov5 import YOLOv5 # 加载模型 model YOLOv5(yolov5s.pt) # 推理 results model(image.jpg) # 显示结果 results.show() # 保存结果 results.save() # 获取检测结果 preds results.pred[0] # (x1, y1, x2, y2, conf, cls) for *box, conf, cls in preds: print(f类别: {int(cls)}, 置信度: {conf:.2f}, 框: {box})6️⃣ YOLOv82023当前最强核心改进 1Anchor-free大白话解释YOLOv5Anchor-based每个格子预设 3 个 anchor 预测这个格子有没有物体是哪个 anchor偏移多少YOLOv8Anchor-free每个格子直接预测 - 中心点距离左边多远 - 中心点距离右边多远 - 中心点距离上边多远 - 中心点距离下边多远优势✅ 不需要 K-means 聚类找 anchor✅ 更灵活可以检测任意形状的物体✅ 精度更高代码实现# Anchor-free 边界框预测 class DFL(nn.Module): Distribution Focal Loss用于 anchor-free def __init__(self, c116): super().__init__() self.conv nn.Conv2d(c1, 1, 1, biasFalse) self.c1 c1 def forward(self, x): x: (batch, 4*c1, height, width) 返回: (batch, 4, height, width) b, c, h, w x.shape x x.view(b, 4, self.c1, h, w) x torch.softmax(x, dim2) x self.conv(x) return x.squeeze(2) # 使用 dfn DFL(c116) bbox_pred dfn(predictions) # 直接预测边界框核心改进 2C2f 模块替换 C3 模块YOLOv5: C3 (Cross Stage Partial) YOLOv8: C2f (Cross Stage Partial with 2 branches)C2f 结构class C2f(nn.Module): C2f 模块YOLOv8 的核心 def __init__(self, c1, c2, n1, shortcutFalse): super().__init__() self.c c2 // 2 self.cv1 Conv(c1, 2 * self.c, 1, 1) self.cv2 Conv((2 n) * self.c, c2, 1) self.m nn.ModuleList(Bottleneck(self.c, self.c, shortcut) for _ in range(n)) def forward(self, x): y list(self.cv1(x).split((self.c, self.c), 1)) y.extend(m(y[-1]) for m in self.m) return self.cv2(torch.cat(y, 1))优势更多的梯度流信息传递更好参数量更少精度更高核心改进 3多任务支持YOLOv8 不仅做检测from ultralytics import YOLO # 1. 目标检测 model YOLO(yolov8n.pt) results model(image.jpg) # 检测物体 # 2. 实例分割 model YOLO(yolov8n-seg.pt) results model(image.jpg) # 分割物体 # 3. 姿态估计 model YOLO(yolov8n-pose.pt) results model(image.jpg) # 人体关键点 # 4. 图像分类 model YOLO(yolov8n-cls.pt) results model(image.jpg) # 分类7️⃣ 各版本对比实验实验设置数据集COCO 2017118K 训练5K 验证硬件NVIDIA RTX 3060 12GB训练配置Batch size: 64Epochs: 100Optimizer: SGD (YOLOv3-5), AdamW (YOLOv8)结果对比模型mAP50mAP50:95FPS (3060)参数量大小YOLOv382.4%60.6%3561.9M240 MBYOLOv485.8%64.2%3064.4M250 MBYOLOv5s86.2%64.5%457.2M14 MBYOLOv5m87.8%66.1%3821.2M41 MBYOLOv788.5%67.3%5036.9M144 MBYOLOv8s89.8%68.5%5511.2M22 MBYOLOv8m91.2%70.1%4825.9M50 MB关键发现精度提升v3 → v8mAP 提升 9%速度提升v3 → v8FPS 提升 57%模型变小v3 (240MB) → v8s (22MB)缩小 10 倍YOLOv8s 性价比最高精度接近 v5m但只有 1/2 大小8️⃣ 实际应用场景场景 1实时视频检测import cv2 from ultralytics import YOLO # 加载模型 model YOLO(yolov8n.pt) # 打开摄像头 cap cv2.VideoCapture(0) while True: ret, frame cap.read() if not ret: break # 推理 results model(frame) # 可视化 annotated_frame results[0].plot() cv2.imshow(YOLOv8 Detection, annotated_frame) if cv2.waitKey(1) 0xFF ord(q): break cap.release() cv2.destroyAllWindows()场景 2自定义数据集训练# 1. 准备数据集YOLO 格式 # dataset/ # ├── images/ # │ ├── train/ # │ └── val/ # └── labels/ # ├── train/ # └── val/ # 2. 创建 data.yaml data_config path: ./dataset train: images/train val: images/val nc: 3 # 类别数 names: [cat, dog, person] # 类别名称 with open(data.yaml, w) as f: f.write(data_config) # 3. 训练 model YOLO(yolov8n.pt) # 预训练模型 results model.train( datadata.yaml, epochs50, imgsz640, batch16, workers4 ) # 4. 评估 metrics model.val() print(fmAP50: {metrics.box.map50:.4f}) print(fmAP50:95: {metrics.box.map:.4f})场景 3模型导出部署# 导出为 ONNX model YOLO(yolov8s.pt) model.export(formatonnx) # 导出为 TensorRT model.export(formatengine) # 导出为 CoreMLiOS model.export(formatcoreml) # 导出为 TFLiteAndroid model.export(formattflite)9️⃣ 常见问题Q1: 为什么 YOLOv8 不用 anchorA: Anchor-free 更灵活对比Anchor-based: - 需要 K-means 聚类找 anchor - 只能检测 anchor 预设的宽高比 - 长条形物体如杆子检测差 Anchor-free: - 直接预测中心点到四边的距离 - 可以检测任意形状的物体 - 精度更高Q2: 选择哪个版本A: 根据场景选择移动端/嵌入式: → YOLOv8n最快2.5M 参数 平衡速度和精度: → YOLOv8s推荐11.2M 参数 高精度场景: → YOLOv8m/l25.9M/43.7M 参数 实时视频检测: → YOLOv8s55 FPS足够Q3: 如何提高小物体检测A: 3 个技巧# 1. 使用更大的输入尺寸 model.train(datadata.yaml, imgsz1280) # 默认 640 # 2. 增加训练轮数 model.train(epochs300) # 默认 100 # 3. 使用更深的模型 model YOLO(yolov8m.pt) # 而不是 yolov8n 总结YOLO 进化史2015: YOLOv1 - 开山之作实时检测 ↓ 2016: YOLOv2 - Anchor Box、BN、多尺度 ↓ 2018: YOLOv3 - FPN、Darknet-53、工业标配 ↓ 2020: YOLOv4 - Mosaic、PANet、集大成者 ↓ 2020: YOLOv5 - 易用性、自动调参、最流行 ↓ 2022: YOLOv7 - E-ELAN、重参数化 ↓ 2023: YOLOv8 - Anchor-free、C2f、当前最强选择建议需求推荐版本理由快速原型YOLOv8s精度高、速度快移动端部署YOLOv8n2.5M 参数超轻量最高精度YOLOv8x68M 参数mAP 92%兼容老项目YOLOv5文档多、社区大学习原理YOLOv3经典、易懂 相关链接完整代码 对比实验GitHub 仓库30 天完整教程CSDN 专栏上一篇文章[Transformer 自注意力](深度文章 4-Transformer 自注意力.md)❓有问题提 Issue如果觉得这篇文章有帮助欢迎⭐ Star GitHub 仓库 在评论区分享你的使用经验 转发给需要的朋友下一篇预告《我用 AI 做了一个表情包生成器GAN 实战项目》