🎯 08 · YOLO 系列目标检测详解(v1 → v11 全演进 · 故事版)¶
上一篇
04-目标检测给你备好了零件(IoU/NMS/anchor/mAP);这一篇把这些零件装成 一部 10 年的技术进化史:为什么 YOLO 从「7×7 网格」一路进化到「无锚框 + 分布回归」, 每一代解决上一个痛点、又埋下下一个伏笔。阅读方式:按「痛点 → 方案 → 新痛点」的故事线走,把每一代的动机先记下,再背结构与数字。 下一篇
09-U-Net系列是像素级任务的同类故事(分割家族),再下一篇10-SAM是视觉基础模型时代。
🧩 一句话主线:一个框怎么描述? v1 直接回归「格内偏移 + 相对宽高」→ v2 引入 anchor(回归变成小偏移)→ v3 上 多尺度 FPN(大小物体分开管)→ v4/v5 把训练配方做极致 → v6/v7 卷效率 → v8 回归 anchor-free + 分布回归 → v9/v10/v11 卷梯度信息与注意力。
核心概念¶
(a) 🗂️ YOLO 系列目标检测详解知识结构¶
这篇文章把 YOLO 从 v1 到 v11 讲成一部"痛点→方案→新痛点"的技术进化史,每一代的动机先记下,再背结构与数字。
flowchart TB
Node1["🎯 YOLOv1 网格回归"]
Node1 --> Node2["⚓ YOLOv2 Anchor起源"]
Node2 --> Node3["🗼 YOLOv3 多尺度FPN"]
Node3 --> Node4["🧪 YOLOv4 训练配方"]
Node4 --> Node5["🛠️ YOLOv5 工程化"]
Node5 --> Node6["⚡ YOLOv6/v7 效率革命"]
Node6 --> Node7["🕊️ YOLOv8 无锚框"]
Node7 --> Node8["🧬 YOLOv9/v10/v11 PGI与PSA"]
Node8 --> Node9["📊 跨版本横向对比"]
- YOLOv1 网格回归:把 448×448 图切成 7×7 网格,每格负责中心落在格内的物体,预测 B=2 个框。损失五项之和,w/h 开根号让大小框误差同等重视——开山之作但一格一物、小物体漏检。
- YOLOv2 Anchor起源:直接回归绝对坐标难收敛,用 K-Means(IoU 距离)对 GT 聚类出 K=5 个常见形状做先验,网络改学"相对 anchor 的小偏移"——回归任务被降维成预测小修正。
- YOLOv3 多尺度FPN:v2 只拼一个浅层小物体仍漏检,v3 从 backbone 抽三个尺度(stride 8/16/32 → 52/26/13 网格),大特征图管小物体、小特征图管大物体,9 个 anchor 按尺度分组。
- YOLOv4 训练配方:v3 结构定了,v4 把训练配方拉满——CSPDarknet(通道切半一半直连一半卷积)、Mish 激活、Mosaic 增强(4 张图拼 1 张)、CIoU 损失。v4 的核心是配方不是网络本身。
- YOLOv5 工程化:没有论文的工业王者——auto-anchor 自动聚类、超参进化、AMP 混合精度、一键导出 ONNX/TFLite/TensorRT。Focus 层隔像素采样拼通道,开局就省一半算力。
- YOLOv6/v7 效率革命:v6 把分类和回归解耦成两个头(任务冲突缓解);v7 的 RepConv 训练 3 分支、推理时数学等价融合成 1 个卷积——训练学习好、推理跑得快。
- YOLOv8 无锚框:anchor 机制繁琐(聚类/分配/IoU 匹配),v8 回归目标改成中心点到四边距离 (l,t,r,b),解码直出框;DFL 分布回归让框回归对尺度更鲁棒;TaskAlignedAssigner 做标签分配。
- YOLOv9/v10/v11 PGI与PSA:v9 的 PGI 给浅层修一条梯度直达高速公路(辅助分支训练时喂梯度、推理剪掉);v10/v11 的 PSA 只对部分通道做自注意力(一半注意力一半卷积),算力省一大半精度掉很少。
- 跨版本横向对比:v1 网格直配、v2 anchor+BN、v3 FPN 多尺度、v4 训练配方、v5 工程化、v6/v7 解耦头与重参数化、v8 无锚框+DFL、v9 PGI、v10/v11 PSA——选型看场景,面试按故事线背。
§0 前情提要:检测的三次思想跃迁(知识链起点)¶
任务定义:检测 = 分类 + 定位,输出不定数量的 $(x_1,y_1,x_2,y_2,\text{class},\text{conf})$。
三次跃迁(这就是全部故事线):
| 范式 | 代表 | 思想 | 代价 |
|---|---|---|---|
| 滑动窗口 | 2012 前 | 全图滑窗+分类 | 计算爆炸、窗口要试无数尺寸 |
| 两阶段 | R-CNN→Faster | 候选框(搜索/学习)→ 逐框精修 | 慢(2k 框两次前向) |
| 一阶段 | YOLO/SSD | 全图一次前向直接回归框 | 精度低 → 靠十年迭代追平 |
本篇的主角是一阶段:它的起步很朴素(v1),但十年的每一次修补都对应一个可讲的面试题。 先把 v1 的朴素方案吃透,后面每代都只是"给这个朴素方案打补丁"。
第 1 幕 · YOLOv1(2016):一个格子一个梦¶
痛点:Faster R-CNN 已经在 COCO 上很强,但 2k 个候选框两次前向,只能跑 5 FPS。 能不能把整张图当成一个回归任务,一次前向输出所有框?
方案(朴素但天才):把 448×448 图切成 $7\times7$ 网格。
- 每个格子负责「中心落在自己范围内的物体」
- 每格预测 $B=2$ 个框:$(x,y,w,h,conf)$ —— $(x,y)$ 相对格子、$(w,h)$ 相对整图、$conf$ = 有物体的置信度
- 每格预测 $C=20$ 个类别分数(PASCAL)
- 输出张量:$7\times7\times30$($B\cdot5+C = 2\times5+20$),全图只有一次前向
为什么敢这么做:把检测当成「结构化回归」——网络端到端地学「图像 → 框集合」。
# ---- matplotlib 中文字体(防图内中文乱码)----
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'Songti SC', 'Arial Unicode MS', 'DejaVu Sans']
matplotlib.rcParams['axes.unicode_minus'] = False
# -------------------------------------------
import numpy as np
# ================= YOLOv1 损失:五项之和(手写 + 手算对账) =================
# 张量 (S,S,B,5+C):每格每框预测 (x,y,w,h,conf) + C 个类别分数。
# 掩码约定:1_obj = 该格子有物体(负责任的框);1_noobj = 没有(背景格子占绝大多数)。
def yolo_v1_loss(pred, target, S=2, B=1, C=3, lam_coord=5.0, lam_noobj=0.5):
pred = np.asarray(pred, float); target = np.asarray(target, float)
obj = target[..., 4:5] # 1_obj 掩码
noobj = 1.0 - obj # 1_noobj 掩码
# ① 中心坐标 MSE:λ_coord=5 —— 坐标直接决定框在哪,权重最大
# (为什么用平方:方便求导,且对大偏差惩罚更狠)
xy = obj * (target[..., :2] - pred[..., :2]) ** 2
# ② 宽高「开根号」MSE:对 √w、√h 求差再平方。
# 为什么开根号:直接算 (w−ŵ)² 会让大框误差主导(大框 w≈0.9、小框 w≈0.1,
# 同样 0.05 的绝对误差,大框损失是小框的 81 倍);开根号把「相对误差」拉平。
wh = obj * (np.sqrt(target[..., 2:4]) - np.sqrt(np.clip(pred[..., 2:4], 1e-6, None))) ** 2
# ③ 有物体格子的置信度 MSE(conf = P(有物体)·IoU,v1 用两者的乘积当回归目标)
conf = obj * (target[..., 4:5] - pred[..., 4:5]) ** 2
# ④ 无物体格子的置信度 MSE:背景格子远多于前景,必须显式学「这里没东西」,
# 但权重压到 λ_noobj=0.5,否则模型会被「全输出低置信度」带偏。
conf_no = noobj * (target[..., 4:5] - pred[..., 4:5]) ** 2
# ⑤ 类别 MSE:v1 连分类都用 MSE(v3 起换成 BCE,见第 3 幕)
cls = obj * (target[..., 5:] - pred[..., 5:]) ** 2
return (lam_coord * xy.sum() + lam_coord * wh.sum()
+ conf.sum() + lam_noobj * conf_no.sum() + cls.sum())
# ---- 手工小例子:只有格子 (0,0) 有物体,逐步手算与代码对账 ----
S, B, C = 2, 1, 3
pred = np.zeros((S, S, B, 5 + C))
target = np.zeros_like(pred)
pred[0, 0, 0] = [0.3, 0.4, 0.5, 0.5, 0.8, 0.6, 0.1, 0.3] # 预测:框(0.3,0.4,0.5,0.5) 置信0.8 类别(0.6,0.1,0.3)
target[0, 0, 0] = [0.3, 0.4, 0.25, 0.25, 1.0, 1.0, 0.0, 0.0] # 真值:框(0.3,0.4,0.25,0.25) 置信1 one-hot(1,0,0)
loss = yolo_v1_loss(pred, target, S, B, C)
# 手算:
# ① 坐标差全 0 → 0
# ② (√0.25−√0.5)² 的 w、h 两项 = 2·(0.5−√0.5)² ≈ 2×0.0429 = 0.0858,×λ_coord=5
# ③ (1−0.8)² = 0.04
# ④ 其余格子 pred/target 置信都是 0 → 0
# ⑤ (1−0.6)²+(0−0.1)²+(0−0.3)² = 0.16+0.01+0.09 = 0.26
manual = 5.0 * 0.0 + 5.0 * 2 * (0.5 - np.sqrt(0.5)) ** 2 + 0.04 + 0.5 * 0.0 + 0.26
print('YOLOv1 loss = %.4f(手算 %.4f)' % (loss, manual))
assert abs(loss - manual) < 1e-6
print('对照通过:开根号项、λ_coord、λ_noobj 全部按设计生效')
YOLOv1 loss = 0.7289(手算 0.7289) 对照通过:开根号项、λ_coord、λ_noobj 全部按设计生效
v1 的推理:编解码 + 置信度 + NMS 一条流水线¶
训练学的是「相对量」,推理要还原成「绝对框」:解码(网格偏移 → 图像坐标)→ 按置信度过滤 → NMS 去重(同一物体多个框只留一个,NMS 原理见 04 篇)。 下面把 v1 的完整推理流水线手写一遍。
# ================= YOLOv1 编解码 + 推理流水线(手写) =================
S, IMG = 7, 448 # v1 真参数:7x7 网格、448 输入
def yolo_encode(box, S=S, IMG=IMG):
# 绝对框 (x1,y1,x2,y2) -> (格子坐标 gx,gy, 格内偏移 cx_off,cy_off, 相对宽高 w_rel,h_rel)
cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2 # 中心点
w, h = box[2] - box[0], box[3] - box[1]
gx, gy = int(cx / IMG * S), int(cy / IMG * S) # 中心落在哪个格子
cx_off, cy_off = cx / IMG * S - gx, cy / IMG * S - gy # 格内偏移 ∈ [0,1)
return gx, gy, cx_off, cy_off, w / IMG, h / IMG
def yolo_decode(gx, gy, cx_off, cy_off, w_rel, h_rel, S=S, IMG=IMG):
# 逆运算:格子 + 偏移 -> 图像绝对坐标(训练目标就是让这组数逼近真值)
cx = (gx + cx_off) / S * IMG
cy = (gy + cy_off) / S * IMG
w, h = w_rel * IMG, h_rel * IMG
return np.array([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2])
def iou(a, b):
ix1 = max(a[0], b[0]); iy1 = max(a[1], b[1]); ix2 = min(a[2], b[2]); iy2 = min(a[3], b[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
u = (a[2]-a[0])*(a[3]-a[1]) + (b[2]-b[0])*(b[3]-b[1]) - inter
return inter / max(u, 1e-9)
def nms_boxes(boxes, scores, iou_thr=0.5):
# NMS:按置信度降序,依次保留最高分框、抑制与其重叠>阈值的框(04 篇详解,这里内联复刻)
order = np.argsort(-scores)
keep = []
while order.size:
i = order[0]; keep.append(i)
rest = order[1:]
if rest.size:
ious = np.array([iou(boxes[i], boxes[j]) for j in rest])
order = rest[ious <= iou_thr] # 只留与最高分框不重叠的
else:
order = rest
return np.array(keep)
# ---- 推理流水线演示:3 个重叠预测 -> 阈值过滤 -> NMS 去重 ----
boxes = np.array([[100, 80, 200, 180], [110, 90, 210, 190], [300, 250, 380, 330]], float) # 前两个重叠
scores = np.array([0.9, 0.7, 0.4])
keep0 = np.where(scores >= 0.3)[0] # ① 置信度阈值过滤(保留 0.9/0.7/0.4)
keep = nms_boxes(boxes[keep0], scores[keep0]) # ② NMS:前两个 IoU 高 -> 只留 0.9 那个
print('解码示例:格子(3,2)偏移(0.4,0.4)宽高(0.6,0.5) ->', yolo_decode(3, 2, 0.4, 0.4, 0.6, 0.5))
print('推理保留框数: %d(期望 2:重叠的被 NMS 抑制)' % len(keep))
# 编解码 round-trip 一致性
for b in boxes:
gx, gy, ox, oy, wr, hr = yolo_encode(b)
assert np.allclose(yolo_decode(gx, gy, ox, oy, wr, hr), b)
assert len(keep) == 2
print('编解码 round-trip 通过 ✓')
解码示例:格子(3,2)偏移(0.4,0.4)宽高(0.6,0.5) -> [ 83.2 41.6 352. 265.6] 推理保留框数: 2(期望 2:重叠的被 NMS 抑制) 编解码 round-trip 通过 ✓
# ================= YOLOv1:检测头 nn.Module + 五项损失(torch 版) =================
import torch
import torch.nn as nn
class YOLOv1Head(nn.Module):
# 输入 backbone 特征 (N,1024,7,7) -> (N,S,S,B*5+C):把整图检测当成一个回归任务
def __init__(self, in_ch=1024, S=7, B=2, C=20):
super().__init__()
self.S, self.B, self.C = S, B, C
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(in_ch * S * S, 4096),
nn.LeakyReLU(0.1),
nn.Dropout(0.5),
nn.Linear(4096, S * S * (B * 5 + C)),
)
def forward(self, x):
out = self.fc(x)
return out.view(-1, self.S, self.S, self.B * 5 + self.C)
def v1_loss_torch(pred, target, lam_coord=5.0, lam_noobj=0.5):
# pred/target: (N,S,S,B,5+C)——五项损失全部张量化(与上面 numpy 版同语义)
obj = target[..., 4:5] # 1_obj
noobj = 1.0 - obj # 1_noobj
xy = obj * (target[..., :2] - pred[..., :2]) ** 2 # ① 坐标
wh = obj * (target[..., 2:4].sqrt() - pred[..., 2:4].clamp(min=1e-6).sqrt()) ** 2 # ② √w/√h
conf = obj * (target[..., 4:5] - pred[..., 4:5]) ** 2 # ③ 有物置信
conf_no = noobj * (target[..., 4:5] - pred[..., 4:5]) ** 2 # ④ 背景置信
cls = obj * (target[..., 5:] - pred[..., 5:]) ** 2 # ⑤ 类别 MSE
return (lam_coord * xy.sum() + lam_coord * wh.sum()
+ conf.sum() + lam_noobj * conf_no.sum() + cls.sum())
torch.manual_seed(0)
head = YOLOv1Head(in_ch=64, S=2, B=1, C=3) # 迷你版:小输入便于演示
feat = torch.randn(2, 64, 2, 2)
out = head(feat)
print('YOLOv1Head: (2,64,2,2) ->', tuple(out.shape))
assert tuple(out.shape) == (2, 2, 2, 8)
# 损失对照:把上面 numpy 手算的 pred/target 原样搬来(格子(0,0)有物体)
pred = torch.zeros(1, 2, 2, 1, 8); target = torch.zeros_like(pred)
pred[0, 0, 0, 0] = torch.tensor([0.3, 0.4, 0.5, 0.5, 0.8, 0.6, 0.1, 0.3])
target[0, 0, 0, 0] = torch.tensor([0.3, 0.4, 0.25, 0.25, 1.0, 1.0, 0.0, 0.0])
loss = v1_loss_torch(pred, target)
manual = 5.0 * 2 * (0.5 - 0.5 ** 0.5) ** 2 + (1 - 0.8) ** 2 + 0.26
print('v1 loss(torch) = %.4f(对照手算 %.4f)' % (loss.item(), manual))
assert abs(loss.item() - manual) < 1e-4
print('对照通过:v1 开根号项、λ_coord、λ_noobj 在 torch 张量版同样生效 ✓')
# ============ YOLOv1 完整网络:Conv 骨干 + 7x7 网格回归头(torch) ============
import torch
import torch.nn as nn
class YOLOv1Net(nn.Module):
# mini 版:4 个 stride2 卷积把 64x64 图降到 4x4,adaptive pool 对齐 7x7 网格,
# 每个网格位置输出 B*5+C 维(中心偏移 + 宽高 + 置信 + 类别)——整图一次前向出所有框
def __init__(self, S=7, B=2, C=20):
super().__init__()
self.S, self.B, self.C = S, B, C
self.backbone = nn.Sequential(
nn.Conv2d(3, 32, 3, 2, 1), nn.BatchNorm2d(32), nn.LeakyReLU(0.1),
nn.Conv2d(32, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.LeakyReLU(0.1),
nn.Conv2d(64, 128, 3, 2, 1), nn.BatchNorm2d(128), nn.LeakyReLU(0.1),
nn.Conv2d(128, 256, 3, 2, 1), nn.BatchNorm2d(256), nn.LeakyReLU(0.1),
)
self.grid = nn.AdaptiveAvgPool2d((S, S)) # 任意输入 -> 恰好 SxS 网格
self.head = nn.Conv2d(256, B * 5 + C, 1) # 每格输出 (B*5+C) 维
def forward(self, x):
f = self.grid(self.backbone(x)) # (N,256,S,S)
out = self.head(f) # (N,B*5+C,S,S)
return out.permute(0, 2, 3, 1) # (N,S,S,B*5+C)
torch.manual_seed(0)
net = YOLOv1Net(S=7, B=2, C=20)
x = torch.randn(2, 3, 64, 64)
out = net(x)
print('YOLOv1Net: (2,3,64,64) ->', tuple(out.shape), '(7x7 网格,每格 30 维 = 2*5+20)')
assert tuple(out.shape) == (2, 7, 7, 30)
# 与 v1_loss_torch 无缝衔接:view 成 (N,S,S,B,5+C) 直接算损失
pred4 = out.view(2, 7, 7, 2, 5 + 20)
target4 = torch.zeros_like(pred4)
loss = v1_loss_torch(pred4, target4)
print('view 成 (N,S,S,B,5+C):', tuple(pred4.shape), '→ 直接喂 v1_loss_torch,loss = %.4f ✓' % loss.item())
print('要点:v1 = 一次前向出全部框(无锚框、无 RPN),简单粗暴但小物体漏检 → 逼出 v2 的 anchor')
# ===== YOLOv1 模型架构图 =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 3.0))
ax.set_xlim(0, 10); ax.set_ylim(0, 2.2); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=10)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.8))
box(0.2, 0.8, 1.3, 0.7, '输入图像\n448×448×3', fc='lightyellow')
box(1.9, 0.8, 1.7, 0.7, '卷积骨干\n(最后 7×7×1024)', fc='lightblue')
box(4.0, 0.8, 1.5, 0.7, '全连接\n4096 维', fc='lightblue')
box(5.9, 0.8, 1.5, 0.7, 'FC 回归头\n7×7×30', fc='lightgreen')
box(7.8, 0.8, 1.9, 0.7, '解码 + NMS\n→ 框 + 类别', fc='lightsalmon')
arrow(1.5, 1.15, 1.9, 1.15); arrow(3.6, 1.15, 4.0, 1.15)
arrow(5.5, 1.15, 5.9, 1.15); arrow(7.4, 1.15, 7.8, 1.15)
# 标注每格输出含义
ax.text(6.65, 0.35, '每格 30 维 = 2框×5 + 20类', ha='center', fontsize=9, color='#2E5F9E')
ax.set_title('YOLOv1 架构:整图一次前向,直接回归出所有框', fontsize=13)
plt.tight_layout(); plt.show()
v1 的四个痛点(记住这页,v2/v3 全是来补窟窿的)¶
- 一格一物:两个物体中心落在同一格子 → 只能报一个(重叠物体无解)
- 小物体漏检:7×7=49 个格子对大图上的小物体太稀疏(小猫只有几个像素)
- 框数固定:每格固定 2 个框,物体多时框不够、物体少时浪费
- 定位粗糙:$(x,y)$ 直接回归绝对坐标难收敛;宽高比例没先验
🔄 转折点:第 2 个痛点(小物体)和第 4 个痛点(定位)直接催生了 v2 的 anchor。
第 2 幕 · YOLOv2(2017):anchor —— 给回归一个「起点」¶
痛点:直接回归任意框的坐标 → 收敛慢、框的比例千奇百怪。
方案:先验框(anchor)。对训练集 GT 框的宽高做聚类,得到 $K$ 个「常见形状」; 网络不再回归绝对坐标,而是回归「相对 anchor 的小偏移」: $$\hat{x} = a_x + t_x \cdot a_w,\quad \hat{w} = a_w \cdot e^{t_w}$$
为什么用 K-Means + IoU 距离:欧氏距离对大框敏感(大框差 0.1 和小框差 0.1 的欧氏距离一样, 但形状上差很多);IoU 衡量的是形状相似度,与尺寸解耦。
# ================= YOLOv2 的 anchor:手写 K-Means(IoU 距离) + sklearn 对照 =================
def kmeans_wh(wh, K=5, iters=50, seed=0):
# wh: (N,2) 的 (w,h);返回 K 个聚类中心(就是 anchor 的宽高)
rng = np.random.default_rng(seed)
centers = wh[rng.choice(len(wh), K, replace=False)].astype(float) # 随机抽 K 个真值框当初始中心
for _ in range(iters):
# 距离 = 1 − IoU(把宽高当中心对齐的两个框算重叠):形状越像距离越小
a = wh[:, None, :] # (N,1,2)
c = centers[None, :, :] # (1,K,2)
inter = np.minimum(a, c)[..., 0] * np.minimum(a, c)[..., 1] # 重叠宽 × 重叠高
union = a[..., 0] * a[..., 1] + c[..., 0] * c[..., 1] - inter
dist = 1 - inter / np.maximum(union, 1e-9)
assign = np.argmin(dist, axis=1) # 每个框归到最近的锚框簇
for k in range(K): # 重算中心 = 该簇框宽高的均值(EM 风格迭代)
if np.any(assign == k):
centers[k] = wh[assign == k].mean(axis=0)
return centers
# 合成 GT 宽高:三种形状簇(瘦长 / 正方 / 扁宽)——聚类应能找回这三种比例
rng = np.random.default_rng(3)
wh_gt = np.vstack([
rng.uniform(0.03, 0.08, (300, 2)) * [3, 1], # 瘦长:w >> h
rng.uniform(0.05, 0.12, (300, 2)), # 正方:w ≈ h
rng.uniform(0.03, 0.08, (300, 2)) * [1, 3], # 扁宽:w << h
])
centers = kmeans_wh(wh_gt, K=3, seed=0)
print('聚类出的 anchor 宽高(应各代表一个形状簇):')
for w, h in centers:
print(' w=%.4f h=%.4f(ratio=%.2f)' % (w, h, w / h))
assert centers.shape == (3, 2) and np.all(centers > 0)
ratios = centers[:, 0] / centers[:, 1]
assert ratios.max() > 1.5 and ratios.min() < 1 / 1.5 and np.any(np.abs(ratios - 1) < 0.5)
# ---- 对照:sklearn KMeans(欧氏距离)会怎样? ----
from sklearn.cluster import KMeans
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(wh_gt)
print('sklearn(欧氏) 中心:', np.round(km.cluster_centers_, 4))
# 结论:欧氏距离偏向大框,聚类结果被大框带偏;这就是 YOLO 坚持 IoU 距离的原因
# ========== 图:GT 宽高散点 + IoU 距离聚类中心 ==========
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(6.6, 5.0))
ax.scatter(wh_gt[:, 0], wh_gt[:, 1], s=6, alpha=0.45, color='#9ecae1', label='GT 框宽高')
ax.scatter(centers[:, 0], centers[:, 1], s=180, marker='*', color='#C44E52', label='IoU-KMeans 聚类中心')
ax.set_xlabel('w(相对图宽)'); ax.set_ylabel('h(相对图高)')
ax.set_title('anchor = 对 GT 宽高做 IoU 距离 K-Means 聚类', fontsize=12)
ax.legend(fontsize=9); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
聚类出的 anchor 宽高(应各代表一个形状簇): w=0.1727 h=0.0541(ratio=3.19) w=0.0882 h=0.0816(ratio=1.08) w=0.0529 h=0.1672(ratio=0.32)
sklearn(欧氏) 中心: [[0.0536 0.1861] [0.0848 0.084 ] [0.184 0.0546]]
anchor 怎么用:偏移回归的编解码(v2/v3 的实现核心)¶
聚类只回答了「先验形状从哪来」,真正让网络学的是偏移回归:
- 中心:$\hat{c}_x = \sigma(t_x) + \text{grid}_x$ —— 输出过 sigmoid 被压进格子内(不会飘到别的格子)
- 宽高:$t_w = \log(w / a_w)$,解码 $\hat{w} = a_w e^{t_w}$
为什么宽高用 log/exp:① $e^{t}$ 恒为正 → 网络无论输出什么符号都不会出现负宽高; ② log 把「宽高比」变成「线性距离」——目标从「预测绝对像素」降维成「预测一个很小的乘性修正」, 回归任务变简单(这是 anchor 方法比 v1 直接回归绝对框好收敛的根本原因)。
# ================= anchor 编解码(手写 + 手算 + round-trip) =================
def anchor_encode(box_wh, anchor_wh):
# box_wh/(anchor_wh): gt 相对锚框宽高 -> log 空间偏移(锚框是"起点")
return np.log(np.clip(box_wh / anchor_wh, 1e-6, None))
def anchor_decode(t, anchor_wh):
# 解码:锚框宽高 × e^t(训练目标就是让 t 逼近 encode 结果)
return anchor_wh * np.exp(t)
# 手算:anchor w=80,GT w=60 → t_w = ln(60/80) = ln(0.75) ≈ -0.2877;h: 50/80 → -0.4700
a = np.array([80.0, 80.0]); box = np.array([60.0, 50.0])
t = anchor_encode(box, a)
print('t =', np.round(t, 4), '(手算 ln(0.75)=%.4f, ln(0.625)=%.4f)' % (np.log(0.75), np.log(0.625)))
assert abs(t[0] - np.log(0.75)) < 1e-9 and abs(t[1] - np.log(0.625)) < 1e-9
assert np.allclose(anchor_decode(t, a), box) # round-trip:encode 后 decode 回原框
print('round-trip: 60/50 ->', np.round(anchor_decode(t, a), 4), '✓')
# 中心编码:归一化坐标 -> 格内偏移(v3 起输出过 sigmoid,训练目标同样归一化)
def center_encode(cx, cy, grid_x, grid_y, S=13):
# cx/cy 为归一化坐标 [0,1];grid 是中心所在格子索引
return cx * S - grid_x, cy * S - grid_y
off = center_encode(0.41, 0.27, 5, 3, S=13)
print('中心编码:归一化 (0.41,0.27) 落格子 (5,3) → 格内偏移', np.round(off, 3))
assert np.allclose(off, (0.33, 0.51), atol=0.01)
print('要点:网络从不直接输出像素坐标,只输出「格内偏移 + log 宽高比」——回归的都是小量')
t = [-0.2877 -0.47 ] (手算 ln(0.75)=-0.2877, ln(0.625)=-0.4700) round-trip: 60/50 -> [60. 50.] ✓ 中心编码:归一化 (0.41,0.27) 落格子 (5,3) → 格内偏移 [0.33 0.51] 要点:网络从不直接输出像素坐标,只输出「格内偏移 + log 宽高比」——回归的都是小量
# ================= YOLOv2:Darknet19 核心块 + anchor 编解码(torch 版) =================
import torch
import torch.nn as nn
import torch.nn.functional as F
class ConvBN(nn.Module):
# Darknet19 标配块:Conv + BN + LeakyReLU(BN 在卷积后、激活前——v2 引入 BN 的关键收益)
def __init__(self, cin, cout, k=3, s=1):
super().__init__()
self.c = nn.Conv2d(cin, cout, k, s, padding=k // 2, bias=False)
self.bn = nn.BatchNorm2d(cout)
def forward(self, x):
return F.leaky_relu(self.bn(self.c(x)), 0.1)
class Darknet19Block(nn.Module):
# 一个 stage:1x1 降维 + 3x3 升维(v2 的高效组合,参数量小、感受野够)
def __init__(self, cin, mid, cout):
super().__init__()
self.body = nn.Sequential(ConvBN(cin, mid, 1), ConvBN(mid, cout, 3))
def forward(self, x):
return self.body(x)
# ---- anchor 编解码 torch 版(与上面 numpy 手算对照) ----
def anchor_encode_t(box_wh, anchor_wh):
return torch.log(torch.clamp(box_wh / anchor_wh, min=1e-6))
def anchor_decode_t(t, anchor_wh):
return anchor_wh * torch.exp(t)
torch.manual_seed(0)
a = torch.tensor([80.0, 80.0]); box = torch.tensor([60.0, 50.0])
t = anchor_encode_t(box, a)
print('t =', t.numpy().round(4), '(对照 numpy 手算 ln(0.75)=-0.2877, ln(0.625)=-0.4700)')
assert torch.allclose(anchor_decode_t(t, a), box)
print('round-trip: 60/50 ->', anchor_decode_t(t, a).numpy().round(4), '✓')
# Darknet19 块形状推演:1x1 降维 -> 3x3 升维
x = torch.randn(2, 64, 16, 16)
blk = Darknet19Block(64, 32, 128)
y = blk(x)
print('Darknet19Block: (2,64,16,16) ->', tuple(y.shape))
assert tuple(y.shape) == (2, 128, 16, 16)
print('要点:BN 让每层输出分布稳定 → 学习率可以更大、收敛更快(v2 的 BN 收益在 torch 里就是这个组合)')
# ============ YOLOv2 完整网络:Darknet19 mini + passthrough + anchor 头(torch) ============
import torch
import torch.nn as nn
import torch.nn.functional as F
class YOLOv2Net(nn.Module):
# mini Darknet19:3 次下采样到 stride 8;passthrough 把浅层 16x16 特征拼进深层 8x8
#(v2 的『细粒度特征』手术,v3 多尺度 FPN 的雏形)
def __init__(self, n_anchors=5, n_cls=20):
super().__init__()
self.stage1 = nn.Sequential(ConvBN(3, 32, 3, 1), ConvBN(32, 64, 3, 2)) # 64->32
self.stage2 = nn.Sequential(ConvBN(64, 128, 3, 2), ConvBN(128, 64, 1), ConvBN(64, 128, 3, 1)) # 32->16
self.stage3 = nn.Sequential(ConvBN(128, 256, 3, 2)) # 16->8
# passthrough:浅层 16x16 降维后 pixel_unshuffle 成 8x8、通道 x4,与深层拼接
self.pass_conv = ConvBN(128, 128, 1)
self.head = nn.Conv2d(256 + 128 * 4, n_anchors * (5 + n_cls), 1)
self.n_anchors, self.n_cls = n_anchors, n_cls
def forward(self, x):
s1 = self.stage1(x) # (N,64,32,32)
s2 = self.stage2(s1) # (N,128,16,16)
deep = self.stage3(s2) # (N,256,8,8)
sh = F.pixel_unshuffle(self.pass_conv(s2), 2) # (N,512,8,8) 细粒度特征
f = torch.cat([deep, sh], dim=1) # (N,768,8,8)
out = self.head(f) # (N,A*(5+C),8,8)
return out.permute(0, 2, 3, 1) # (N,8,8,A*(5+C))
torch.manual_seed(0)
net = YOLOv2Net(n_anchors=5, n_cls=20)
x = torch.randn(2, 3, 64, 64)
out = net(x)
print('YOLOv2Net: (2,3,64,64) ->', tuple(out.shape), '(stride8 网格,每格 5*(5+20)=125 维)')
assert tuple(out.shape) == (2, 8, 8, 125)
# 验证 passthrough 确实把浅层接进来了:特征通道数 = 256 + 512
print('要点:passthrough 通道 = 深层256 + 浅层重排512 —— 小物体细节直达预测头 ✓')
print('anchor 头输出的是『相对 anchor 的小偏移』:回归从绝对坐标降维成小修正(anchor 起源)')
# ===== YOLOv2 模型架构图(Darknet19 + passthrough + anchor 头) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.0))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.4); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=10)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.8))
box(0.2, 1.6, 1.4, 0.7, '输入图像\n416×416×3', fc='lightyellow')
box(2.0, 1.6, 2.0, 0.7, 'Darknet19 骨干\n(19 层卷积+BN)', fc='lightblue')
box(4.4, 1.6, 1.7, 0.7, '深层特征\n13×13×1024', fc='lightgreen')
# passthrough 分支:浅层 26×26 重排成 13×13
box(4.4, 2.6, 1.7, 0.6, '浅层特征\n26×26×512', fc='khaki')
box(6.5, 2.6, 1.7, 0.6, '重排拼接\n13×13×2048', fc='khaki')
ax.text(5.25, 3.1, 'passthrough:隔像素重组\n细节特征直达深层', ha='center', fontsize=9, color='#8B6914')
arrow(2.4, 2.6, 4.4, 2.6); arrow(6.1, 2.6, 6.5, 2.6)
arrow(6.2, 2.5, 6.2, 2.0) # 拼接结果送入检测头
box(6.5, 1.2, 1.8, 0.7, 'anchor 头\n13×13×125', fc='lightgreen')
box(8.7, 1.2, 1.1, 0.7, '解码\nK=5 锚框', fc='lightsalmon')
arrow(6.2, 1.9, 6.5, 1.55); arrow(8.3, 1.55, 8.7, 1.55)
ax.text(7.45, 0.75, '125 = 5 anchor × (4 + 1 + 20 类)', ha='center', fontsize=9, color='#2E5F9E')
ax.set_title('YOLOv2 架构:K-Means 聚类 anchor + passthrough 拼浅层', fontsize=13)
plt.tight_layout(); plt.show()
v2 的其余手术(每个都是一句话考点)¶
| 手术 | 解决什么 | 一句话原理 |
|---|---|---|
| BatchNorm | 训练不稳、收敛慢 | 每层输出按 batch 统计归一化 → 分布稳定、可大步长(下文手写对照) |
| 高分辨率微调 | 小物体 | 预训练 448 → 检测阶段 480(分辨率越高小物体越清楚) |
| 多尺度训练 | 尺度鲁棒 | 每 10 batch 随机换输入尺寸 320~608,模型自适应各种分辨率 |
| Darknet-19 | 速度 | 19 层卷积(借鉴 VGG 堆叠 + 全卷积),比 VGG 快一个量级 |
| passthrough 层 | 细粒度特征 | 把 26×26 浅层特征拼进 13×13 深层 → 小物体细节(v3 的 FPN 雏形) |
import torch
import torch.nn as nn
# ================= 手写 BatchNorm 前向(训练模式) + torch 数值对照 =================
# BN 做的事:对每个通道,用 batch 均值/方差归一化,再乘可学习 γ、加 β:
# x̂ = (x − μ_c) / √(σ_c² + ε), y = γ·x̂ + β
# 为什么能加速收敛:激活分布不再随前层权重变化而漂移(内部协变量漂移),
# 每层输入分布稳定 → 学习率可以更大、初始化可以不那么讲究。
def batchnorm_forward(x, gamma, beta, eps=1e-5):
# x: (N,C,H,W);γ/β: (C,)。训练模式:统计来自当前 batch。
mean = x.mean(axis=(0, 2, 3), keepdims=True) # 每个通道一个均值 (1,C,1,1)
var = x.var(axis=(0, 2, 3), keepdims=True) # 每个通道一个方差(无偏与否只差 n/(n-1))
xhat = (x - mean) / np.sqrt(var + eps) # 归一化:分布 → 均值0方差1
return gamma.reshape(1, -1, 1, 1) * xhat + beta.reshape(1, -1, 1, 1)
torch.manual_seed(0)
xt = torch.randn(2, 3, 8, 8)
bn = nn.BatchNorm2d(3).train() # 训练模式:用 batch 统计(γ=1、β=0 默认)
with torch.no_grad():
out_t = bn(xt)
out_np = batchnorm_forward(xt.numpy(), np.ones(3), np.zeros(3))
err = np.abs(out_np - out_t.numpy()).max()
print('手写 BN 前向 vs torch 最大误差: %.2e' % err)
assert err < 1e-5
# 演示「内部协变量漂移」:两批分布差异很大的数据,BN 后都被拉回同一分布
x_a = np.random.default_rng(1).normal(0.2, 1.5, (4, 3, 8, 8)) # 批 A:均值 0.2 方差 1.5
x_b = np.random.default_rng(2).normal(3.0, 0.3, (4, 3, 8, 8)) # 批 B:均值 3.0 方差 0.3
print('无 BN:批 A 均值 %.2f 方差 %.2f | 批 B 均值 %.2f 方差 %.2f(分布漂移大)' % (
x_a.mean(), x_a.var(), x_b.mean(), x_b.var()))
o_a = batchnorm_forward(x_a, np.ones(3), np.zeros(3))
o_b = batchnorm_forward(x_b, np.ones(3), np.zeros(3))
print('有 BN:批 A 输出均值 %.4f 方差 %.4f | 批 B 输出均值 %.4f 方差 %.4f(都被拉回同分布)' % (
o_a.mean(), o_a.var(), o_b.mean(), o_b.var()))
assert abs(o_a.mean()) < 1e-2 and abs(o_b.mean()) < 1e-2
手写 BN 前向 vs torch 最大误差: 4.77e-07 无 BN:批 A 均值 0.11 方差 2.14 | 批 B 均值 2.99 方差 0.09(分布漂移大) 有 BN:批 A 输出均值 0.0000 方差 1.0000 | 批 B 输出均值 0.0000 方差 0.9999(都被拉回同分布)
第 3 幕 · YOLOv3(2018):多尺度 FPN —— 大小物体各就各位¶
痛点:v2 的 passthrough 只拼了一个浅层,小物体依然漏检;物体尺度差异大,单尺度特征顾此失彼。
方案:特征金字塔(FPN)——从 backbone 抽出三个尺度(stride 8/16/32 → 52/26/13 网格), 大特征图管小物体(分辨率高、细节多),小特征图管大物体(语义强)。
- Darknet-53:53 层卷积(残差思想),比 ResNet-152 快 2 倍
- 9 个 anchor 按尺度分:小 anchor → stride 8 的特征图,中 → 16,大 → 32
- 中心约束:$c_x = \sigma(t_x)+\text{grid}_x$ —— sigmoid 把偏移压进格子内(不会飘到别的格子)
- 多标签:类别用 sigmoid + 二元 CE(一个物体可以同时是 person 和 woman),不再 softmax 互斥
- 对象性:每个 anchor 预测「有没有物体」单独用 BCE(v1 用回归,v3 换成二分类更稳)
# ================= YOLOv3 三尺度 + anchor 分配模拟 =================
# 输入 416:stride 8/16/32 → 特征图 52/26/13。anchor 按「负责尺度」分组:
anchors_3s = {8: [(10, 13), (16, 30), (33, 23)],
16: [(30, 61), (62, 45), (59, 119)],
32: [(116, 90), (156, 198), (373, 326)]}
print('YOLOv3 三尺度特征图与 anchor 分组(416 输入,COCO 80 类):')
for st, as_ in sorted(anchors_3s.items()):
fm = 416 // st
print(' stride=%2d → %3d×%3d 网格,anchor=%s,输出通道 %d' %
(st, fm, fm, as_, 3 * (5 + 80)))
# ---- GT 按面积分配到尺度(小物体→大特征图):模拟一批 GT ----
rng = np.random.default_rng(0)
n = 40
areas = np.exp(rng.uniform(np.log(8 ** 2), np.log(200 ** 2), n)) # 面积 8²~200² 像素
def assign_scale(area, img=416):
# 经验阈值:面积 < (32²) 给 stride8;< (96²) 给 stride16;否则 stride32
if area < 32 ** 2: return 8
if area < 96 ** 2: return 16
return 32
counts = {s: 0 for s in (8, 16, 32)}
for a in areas:
counts[assign_scale(a)] += 1
print('40 个随机 GT 的尺度分配: stride8(小物体)=%d, stride16=%d, stride32(大物体)=%d' %
(counts[8], counts[16], counts[32]))
assert counts[8] + counts[16] + counts[32] == n and counts[8] > 0 and counts[32] > 0
# ---- 3×3 卷积堆叠与 stride 的关系:为什么 stride8 需要 2 次 stride2 卷积 ----
print('stride 是 backbone 逐层 stride 的乘积:2×2×2=8,4 次 2=16,5 次 2=32')
YOLOv3 三尺度特征图与 anchor 分组(416 输入,COCO 80 类): stride= 8 → 52× 52 网格,anchor=[(10, 13), (16, 30), (33, 23)],输出通道 255 stride=16 → 26× 26 网格,anchor=[(30, 61), (62, 45), (59, 119)],输出通道 255 stride=32 → 13× 13 网格,anchor=[(116, 90), (156, 198), (373, 326)],输出通道 255 40 个随机 GT 的尺度分配: stride8(小物体)=15, stride16=15, stride32(大物体)=10 stride 是 backbone 逐层 stride 的乘积:2×2×2=8,4 次 2=16,5 次 2=32
FPN 自顶向下融合:深层语义注入浅层(v3 多尺度的实现)¶
三个独立特征图还不够——浅层(52×52)细节多但语义弱,深层(13×13)语义强但分辨率低。 FPN 的做法:自顶向下逐级上采样相加: $$P_4 = \text{conv}_{1\times1}(C_4) + \text{up}(P_5),\qquad P_3 = \text{conv}_{1\times1}(C_3) + \text{up}(P_4)$$
每个输出头因此同时拿到「同级细节 + 深层语义」。v4 再加自底向上(PANet)把细节送回深层, 形成双向信息流。
# ================= FPN 自顶向下 + PANet 自底向上(torch 形状推演) =================
import torch
import torch.nn as nn
torch.manual_seed(0)
# backbone 三支(YOLO 命名 C3/C4/C5 = stride 8/16/32:空间 52/26/13,通道 256/512/1024)
C3 = torch.randn(2, 256, 52, 52) # 最浅:细节最多(管小物体)
C4 = torch.randn(2, 512, 26, 26) # 中层
C5 = torch.randn(2, 1024, 13, 13) # 最深:语义最强(管大物体)
# ---- 自顶向下:深层上采样 x2,逐级 add 给浅层 ----
up = nn.Upsample(scale_factor=2, mode='nearest')
p5 = nn.Conv2d(1024, 128, 1)(C5) # 最深层先投影(FPN 起点)
p4 = nn.Conv2d(512, 128, 1)(C4) + up(p5) # 26 = 13×2:26x26 细节 + 13x13 语义
p3 = nn.Conv2d(256, 128, 1)(C3) + up(p4) # 52 = 26×2:52x52 再收一层语义
print('FPN 输出(各接一个检测头):', tuple(p3.shape), tuple(p4.shape), tuple(p5.shape))
assert tuple(p3.shape) == (2, 128, 52, 52) and tuple(p4.shape) == (2, 128, 26, 26) and tuple(p5.shape) == (2, 128, 13, 13)
# ---- 自底向上(v4 的 PANet):细节再送回深层 ----
down = nn.Conv2d(128, 128, 3, stride=2, padding=1) # 分辨率减半的卷积(52->26->13)
n3 = p3
n4 = p4 + down(n3) # 52 -> 26(细节注入中层)
n5 = p5 + down(n4) # 26 -> 13(细节注入深层)
print('PANet 自底向上后:', tuple(n3.shape), tuple(n4.shape), tuple(n5.shape))
assert tuple(n4.shape) == (2, 128, 26, 26) and tuple(n5.shape) == (2, 128, 13, 13)
print('要点:FPN 给浅层补语义、PANet 给深层补细节 —— 双向信息流是 v3/v4 多尺度效果好的实现根基')
FPN 输出(各接一个检测头): (2, 128, 52, 52) (2, 128, 26, 26) (2, 128, 13, 13) PANet 自底向上后: (2, 128, 52, 52) (2, 128, 26, 26) (2, 128, 13, 13) 要点:FPN 给浅层补语义、PANet 给深层补细节 —— 双向信息流是 v3/v4 多尺度效果好的实现根基
# ================= YOLOv3:三尺度检测头 + anchor 解码(torch 版) =================
import torch
import torch.nn as nn
class YOLOv3Head(nn.Module):
# 每个尺度一个检测头:1x1 卷积输出 n_anchor*(5+n_cls) 通道(v3: 3*(5+80)=255)
def __init__(self, in_ch, n_anchors=3, n_cls=80):
super().__init__()
self.n_anchors = n_anchors
self.n_cls = n_cls
self.conv = nn.Conv2d(in_ch, n_anchors * (5 + n_cls), 1)
def forward(self, x):
b, _, h, w = x.shape
out = self.conv(x).view(b, self.n_anchors, 5 + self.n_cls, h, w)
return out.permute(0, 1, 3, 4, 2) # (B,A,H,W,5+C)
def v3_decode(pred, anchors, stride):
# pred: (B,A,H,W,5+C);anchors: (A,2) 归一化宽高;stride: 下采样倍数
b, a, h, w, _ = pred.shape
gy, gx = torch.meshgrid(torch.arange(h), torch.arange(w), indexing='ij')
grid = torch.stack([gx, gy], dim=-1).float() # (H,W,2) 格内原点
# 中心 = (sigmoid(xy) + 网格) * stride;宽高 = anchor * exp(wh)
xy = (torch.sigmoid(pred[..., :2]) + grid.unsqueeze(0).unsqueeze(0)) * stride
wh = anchors.unsqueeze(0).unsqueeze(2).unsqueeze(3) * torch.exp(pred[..., 2:4])
x1y1 = xy - wh / 2
x2y2 = xy + wh / 2
return torch.cat([x1y1, x2y2, pred[..., 4:]], dim=-1) # 绝对坐标 + 对象性 + 类别
torch.manual_seed(0)
feat = torch.randn(2, 512, 52, 52) # stride=8 的浅层特征(管小物体)
head = YOLOv3Head(512)
raw = head(feat)
print('YOLOv3Head 输出:', tuple(raw.shape), '(B,A,H,W,5+C)')
assert tuple(raw.shape) == (2, 3, 52, 52, 85)
anchors = torch.tensor([[10., 13.], [16., 30.], [33., 23.]]) # stride8 组
boxes = v3_decode(raw, anchors, stride=8)
print('decode 后:', tuple(boxes.shape), '(前 4 维是图像绝对坐标 x1,y1,x2,y2)')
assert tuple(boxes.shape) == (2, 3, 52, 52, 85)
print('验证某格 anchor 0 的框中心在 (stride*gx + sigmoid, ...) 附近,abs 值合理:')
print(' 示例框:', boxes[0, 0, 25, 25, :4].detach().numpy().round(1))
print('要点:v3 三个尺度各配一组 anchor;decode = sigmoid(xy)+网格 与 exp(wh)*anchor,缺一个框就错位')
# ============ YOLOv3 完整网络:多尺度骨干 + FPN + 3 个检测头(torch) ============
import torch
import torch.nn as nn
import torch.nn.functional as F
class YOLOv3Net(nn.Module):
# mini 骨干:3 个 stage 输出 stride 8/16/32 的特征;FPN 自顶向下融合;每尺度一个 YOLOv3Head
def __init__(self, n_anchors=3, n_cls=80):
super().__init__()
self.s1 = nn.Sequential(ConvBN(3, 32, 3, 1), ConvBN(32, 64, 3, 2)) # 64->32 (stride2)
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), ConvBN(128, 128, 1), ConvBN(128, 128, 3, 1)) # stride4
self.s3 = nn.Sequential(ConvBN(128, 256, 3, 2), ConvBN(256, 256, 1), ConvBN(256, 256, 3, 1)) # stride8
# FPN 投影层(把三路通道统一到 128,便于相加)
self.proj3 = nn.Conv2d(64, 128, 1)
self.proj4 = nn.Conv2d(128, 128, 1)
self.proj5 = nn.Conv2d(256, 128, 1)
# 三个尺度的检测头
self.h3 = YOLOv3Head(128, n_anchors, n_cls)
self.h4 = YOLOv3Head(128, n_anchors, n_cls)
self.h5 = YOLOv3Head(128, n_anchors, n_cls)
def forward(self, x):
c3 = self.s1(x) # (N,64,32,32) stride2
c4 = self.s2(c3) # (N,128,16,16) stride4
c5 = self.s3(c4) # (N,256,8,8) stride8
# FPN 自顶向下:深层上采样 x2 与浅层相加
p5 = self.proj5(c5) # (N,128,8,8)
p4 = self.proj4(c4) + F.interpolate(p5, scale_factor=2, mode='nearest') # (N,128,16,16)
p3 = self.proj3(c3) + F.interpolate(p4, scale_factor=2, mode='nearest') # (N,128,32,32)
return self.h3(p3), self.h4(p4), self.h5(p5) # 三个 (N,A,H,W,5+C)
torch.manual_seed(0)
net = YOLOv3Net(n_anchors=3, n_cls=80)
x = torch.randn(2, 3, 64, 64)
o3, o4, o5 = net(x)
print('YOLOv3Net 三尺度输出:', tuple(o3.shape), tuple(o4.shape), tuple(o5.shape))
assert tuple(o3.shape) == (2, 3, 32, 32, 85) and tuple(o4.shape) == (2, 3, 16, 16, 85) and tuple(o5.shape) == (2, 3, 8, 8, 85)
print('要点:大特征图(32x32)管小物体、小特征图(8x8)管大物体——多尺度是 v3 精度跳升的核心')
# ===== YOLOv3 模型架构图(3 尺度骨干 + FPN + 3 检测头) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.6))
ax.set_xlim(0, 10); ax.set_ylim(0, 4.0); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.6))
# 输入 + 骨干金字塔
box(0.2, 2.0, 1.4, 0.8, '输入图像\n416×416×3', fc='lightyellow')
box(2.0, 2.0, 1.8, 0.8, 'Darknet-53\n骨干', fc='lightblue')
box(4.2, 2.9, 1.6, 0.7, 'C3: 52×52', fc='lightgreen')
box(4.2, 2.0, 1.6, 0.7, 'C4: 26×26', fc='lightgreen')
box(4.2, 1.1, 1.6, 0.7, 'C5: 13×13', fc='lightgreen')
arrow(2.0, 2.4, 4.2, 2.4)
# FPN 融合层
box(6.2, 2.9, 1.6, 0.7, 'P3: 52×52\n(小物体)', fc='lavender')
box(6.2, 2.0, 1.6, 0.7, 'P4: 26×26', fc='lavender')
box(6.2, 1.1, 1.6, 0.7, 'P5: 13×13\n(大物体)', fc='lavender')
# FPN 自顶向下箭头
arrow(7.0, 1.8, 7.0, 2.2); arrow(7.0, 2.7, 7.0, 3.1)
ax.text(7.3, 3.35, '上采样相加\n(FPN)', fontsize=9, color='#6A5ACD')
# 三个检测头
box(8.2, 2.9, 1.5, 0.7, '头3: 255 通道', fc='lightsalmon')
box(8.2, 2.0, 1.5, 0.7, '头4: 255 通道', fc='lightsalmon')
box(8.2, 1.1, 1.5, 0.7, '头5: 255 通道', fc='lightsalmon')
arrow(7.8, 3.25, 8.2, 3.25); arrow(7.8, 2.35, 8.2, 2.35); arrow(7.8, 1.45, 8.2, 1.45)
ax.text(8.95, 3.7, '每尺度 3 anchor\n255 = 3×(5+80)', ha='center', fontsize=9, color='#A0522D')
ax.set_title('YOLOv3 架构:FPN 多尺度融合,大小物体各就各位', fontsize=13)
plt.tight_layout(); plt.show()
# ================= YOLOv3 的损失核心:对象性 BCE + 类别 BCE(手写 + 手算) =================
# v3 每尺度每 anchor 独立预测:对象性(1 维,sigmoid+BCE)+ 类别(C 维,sigmoid+多标签 BCE)。
# 分配规则:每个 GT 中心所在格子,取与之 IoU 最大的 anchor 为正样本(负责它)。
def bce_loss(pred_prob, target):
# 二元交叉熵:−[t·log p + (1−t)·log(1−p)]。p 是 sigmoid 后的概率。
eps = 1e-7
return -(target * np.log(pred_prob + eps) + (1 - target) * np.log(1 - pred_prob + eps))
# 手算小例子:一个 GT 落在 13x13 网格 (5,7),与 3 个候选 anchor 的 IoU = (0.1, 0.7, 0.2)
# → 选 anchor 2(IoU 最大)为正样本:对象性目标=1,类别目标=one-hot(人)
ious = np.array([0.1, 0.7, 0.2])
best = int(np.argmax(ious)) # 正样本 anchor = IoU 最大的那个
pred_conf = np.array([0.3, 0.6, 0.1]) # 三个 anchor 预测的对象性 logit(假设已 sigmoid)
pred_cls = np.array([0.4, 0.6, 0.2]) # 预测的「人」概率(多标签之一)
# 对象性损失:只有正样本 anchor 参与(目标 1),其余为背景(目标 0)
l_obj = bce_loss(pred_conf[best], 1.0) + sum(bce_loss(pred_conf[j], 0.0) for j in range(3) if j != best)
l_cls = bce_loss(pred_cls[best], 1.0) # 类别损失只看正样本
print('正样本 anchor = %d(IoU=%.1f 最大)' % (best, ious[best]))
print('对象性 BCE = %.4f | 类别 BCE = %.4f' % (l_obj, l_cls))
# 手算核对:l_obj = −log(0.6) − log(0.7) − log(0.9) ≈ 0.511+0.357+0.105 = 0.973
manual_obj = -np.log(0.6) - np.log(1 - 0.3) - np.log(1 - 0.1)
manual_cls = -np.log(0.6)
assert abs(l_obj - manual_obj) < 1e-6 and abs(l_cls - manual_cls) < 1e-6
print('手算一致 ✓(背景 anchor 也要学「没东西」——与 v1 的 λ_noobj 同源的思想)')
正样本 anchor = 1(IoU=0.7 最大) 对象性 BCE = 0.9729 | 类别 BCE = 0.5108 手算一致 ✓(背景 anchor 也要学「没东西」——与 v1 的 λ_noobj 同源的思想)
第 4 幕 · YOLOv4(2020):把「训练配方」做到极致¶
痛点:v3 结构已定,但训练技巧没有拉满——同样结构,配方不同效果差 5 个点。
方案(v4 是配方集大成者):
| 配方 | 作用 |
|---|---|
| CSPDarknet-53 | CSP:通道切两半、一半直连一半卷积 → 减计算 + 梯度流动更好 |
| Mish 激活 | 平滑激活(比 ReLU 梯度更稳),分类任务普遍 +1~2 点 |
| PANet 融合 | FPN 自顶向下后,再自底向上补一条 → 小物体信息也传到高层 |
| Mosaic 增强 | 4 张图拼 1 张 → 小目标样本翻倍 + BN 统计更稳(下文手写) |
| CIoU 损失 | IoU + 中心距 + 宽高比三重惩罚(下文手写) |
| 自对抗训练 | 先让网络「骗自己」制造难样本,再正常训练 |
面试常问:v4 最大贡献是网络还是配方? 答:配方。网络是 v3 的改造,配方才是收益大头。
# ================= Mosaic 增强手写:4 张图拼 1 张(v4/v5 的训练神器) =================
rng = np.random.default_rng(0)
def synth_img(cat, size=64):
# 合成三类图:0=左下亮三角 1=右上半圆 2=中心方块(模拟不同类别)
yy, xx = np.mgrid[0:size, 0:size]
if cat == 0:
mask = xx < yy # 左下三角
elif cat == 1:
mask = (xx - size // 2) ** 2 + (yy - size // 2) ** 2 < (size // 3) ** 2 # 圆
else:
mask = (abs(xx - size // 2) < size // 5) & (abs(yy - size // 2) < size // 5) # 方块
img = np.zeros((size, size, 3))
img[mask] = np.array([0.2, 0.6, 0.9]) if cat == 0 else (np.array([0.9, 0.5, 0.2]) if cat == 1 else np.array([0.3, 0.8, 0.3]))
return img, mask
size = 64
canvas = np.zeros((size, size, 3))
label_boxes = [] # 拼接后每个物体的框(yolo 风格)
for k, cat in enumerate([0, 1, 2, 0]): # 4 张不同/重复类别图
img, mask = synth_img(cat)
# 随机从原图裁一块(Mosaic 的思想:裁剪后拼接 → 局部信息更密集)
y0 = rng.integers(0, size // 2); x0 = rng.integers(0, size // 2)
crop = img[y0:y0 + size // 2, x0:x0 + size // 2]
py = (k // 2) * (size // 2); px = (k % 2) * (size // 2) # 4 个象限的放置位置
canvas[py:py + size // 2, px:px + size // 2] = crop
m = mask[y0:y0 + size // 2, x0:x0 + size // 2]
ys, xs = np.where(m)
if len(ys):
label_boxes.append((py + ys.min(), px + xs.min(), py + ys.max(), px + xs.max(), cat))
print('拼接后画布形状:', canvas.shape, '| 检测到物体框数:', len(label_boxes))
assert canvas.shape == (size, size, 3) and len(label_boxes) == 4
print('标签框(y1,x1,y2,x2,cat):')
for b in label_boxes:
print(' ', b)
# ========== 图:4 张原图 + 拼接结果 ==========
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, axes = plt.subplots(1, 3, figsize=(11.5, 3.8))
srcs = [synth_img(c)[0] for c in (0, 1, 2)]
for ax, im, t in zip(axes[:3], srcs, ['类别0(三角)', '类别1(圆)', '类别2(方块)']):
ax.imshow(im); ax.set_title(t); ax.axis('off')
plt.tight_layout(); plt.show()
fig2, ax2 = plt.subplots(figsize=(4.6, 4.6))
ax2.imshow(canvas); ax2.set_title('Mosaic 拼接结果(4 图 1 张)', fontsize=12); ax2.axis('off')
plt.tight_layout(); plt.show()
print('Mosaic 效果:小目标密度提升(原本 1/4 图的大小变成 1/16 的小目标)→ 小物体训练样本激增')
拼接后画布形状: (64, 64, 3) | 检测到物体框数: 4 标签框(y1,x1,y2,x2,cat): (np.int64(0), np.int64(0), np.int64(31), np.int64(31), 0) (np.int64(0), np.int64(36), np.int64(31), np.int64(63), 1) (np.int64(44), np.int64(20), np.int64(63), np.int64(31), 2) (np.int64(32), np.int64(32), np.int64(63), np.int64(63), 0)
Mosaic 效果:小目标密度提升(原本 1/4 图的大小变成 1/16 的小目标)→ 小物体训练样本激增
# ================= CIoU 手写(v4/v5 回归损失,三代惩罚逐行注释) =================
def iou(b1, b2):
ix1 = max(b1[0], b2[0]); iy1 = max(b1[1], b2[1])
ix2 = min(b1[2], b2[2]); iy2 = min(b1[3], b2[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
a1 = (b1[2]-b1[0])*(b1[3]-b1[1]); a2 = (b2[2]-b2[0])*(b2[3]-b2[1])
return inter / max(a1 + a2 - inter, 1e-9)
def giou(b1, b2):
iou_v = iou(b1, b2)
c_x1 = min(b1[0], b2[0]); c_y1 = min(b1[1], b2[1]); c_x2 = max(b1[2], b2[2]); c_y2 = max(b1[3], b2[3])
area_c = (c_x2 - c_x1) * (c_y2 - c_y1)
ix1 = max(b1[0], b2[0]); iy1 = max(b1[1], b2[1]); ix2 = min(b1[2], b2[2]); iy2 = min(b1[3], b2[3])
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
area_u = (b1[2]-b1[0])*(b1[3]-b1[1]) + (b2[2]-b2[0])*(b2[3]-b2[1]) - inter
return iou_v - (area_c - area_u) / max(area_c, 1e-9) # 惩罚「C 里没被框盖住的空隙」
def diou(b1, b2):
iou_v = iou(b1, b2)
c_x1 = min(b1[0], b2[0]); c_y1 = min(b1[1], b2[1]); c_x2 = max(b1[2], b2[2]); c_y2 = max(b1[3], b2[3])
c = (c_x2 - c_x1) ** 2 + (c_y2 - c_y1) ** 2
b1c = ((b1[0]+b1[2])/2, (b1[1]+b1[3])/2); b2c = ((b2[0]+b2[2])/2, (b2[1]+b2[3])/2)
rho2 = (b1c[0]-b2c[0]) ** 2 + (b1c[1]-b2c[1]) ** 2
return iou_v - rho2 / max(c, 1e-9)
def ciou(b1, b2):
iou_v = iou(b1, b2)
c_x1 = min(b1[0], b2[0]); c_y1 = min(b1[1], b2[1]); c_x2 = max(b1[2], b2[2]); c_y2 = max(b1[3], b2[3])
c = (c_x2 - c_x1) ** 2 + (c_y2 - c_y1) ** 2
b1c = ((b1[0]+b1[2])/2, (b1[1]+b1[3])/2); b2c = ((b2[0]+b2[2])/2, (b2[1]+b2[3])/2)
rho2 = (b1c[0]-b2c[0]) ** 2 + (b1c[1]-b2c[1]) ** 2
# 宽高比一致性:v 衡量 (w1/h1) 与 (w2/h2) 的差异;α 让惩罚随 IoU 自动缩放(重叠越大越在意比例)
w1 = b1[2]-b1[0]; h1 = b1[3]-b1[1]; w2 = b2[2]-b2[0]; h2 = b2[3]-b2[1]
v = (4 / np.pi ** 2) * (np.arctan(w1 / h1) - np.arctan(w2 / h2)) ** 2
alpha = v / max((1 - iou_v) + v, 1e-9)
return iou_v - rho2 / max(c, 1e-9) - alpha * v
# 数值验证:两个同尺寸正方形左右错开 4 像素 → CIoU < IoU(中心距被惩罚;宽高比相同所以 v=0)
b1 = (10, 10, 30, 30); b2 = (14, 10, 34, 30)
print('IoU = %.4f(手算 320/480=0.6667),CIoU = %.4f' % (iou(b1, b2), ciou(b1, b2)))
assert abs(iou(b1, b2) - 320 / 480) < 1e-9 and ciou(b1, b2) < iou(b1, b2)
# ========== 图:IoU 系损失随「错开量」变化(分离时谁还有梯度) ==========
def loss_curves():
sim, offs = 20, np.linspace(0, 19, 200)
fig, ax = plt.subplots(figsize=(7.4, 4.6))
for name, fn in [('IoU', iou), ('GIoU', giou), ('DIoU', diou), ('CIoU', ciou)]:
ls = [1.0 - fn((0, 0, sim, sim), (d, 0, sim + d, sim)) for d in offs]
ax.plot(offs, ls, lw=1.7, label=name + ' 损失')
ax.set_xlabel('两框错开距离(0=完全重合 → 大=完全分离)'); ax.set_ylabel('损失值')
ax.set_title('分离后 IoU 损失饱和在 1,GIoU/DIoU/CIoU 仍有梯度可学', fontsize=12)
ax.legend(fontsize=9); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
loss_curves()
IoU = 0.6667(手算 320/480=0.6667),CIoU = 0.6503
# ================= YOLOv4:CIoU 损失(torch 向量化版)+ CSP 块 nn.Module =================
import torch
import torch.nn as nn
def ciou_loss_torch(pred, target, eps=1e-7):
# pred/target: (N,4) = (x1,y1,x2,y2),批量向量化(与上面逐框手写 ciou 同语义)
p1x, p1y, p2x, p2y = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]
t1x, t1y, t2x, t2y = target[:, 0], target[:, 1], target[:, 2], target[:, 3]
# IoU
ix1 = torch.max(p1x, t1x); iy1 = torch.max(p1y, t1y)
ix2 = torch.min(p2x, t2x); iy2 = torch.min(p2y, t2y)
iw = (ix2 - ix1).clamp(min=0); ih = (iy2 - iy1).clamp(min=0)
inter = iw * ih
pa = (p2x - p1x) * (p2y - p1y); ta = (t2x - t1x) * (t2y - t1y)
union = pa + ta - inter + eps
iou = inter / union
# 中心距 / 最小外接矩形对角线平方
pcx = (p1x + p2x) / 2; pcy = (p1y + p2y) / 2
tcx = (t1x + t2x) / 2; tcy = (t1y + t2y) / 2
c_x1 = torch.min(p1x, t1x); c_y1 = torch.min(p1y, t1y)
c_x2 = torch.max(p2x, t2x); c_y2 = torch.max(p2y, t2y)
rho2 = (pcx - tcx) ** 2 + (pcy - tcy) ** 2
c2 = (c_x2 - c_x1) ** 2 + (c_y2 - c_y1) ** 2 + eps
# 宽高比惩罚 v + 自适应权重 alpha
pw = (p2x - p1x).clamp(min=eps); ph = (p2y - p1y).clamp(min=eps)
tw = (t2x - t1x).clamp(min=eps); th = (t2y - t1y).clamp(min=eps)
v = (4 / (torch.pi ** 2)) * (torch.atan(pw / ph) - torch.atan(tw / th)) ** 2
alpha = v / ((1 - iou) + v + eps)
return 1 - iou + rho2 / c2 + alpha * v # CIoU 损失 = 1 - CIoU(越小越好)
# 与上面手写 ciou 对照:同尺寸正方形错开 4 像素
b1 = torch.tensor([[10., 10., 30., 30.]])
b2 = torch.tensor([[14., 10., 34., 30.]])
loss_t = ciou_loss_torch(b1, b2).item()
print('CIoU 损失(torch) = %.4f(对应 CIoU = %.4f,与手写 0.6503 一致)' % (loss_t, 1 - loss_t))
assert abs((1 - loss_t) - 0.6503) < 1e-3
class CSPBlock(nn.Module):
# v4 CSPDarknet 的核心块:通道切两半,一半恒等直连、一半过两层卷积再拼回
# 梯度因此有「恒等捷径」直通 + 「变换路径」学特征——梯度双路、参数≈单路
def __init__(self, cin, mid, cout):
super().__init__()
half = cin // 2
self.conv_b = nn.Sequential(nn.Conv2d(half, mid, 1), nn.BatchNorm2d(mid), nn.SiLU(),
nn.Conv2d(mid, half, 3, padding=1), nn.BatchNorm2d(half), nn.SiLU())
self.out = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity()
def forward(self, x):
a, b = torch.chunk(x, 2, dim=1) # 沿通道切两半
y = torch.cat([a, self.conv_b(b)], dim=1) # 一半直连 + 一半变换
return self.out(y)
torch.manual_seed(1)
xin = torch.randn(2, 128, 16, 16)
blk = CSPBlock(128, 64, 128)
y = blk(xin)
print('CSPBlock: (2,128,16,16) ->', tuple(y.shape))
assert tuple(y.shape) == (2, 128, 16, 16)
# 恒等支路不改动前一半:前后对照
assert torch.equal(y[:, :64], xin[:, :64])
print('验证:前一半通道保持恒等直通(梯度捷径成立)✓')
# ============ YOLOv4 完整网络:CSPDarknet mini + PANet + 检测头(torch) ============
import torch
import torch.nn as nn
import torch.nn.functional as F
class YOLOv4Net(nn.Module):
# mini CSPDarknet:CSPBlock 堆叠 + PANet(FPN 后再自底向上补一条)
def __init__(self, n_anchors=3, n_cls=80):
super().__init__()
self.stem = nn.Conv2d(3, 32, 3, 1, 1)
# CSP 骨干:每 stage = 下采样 + CSPBlock
self.d1 = nn.Sequential(ConvBN(32, 64, 3, 2), CSPBlock(64, 64, 64)) # 64->32
self.d2 = nn.Sequential(ConvBN(64, 128, 3, 2), CSPBlock(128, 128, 128)) # 32->16
self.d3 = nn.Sequential(ConvBN(128, 256, 3, 2), CSPBlock(256, 256, 256)) # 16->8
# FPN 投影
self.p1 = nn.Conv2d(64, 128, 1)
self.p2 = nn.Conv2d(128, 128, 1)
self.p3 = nn.Conv2d(256, 128, 1)
# PANet 自底向上(细节送回深层)
self.u2 = nn.Conv2d(128, 128, 3, 2, 1)
self.u3 = nn.Conv2d(128, 128, 3, 2, 1)
self.h3 = YOLOv3Head(128, n_anchors, n_cls)
self.h4 = YOLOv3Head(128, n_anchors, n_cls)
self.h5 = YOLOv3Head(128, n_anchors, n_cls)
def forward(self, x):
f0 = self.stem(x) # (N,32,64,64)
c1 = self.d1(f0) # (N,64,32,32)
c2 = self.d2(c1) # (N,128,16,16)
c3 = self.d3(c2) # (N,256,8,8)
# FPN 自顶向下
p3 = self.p3(c3)
p2 = self.p2(c2) + F.interpolate(p3, scale_factor=2, mode='nearest')
p1 = self.p1(c1) + F.interpolate(p2, scale_factor=2, mode='nearest')
# PANet 自底向上
n1 = p1
n2 = p2 + self.u2(n1)
n3 = p3 + self.u3(n2)
return self.h3(n1), self.h4(n2), self.h5(n3)
torch.manual_seed(0)
net = YOLOv4Net()
x = torch.randn(2, 3, 64, 64)
o1, o2, o3 = net(x)
print('YOLOv4Net 三尺度输出:', tuple(o1.shape), tuple(o2.shape), tuple(o3.shape))
assert tuple(o1.shape) == (2, 3, 32, 32, 85) and tuple(o2.shape) == (2, 3, 16, 16, 85) and tuple(o3.shape) == (2, 3, 8, 8, 85)
print('要点:v4 网络结构 = v3 + CSP + PANet;真正的提升大头在训练配方(Mosaic/CIoU)')
# ===== YOLOv4 模型架构图(CSPDarknet + PANet 双向信息流) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.8))
ax.set_xlim(0, 10); ax.set_ylim(0, 4.2); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2, color='#555'):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color=color, lw=1.6))
box(0.2, 2.2, 1.5, 0.9, '输入图像\n416×416×3', fc='lightyellow')
box(2.1, 2.2, 1.7, 0.9, 'CSPDarknet-53\n(CSP 切分骨干)', fc='lightblue')
# 三尺度特征
box(4.2, 3.1, 1.4, 0.7, 'C3: 52×52', fc='lightgreen')
box(4.2, 2.2, 1.4, 0.7, 'C4: 26×26', fc='lightgreen')
box(4.2, 1.3, 1.4, 0.7, 'C5: 13×13', fc='lightgreen')
arrow(2.1, 2.65, 4.2, 2.65)
# FPN(自顶向下)+ PANet(自底向上)
box(6.0, 3.1, 1.5, 0.7, 'P3: 52×52', fc='lavender')
box(6.0, 2.2, 1.5, 0.7, 'P4: 26×26', fc='lavender')
box(6.0, 1.3, 1.5, 0.7, 'P5: 13×13', fc='lavender')
arrow(6.75, 2.0, 6.75, 2.4, color='#6A5ACD') # 自顶向下
arrow(6.75, 2.9, 6.75, 2.5, color='#A0522D') # 自底向上
ax.text(6.85, 3.5, 'FPN 自顶向下\n(深层语义↓)', fontsize=8.5, color='#6A5ACD')
ax.text(5.4, 0.7, 'PANet 自底向上\n(浅层细节↑)', fontsize=8.5, color='#A0522D')
# 检测头
box(7.9, 3.1, 1.4, 0.7, '检测头×3', fc='lightsalmon')
box(7.9, 2.2, 1.4, 0.7, '检测头×3', fc='lightsalmon')
box(7.9, 1.3, 1.4, 0.7, '检测头×3', fc='lightsalmon')
arrow(7.5, 3.45, 7.9, 3.45); arrow(7.5, 2.55, 7.9, 2.55); arrow(7.5, 1.65, 7.9, 1.65)
ax.set_title('YOLOv4 架构:CSPDarknet + PANet 双向融合(结构),配 Mosaic/CIoU 训练配方', fontsize=12)
plt.tight_layout(); plt.show()
v4 的两个结构手术:Mish 激活与 CSP 梯度切分(原理 + 实现)¶
Mish:$\text{Mish}(x) = x \cdot \tanh(\ln(1+e^x))$ —— 与 ReLU 相比,负区间平滑非单调, 梯度不会硬截断为 0,收敛更稳(很多分类任务白捡 1~2 个点)。
CSP(Cross Stage Partial):输入沿通道切两半,一半恒等直连、一半过卷积再拼回: $$x \to [x_{前半}, \; f(x_{后半})]$$ 梯度因此有「恒等捷径」直通(不衰减)+「变换路径」学特征,双双受益——这就是 v4/v5 的 CSPDarknet 比纯 Darknet 强的地方。
# ================= Mish 手写 + torch 对照 + CSP 通道切分(实现) =================
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def mish_np(x):
# Mish = x·tanh(softplus(x)) = x·tanh(ln(1+e^x)):负区平滑、全局光滑、无硬截断
return x * np.tanh(np.log1p(np.exp(x)))
xt = torch.linspace(-6, 6, 2000, dtype=torch.float64)
m_t = F.mish(xt).numpy()
m_np = mish_np(xt.numpy())
err = np.abs(m_t - m_np).max()
print('Mish 手写 vs torch 最大误差: %.2e' % err)
assert err < 1e-5
# ========== 图:ReLU / SiLU / Mish 曲线对比 ==========
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
x = np.linspace(-6, 6, 400)
fig, ax = plt.subplots(figsize=(7.2, 4.2))
ax.plot(x, np.maximum(x, 0), lw=1.6, label='ReLU(负区硬截断)')
ax.plot(x, x / (1 + np.exp(-x)), lw=1.6, label='SiLU(负区小负值)')
ax.plot(x, mish_np(x), lw=1.8, label='Mish(负区平滑、非单调)')
ax.axhline(0, color='gray', lw=0.6)
ax.set_xlabel('x'); ax.set_ylabel('激活值')
ax.set_title('Mish vs ReLU vs SiLU:负区间的平滑性差异', fontsize=12)
ax.legend(fontsize=9); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
# ---- CSP:通道切半,一半直连一半卷积(v4 CSPDarknet 的核心块) ----
torch.manual_seed(1)
xin = torch.randn(2, 128, 16, 16)
a, b = xin[:, :64], xin[:, 64:] # ① 沿通道切成两半(CSP 的『Partial』)
b = nn.Sequential(nn.Conv2d(64, 64, 1), nn.Conv2d(64, 64, 3, padding=1))(b) # ② 一半学变换
out = torch.cat([a, b], dim=1) # ③ 拼回
print('CSP: (2,128,16,16) -> 切 64+64 -> 一半卷积 -> 拼接 %s(参数量≈单路,梯度却双路)' % (tuple(out.shape),))
assert tuple(out.shape) == (2, 128, 16, 16)
print('为什么有效:路径 A 恒等直通(梯度不衰减),路径 B 学新表示 —— 两路梯度互补(面试一句话)')
Mish 手写 vs torch 最大误差: 8.88e-16
CSP: (2,128,16,16) -> 切 64+64 -> 一半卷积 -> 拼接 (2, 128, 16, 16)(参数量≈单路,梯度却双路) 为什么有效:路径 A 恒等直通(梯度不衰减),路径 B 学新表示 —— 两路梯度互补(面试一句话)
第 5 幕 · YOLOv5(2020):没有论文的工业王者¶
痛点:v4 的论文代码不友好(C 风格、难部署),社区需要"开箱即用"。
方案(工程学巅峰):Ultralytics 把检测做成了一键工具:
- auto-anchor:按数据集自动重新聚类 anchor(不用手动调)
- 超参进化:网格搜索/遗传调 lr、mosaic 比例、损失权重
- 工程细节:Mosaic 变体、缓存、AMP 混合精度、模型导出 ONNX/TFLite/TensorRT
- 模型谱系:s/m/l/x 一档一档卖算力(同一结构不同深度宽度)
为什么它最流行:不是精度最高,而是上手成本最低——pip install ultralytics 三行代码训练。
面试观点题:论文 vs 工程谁更重要? v5 的答案:能落地的工程有时比新结构更有价值。
v5 的 Focus 层(原理 + 实现):开局就省一半算力¶
检测输入分辨率大(v5 常用 640),第一层直接从 3 通道卷到 32 通道太贵。 Focus:把输入隔像素采成 4 个子图拼通道——分辨率减半、通道 ×4,信息零丢失(每个像素都保留), 后续卷积在减半的分辨率上做,直接省一半计算量。
后续版本(v6/v7/v8)改回「stride2 卷积」等价替代:效果一样、实现更简单、部署更友好—— 这也是"工程演进"的活例子。
# ================= v5 的 Focus 层:隔像素采样拼接(numpy 手写 + 信息无损验证) =================
def focus(x):
# x: (B,C,H,W) -> (B,4C,H/2,W/2):按奇偶行/列采 4 个子图,沿通道维拼接
s1 = x[:, :, 0::2, 0::2]; s2 = x[:, :, 0::2, 1::2]
s3 = x[:, :, 1::2, 0::2]; s4 = x[:, :, 1::2, 1::2]
return np.concatenate([s1, s2, s3, s4], axis=1)
rng = np.random.default_rng(0)
xin = rng.normal(size=(2, 3, 8, 8))
f = focus(xin)
print('Focus: (2,3,8,8) -> %s(分辨率 8→4,通道 3→12)' % (f.shape,))
assert f.shape == (2, 12, 4, 4)
# 信息无损验证:4 个子图并集恰为完整原图(对比 09 篇的 patch merge——那里是 2x2 邻域拼,这里是隔像素采)
subs = [xin[:, :, 0::2, 0::2], xin[:, :, 0::2, 1::2], xin[:, :, 1::2, 0::2], xin[:, :, 1::2, 1::2]]
restored = np.stack(subs, axis=1) # (B,4,C,H/2,W/2),与 f 的通道顺序一致
assert np.allclose(f.reshape(2, 4, 3, 4, 4), restored)
print('信息无损:4 个子图并集 = 完整原图 ✓(等价于 stride2 卷积的输入,但把\"下采样\"显式化)')
Focus: (2,3,8,8) -> (2, 12, 4, 4)(分辨率 8→4,通道 3→12) 信息无损:4 个子图并集 = 完整原图 ✓(等价于 stride2 卷积的输入,但把"下采样"显式化)
# ================= YOLOv5:Focus 层 nn.Module(torch 版)——隔像素采样拼通道 =================
import torch
import torch.nn as nn
class Focus(nn.Module):
# 输入 (B,C,H,W) -> (B,4C,H/2,W/2):按奇偶行/列采 4 个子图沿通道拼接,信息零丢失
def __init__(self, cin, cout, k=3):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(cin * 4, cout, k, padding=k // 2, bias=False),
nn.BatchNorm2d(cout),
nn.SiLU(),
)
def forward(self, x):
s1 = x[..., 0::2, 0::2]; s2 = x[..., 0::2, 1::2] # 隔行隔列采样
s3 = x[..., 1::2, 0::2]; s4 = x[..., 1::2, 1::2]
return self.conv(torch.cat([s1, s2, s3, s4], dim=1))
torch.manual_seed(0)
x = torch.randn(2, 3, 8, 8)
# 先验证采样部分(不接 conv):与上面 numpy focus 输出逐位一致
s1 = x[..., 0::2, 0::2]; s2 = x[..., 0::2, 1::2]
s3 = x[..., 1::2, 0::2]; s4 = x[..., 1::2, 1::2]
f = torch.cat([s1, s2, s3, s4], dim=1)
print('Focus(采样): (2,3,8,8) ->', tuple(f.shape), '(分辨率 8→4,通道 3→12)')
assert tuple(f.shape) == (2, 12, 4, 4)
# 信息无损:把 4 个子图按奇偶位置放回,恰为原图(每个像素只出现一次)
restored = torch.empty_like(x)
restored[..., 0::2, 0::2] = s1; restored[..., 0::2, 1::2] = s2
restored[..., 1::2, 0::2] = s3; restored[..., 1::2, 1::2] = s4
assert torch.equal(restored, x)
print('信息无损 ✓:隔像素采样只重新排列像素,不增不减(故 v5 开局不丢信息)')
# 完整 Focus 块(卷积 + BN + SiLU):输出 (B,32,4,4)
foc = Focus(3, 32)
y = foc(x)
print('Focus 完整块: (2,3,8,8) ->', tuple(y.shape))
assert tuple(y.shape) == (2, 32, 4, 4)
print('要点:拼通道后接 stride1 卷积即可保留信息;v6+ 用 stride2 卷积等价替代(实现更简单)')
# ============ YOLOv5 完整网络:Focus + CSP 骨干 + 检测头(torch) ============
import torch
import torch.nn as nn
class YOLOv5Net(nn.Module):
# mini v5:Focus 开局(省一半算力)-> CSP 骨干下采样 -> 单尺度检测头
def __init__(self, n_anchors=3, n_cls=80):
super().__init__()
self.focus = nn.Sequential(
nn.Conv2d(3 * 4, 32, 3, 1, 1, bias=False), nn.BatchNorm2d(32), nn.SiLU())
self.s1 = nn.Sequential(ConvBN(32, 64, 3, 2), CSPBlock(64, 64, 64)) # 32->16
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), CSPBlock(128, 128, 128)) # 16->8
self.head = nn.Conv2d(128, n_anchors * (5 + n_cls), 1)
self.n_anchors, self.n_cls = n_anchors, n_cls
def forward(self, x):
# Focus:隔像素采样拼接成 (N,3*4,H/2,W/2),再卷积
s0 = x[..., 0::2, 0::2]; s1 = x[..., 0::2, 1::2]
s2 = x[..., 1::2, 0::2]; s3 = x[..., 1::2, 1::2]
f = self.focus[0](torch.cat([s0, s1, s2, s3], dim=1)) # (N,32,32,32)
f = self.focus[1:](f)
c1 = self.s1(f) # (N,64,16,16)
c2 = self.s2(c1) # (N,128,8,8)
out = self.head(c2).permute(0, 2, 3, 1) # (N,8,8,A*(5+C))
return out
torch.manual_seed(0)
net = YOLOv5Net(n_anchors=3, n_cls=80)
x = torch.randn(2, 3, 64, 64)
out = net(x)
print('YOLOv5Net: (2,3,64,64) ->', tuple(out.shape))
assert tuple(out.shape) == (2, 8, 8, 255)
print('要点:Focus 让首层在减半分辨率上算 + CSP 恒等捷径 —— 同口径下比 v4 更省算力')
# ===== YOLOv5 模型架构图(Focus + CSP 骨干 + 三尺度头) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 3.8))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.4); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.7))
box(0.2, 1.8, 1.4, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(2.0, 1.8, 1.5, 0.8, 'Focus\n(隔像素拼通道,\n省一半算力)', fc='wheat')
box(3.9, 1.8, 1.7, 0.8, 'CSPDarknet 骨干\n(CSP 切分块)', fc='lightblue')
# 三尺度特征 + FPN/PANet
box(6.0, 2.5, 1.5, 0.7, 'P3: 80×80\n(小物体)', fc='lightgreen')
box(6.0, 1.8, 1.5, 0.7, 'P4: 40×40', fc='lightgreen')
box(6.0, 1.1, 1.5, 0.7, 'P5: 20×20\n(大物体)', fc='lightgreen')
arrow(5.6, 2.2, 6.0, 2.2)
box(7.9, 2.5, 1.6, 0.7, '检测头×3\nanchor-based', fc='lightsalmon')
box(7.9, 1.8, 1.6, 0.7, '检测头×3\nanchor-based', fc='lightsalmon')
box(7.9, 1.1, 1.6, 0.7, '检测头×3\nanchor-based', fc='lightsalmon')
arrow(7.5, 2.85, 7.9, 2.85); arrow(7.5, 2.15, 7.9, 2.15); arrow(7.5, 1.45, 7.9, 1.45)
ax.text(5.15, 3.15, 's/m/l/x 四档:深度宽度缩放', ha='center', fontsize=9, color='#A0522D')
ax.set_title('YOLOv5 架构:Focus 开局 + CSP 骨干(工程化王者:auto-anchor/超参进化)', fontsize=12)
plt.tight_layout(); plt.show()
第 6 幕 · YOLOv6/v7(2022):效率革命¶
痛点:检测头里分类和回归共享一个特征——这两个任务的"想要的东西"经常冲突 (分类要语义、回归要边界细节),耦合头互相干扰。
方案 1(v6,美团):解耦头——分类走一条支路、回归走另一条,各学各的。 顺带:回归目标改成 anchor-free 变体(直接预测中心点到四边的距离,见 v8 详解)。
方案 2(v7,台湾中央研究院):
- E-ELAN:把梯度路径织成网(多条旁路 → 梯度信息不衰减)
- 重参数化(RepConv):训练时多分支、推理时融合成单卷积(省算力,数学等价)
- 辅助头深监督:浅层也接检测头拿梯度(深监督思想,与 U-Net++ 同源!见 09 篇)
# ================= 耦合头 vs 解耦头:形状推演(为什么解耦能缓解任务冲突) =================
import torch
import torch.nn as nn
torch.manual_seed(0)
feat = torch.randn(2, 256, 16, 16) # backbone 输出的共享特征 (N,256,16,16)
C, D = 80, 4 # 80 类、4 个回归量
# 耦合头:一个 1x1 卷积同时出分类(80)与回归(4) → 输出 84 通道(两个任务被迫共享表示)
coupled = nn.Conv2d(256, C + D, 1)
out_coupled = coupled(feat)
# 解耦头:分类 1x1→80、回归 1x1→4,两条支路各学各的(v6/v8 的做法)
cls_head = nn.Conv2d(256, C, 1)
reg_head = nn.Conv2d(256, D, 1)
out_cls, out_reg = cls_head(feat), reg_head(feat)
print('耦合头输出:', tuple(out_coupled.shape), '(84 通道:分类回归挤在一个张量)')
print('解耦头输出: 分类', tuple(out_cls.shape), ' + 回归', tuple(out_reg.shape), '(两条独立支路)')
assert out_coupled.shape == (2, 84, 16, 16) and out_cls.shape == (2, 80, 16, 16) and out_reg.shape == (2, 4, 16, 16)
print('要点:分类支路专注语义(这是什么),回归支路专注边界(框在哪)——互不干扰、各调各的损失')
耦合头输出: (2, 84, 16, 16) (84 通道:分类回归挤在一个张量) 解耦头输出: 分类 (2, 80, 16, 16) + 回归 (2, 4, 16, 16) (两条独立支路) 要点:分类支路专注语义(这是什么),回归支路专注边界(框在哪)——互不干扰、各调各的损失
# ============ YOLOv6 完整网络:骨干 + 解耦头(anchor-free 变体,torch) ============
import torch
import torch.nn as nn
class DecoupledHead(nn.Module):
# v6 核心:分类与回归两条独立支路,各学各的(缓解任务冲突)
def __init__(self, in_ch, n_cls=80):
super().__init__()
self.cls = nn.Sequential(ConvBN(in_ch, in_ch, 1), nn.Conv2d(in_ch, n_cls, 1))
self.reg = nn.Sequential(ConvBN(in_ch, in_ch, 1), nn.Conv2d(in_ch, 4, 1))
def forward(self, x):
return self.cls(x), self.reg(x) # (N,C,H,W), (N,4,H,W)
class YOLOv6Net(nn.Module):
def __init__(self, n_cls=80):
super().__init__()
self.s1 = nn.Sequential(ConvBN(3, 32, 3, 1), ConvBN(32, 64, 3, 2)) # 64->32
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), ConvBN(128, 128, 1), ConvBN(128, 128, 3, 1)) # 32->16
self.s3 = nn.Sequential(ConvBN(128, 256, 3, 2), ConvBN(256, 256, 1), ConvBN(256, 256, 3, 1)) # 16->8
self.head = DecoupledHead(256, n_cls) # 解耦头
def forward(self, x):
c1 = self.s1(x)
c2 = self.s2(c1)
c3 = self.s3(c2) # (N,256,8,8)
cls, reg = self.head(c3)
return cls, reg
torch.manual_seed(0)
net = YOLOv6Net(n_cls=80)
x = torch.randn(2, 3, 64, 64)
cls, reg = net(x)
print('YOLOv6Net: 分类', tuple(cls.shape), ' 回归', tuple(reg.shape), '(两条独立支路)')
assert tuple(cls.shape) == (2, 80, 8, 8) and tuple(reg.shape) == (2, 4, 8, 8)
print('要点:v6 回归目标已是 anchor-free 变体(中心到四边距离),比 v5 少一层 anchor 匹配')
# ===== YOLOv6 模型架构图(骨干 + 解耦头:分类/回归分路) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.0))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.6); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.7))
box(0.2, 1.7, 1.4, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(2.0, 1.7, 1.7, 0.8, '骨干网络\n(EfficientRep)', fc='lightblue')
box(4.1, 1.7, 1.5, 0.8, '共享特征\n(分类语义 +\n回归边界)', fc='lightgreen')
# 解耦头分叉:分类上、回归下
box(6.1, 2.4, 1.7, 0.7, '分类支路\n→ n 类分数', fc='lavender')
box(6.1, 0.9, 1.7, 0.7, '回归支路\n→ (l,t,r,b)', fc='lavender')
arrow(5.6, 2.05, 6.1, 2.55); arrow(5.6, 1.55, 6.1, 1.25)
box(8.2, 2.4, 1.4, 0.7, '分类损失\n(BCE)', fc='lightsalmon')
box(8.2, 0.9, 1.4, 0.7, '回归损失\n(SIoU/CIoU)', fc='lightsalmon')
arrow(7.8, 2.75, 8.2, 2.75); arrow(7.8, 1.25, 8.2, 1.25)
ax.text(6.95, 3.35, '解耦头:两条独立支路,各学各的(缓解任务冲突)', ha='center', fontsize=10, color='#6A5ACD')
ax.set_title('YOLOv6 架构:解耦检测头 —— 分类要语义、回归要边界,互不干扰', fontsize=12)
plt.tight_layout(); plt.show()
v7 的重参数化(RepConv):训练 3 分支,推理 1 个卷积(原理 + 实现)¶
痛点:多分支结构(ResNet 风格)训练好但推理慢——每层 3 条支路要算 3 次。
方案(重参数化,re-parameterization):训练时保留多分支(学得好的关键), 推理前把分支数学等价地融合成一个卷积: $$y = \underbrace{W_3*x + b_3}_{\text{3×3}} + \underbrace{W_1*x + b_1}_{\text{1×1}} + \underbrace{x}_{\text{恒等}} \;\Longrightarrow\; y = W'*x + b'$$
- 1×1 核 pad 到 3×3 中心 = 3×3;恒等 = 单位核放中心 → 三者相加成一个 $W'$
- 融合后推理 = 单次卷积,计算量大幅下降,输出逐位一致(下面数值对照验证)
# ================= RepConv 融合(torch 数值对照:训练 3 分支 == 推理 1 卷积) =================
import torch
import torch.nn as nn
torch.manual_seed(0)
C, F = 8, 8
x = torch.randn(2, C, 6, 6)
conv3 = nn.Conv2d(C, F, 3, padding=1) # 分支①:3x3
conv1 = nn.Conv2d(C, F, 1) # 分支②:1x1
with torch.no_grad():
y3 = conv3(x); y1 = conv1(x); y_id = x # 分支③:恒等(F=C 时)
y_train = y3 + y1 + y_id # 训练输出 = 三支路之和
# ---- 融合:1x1 核 pad 到中心 + 单位核放中心 + 两者与 3x3 相加 ----
k = conv3.weight.data.clone()
k1_pad = torch.zeros(F, C, 3, 3); k1_pad[:, :, 1, 1] = conv1.weight.data[:, :, 0, 0] # 1x1 -> 3x3
k = k + k1_pad
eye = torch.zeros(F, C, 3, 3); eye[:, :, 1, 1] = torch.eye(C) # 恒等 -> 单位核
k = k + eye
b = conv3.bias.data + conv1.bias.data # 三个偏置相加(恒等偏置为 0)
fused = nn.Conv2d(C, F, 3, padding=1)
fused.weight.data = k; fused.bias.data = b
y_fused = fused(x) # 推理输出 = 单卷积
err = (y_train - y_fused).abs().max().item()
print('训练 3 分支 vs 融合单卷积 最大误差: %.2e' % err)
assert err < 1e-5
print('对照通过:融合后输出与训练状态逐位一致(推理只跑 1 个卷积 → v7 部署提速的数学根基)')
训练 3 分支 vs 融合单卷积 最大误差: 1.19e-06 对照通过:融合后输出与训练状态逐位一致(推理只跑 1 个卷积 → v7 部署提速的数学根基)
# ============ YOLOv7 完整网络:E-ELAN 骨干 + RepConv + 解耦头(torch) ============
import torch
import torch.nn as nn
class RepConv(nn.Module):
# 训练 3 分支(3x3 + 1x1 + 恒等),推理时 fuse() 成单卷积(数学等价,见上面 cell)
def __init__(self, cin, cout):
super().__init__()
self.conv3 = nn.Conv2d(cin, cout, 3, padding=1)
self.conv1 = nn.Conv2d(cin, cout, 1)
def forward(self, x):
return self.conv3(x) + self.conv1(x) + x # 恒等分支(要求 cin==cout)
class ELAN(nn.Module):
# v7 的 E-ELAN:多条支路串联、每步结果都保留拼接 → 梯度织成网不衰减
def __init__(self, cin, cout, n=3):
super().__init__()
hid = cin // 2
self.cv0 = nn.Conv2d(cin, hid, 1)
self.cvs = nn.ModuleList([nn.Conv2d(hid, hid, 3, padding=1) for _ in range(n)])
self.out = nn.Conv2d(hid * (n + 1), cout, 1)
def forward(self, x):
y = self.cv0(x)
parts = [y]
for cv in self.cvs:
y = cv(y)
parts.append(y)
return self.out(torch.cat(parts, dim=1))
class YOLOv7Net(nn.Module):
def __init__(self, n_cls=80):
super().__init__()
self.stem = nn.Sequential(ConvBN(3, 32, 3, 1), ConvBN(32, 64, 3, 2))
self.s1 = nn.Sequential(RepConv(64, 64), ELAN(64, 128))
self.s2 = nn.Sequential(ConvBN(128, 128, 3, 2), ELAN(128, 256))
self.cls = nn.Conv2d(256, n_cls, 1)
self.reg = nn.Conv2d(256, 4, 1)
def forward(self, x):
f = self.stem(x) # (N,64,32,32)
f = self.s1(f) # (N,128,32,32)
f = self.s2(f) # (N,256,16,16)
return self.cls(f), self.reg(f)
torch.manual_seed(0)
net = YOLOv7Net()
x = torch.randn(2, 3, 64, 64)
cls, reg = net(x)
print('YOLOv7Net: 分类', tuple(cls.shape), ' 回归', tuple(reg.shape))
assert tuple(cls.shape) == (2, 80, 16, 16) and tuple(reg.shape) == (2, 4, 16, 16)
# 验证 RepConv 融合等价(mini 复刻):fuse 前后输出一致
rc = RepConv(64, 64)
xin = torch.randn(1, 64, 8, 8)
with torch.no_grad():
y_before = rc(xin)
k = rc.conv3.weight.data.clone()
k1 = torch.zeros_like(k); k1[:, :, 1, 1] = rc.conv1.weight.data[:, :, 0, 0]
eye = torch.zeros_like(k); eye[:, :, 1, 1] = torch.eye(64)
fused = nn.Conv2d(64, 64, 3, padding=1)
fused.weight.data = k + k1 + eye
fused.bias.data = rc.conv3.bias.data + rc.conv1.bias.data
err = (y_before - fused(xin)).abs().max().item()
assert err < 1e-5
print('RepConv 融合误差 = %.2e(训练 3 分支 == 推理 1 卷积)✓' % err)
print('要点:v7 = E-ELAN 梯度网 + RepConv 重参数化 + 辅助头深监督 —— 训练强、推理快')
# ===== YOLOv7 模型架构图(E-ELAN 骨干 + RepConv 重参数化) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.2))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.8); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2, color='#555'):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color=color, lw=1.7))
box(0.2, 1.8, 1.3, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(1.9, 1.8, 1.5, 0.8, 'E-ELAN 骨干\n(梯度路径织网)', fc='lightblue')
box(3.8, 1.8, 1.5, 0.8, 'RepConv\n(训练 3 分支)', fc='wheat')
arrow(1.5, 2.2, 1.9, 2.2); arrow(3.4, 2.2, 3.8, 2.2)
# RepConv 融合示意
box(3.8, 0.4, 1.5, 0.7, '推理融合\n(单卷积)', fc='lightgreen')
arrow(4.55, 1.8, 4.55, 1.1, color='#A0522D')
ax.text(4.9, 0.9, '3×3 + 1×1 + 恒等\n数学等价合并', fontsize=8.5, color='#A0522D')
# 辅助头深监督
box(5.9, 2.4, 1.7, 0.7, '检测头(主)', fc='lightsalmon')
box(5.9, 0.4, 1.7, 0.7, '辅助头(深监督)\n浅层也拿梯度', fc='khaki')
arrow(5.3, 2.0, 5.9, 2.45)
arrow(3.0, 1.2, 5.9, 0.75, color='#8B6914')
box(8.0, 2.4, 1.5, 0.7, '解码 + NMS\n→ 输出框', fc='lightsalmon')
arrow(7.6, 2.75, 8.0, 2.75)
ax.text(8.75, 3.3, 'E-ELAN:多条旁路 →\n梯度信息不衰减', ha='center', fontsize=9, color='#2E5F9E')
ax.set_title('YOLOv7 架构:E-ELAN 梯度网 + RepConv 重参数化 + 辅助头深监督', fontsize=12)
plt.tight_layout(); plt.show()
第 7 幕 · YOLOv8(2023):anchor-free 的黎明 + 分布回归¶
痛点:anchor 机制其实很繁琐——要聚类、要按尺度分配、要算 IoU 匹配;且框的宽高回归 $\hat{w}=a_w e^{t_w}$ 对大框的偏差不敏感。
方案(v8 三件套):
- anchor-free:回归目标 = 中心点到四边的距离 $(l,t,r,b)$,不再有锚框匹配; decode:$x_1 = c_x - l,\ y_1 = c_y - t,\ x_2 = c_x + r,\ y_2 = c_y + b$
- TaskAlignedAssigner:正负样本分配按「对齐度量」$t = s^\alpha \cdot u^\beta$(分类分 × IoU), 每个 GT 取 top-k —— 同时好的才被选中(替代逐类 IoU 匹配)
- DFL(Distribution Focal Loss):回归输出不再是单个值,而是16 个 bin 的概率分布, 距离 = 分布的期望 —— 对边界细节更敏感(框边缘的"模糊性"被建模)
记忆:v8 = 无锚框 + 对齐分配 + 分布回归 + 解耦头 + C2f 结构。
# ================= v8 解码 + DFL 分布回归(手写) =================
def v8_decode(cx, cy, l, t, r, b):
# anchor-free:中心点 + 中心到四边距离 -> 绝对框 (x1,y1,x2,y2)
return np.array([cx - l, cy - t, cx + r, cy + b])
def dfl(dist_logits, n_bins=16, reg_max=7.0):
# 分布回归:logits -> softmax 概率 -> 期望距离(bin 中心加权)
# 为什么用期望而不是 argmax:框边缘往往"模糊"(介于两个 bin 之间),期望给出亚 bin 精度
p = np.exp(dist_logits - dist_logits.max(axis=1, keepdims=True))
p = p / p.sum(axis=1, keepdims=True)
centers = np.linspace(0, reg_max, n_bins) # bin 中心:0, 0.47, ..., 7.0
return (p * centers).sum(axis=1)
# 演示:模型认为距离"大概 3 附近" → 分布集中在 bin 6/7 → 期望 ≈ 3.03(比硬选 bin 更准)
logits = np.zeros((1, 16))
logits[0, 6:8] = [10.0, 10.0] # 两个 bin 各 ~50%(logits 大 → softmax 尖锐)
d = dfl(logits)[0]
print('分布集中在 bin 6-7 → DFL 期望距离 = %.3f(argmax 只会给出 2.80 或 3.27,期望是两者的插值)' % d)
assert 2.9 < d < 3.2
# round-trip:中心 (200,200) + 四边距离 -> 框 -> 还原距离
cx, cy = 200.0, 200.0
l, t, r, b = 40.0, 30.0, 60.0, 50.0
box = v8_decode(cx, cy, l, t, r, b)
print('v8 decode: (200,200)+边距(40,30,60,50) -> 框', np.round(box, 1))
assert np.allclose(box, [160, 170, 260, 250])
print('还原四边距离: 左=%g 上=%g 右=%g 下=%g(与输入一致 ✓)' %
(cx - box[0], cy - box[1], box[2] - cx, box[3] - cy))
分布集中在 bin 6-7 → DFL 期望距离 = 3.034(argmax 只会给出 2.80 或 3.27,期望是两者的插值) v8 decode: (200,200)+边距(40,30,60,50) -> 框 [160. 170. 260. 250.] 还原四边距离: 左=40 上=30 右=60 下=50(与输入一致 ✓)
# ================= YOLOv8 标签分配:TaskAlignedAssigner(简化手写) =================
# anchor-free 时代的核心问题:预测铺满整图(每个位置一个),谁来负责哪个 GT?
# 对齐度量 t = 分类分^α · IoU^β:分类和定位同时好才算「对齐得好」;每 GT 取 top-k。
def task_aligned_assign(cls_scores, iou_matrix, k=3, alpha=0.5, beta=6.0):
cls_scores = np.asarray(cls_scores, float); iou_matrix = np.asarray(iou_matrix, float)
metric = cls_scores[None, :] ** alpha * iou_matrix ** beta # 对齐度量 (num_gt, num_pred)
pos = np.zeros_like(metric, bool)
for g in range(len(iou_matrix)): # 每个 GT 独立取 top-k
idx = np.argsort(-metric[g])[:k]
pos[g, idx] = True
return metric, pos
# 手算小例子:2 个 GT、5 个预测
cls = np.array([0.8, 0.9, 0.6, 0.2, 0.1])
iou_m = np.array([[0.9, 0.1, 0.2, 0.0, 0.0], # GT1 与各预测的 IoU
[0.2, 0.8, 0.1, 0.5, 0.0]]) # GT2 与各预测的 IoU
metric, pos = task_aligned_assign(cls, iou_m, k=2)
print('对齐度量矩阵:\n', np.round(metric, 4))
print('正样本掩码:\n', pos.astype(int))
# 手算 GT1 行:0.8^0.5·0.9^6 ≈ 0.475;0.9^0.5·0.1^6 ≈ 9e-7;0.6^0.5·0.2^6 ≈ 5e-5 → top2 = 预测0、预测2
gt1 = (cls ** 0.5) * (iou_m[0] ** 6)
assert np.allclose(metric[0], gt1, atol=1e-12) and pos[0].sum() == 2 and pos[1].sum() == 2
print('对照通过:分类分高 + IoU 高才被选中(比只看 IoU 的旧匹配更挑)')
对齐度量矩阵: [[4.753e-01 0.000e+00 0.000e+00 0.000e+00 0.000e+00] [1.000e-04 2.487e-01 0.000e+00 7.000e-03 0.000e+00]] 正样本掩码: [[1 0 1 0 0] [0 1 0 1 0]] 对照通过:分类分高 + IoU 高才被选中(比只看 IoU 的旧匹配更挑)
# ================= YOLOv8:DFL 分布回归 + anchor-free 检测头(torch 版) =================
import torch
import torch.nn as nn
class DFL(nn.Module):
# 分布回归:回归头输出 16 个 bin 的概率分布,距离 = 分布的期望(亚 bin 精度)
def __init__(self, n_bins=16, reg_max=15.0):
super().__init__()
self.register_buffer('proj', torch.linspace(0, reg_max, n_bins)) # bin 中心
def forward(self, logits):
p = logits.softmax(dim=-1) # (...,16) -> 概率
return (p * self.proj).sum(dim=-1) # 期望距离
class V8DetectHead(nn.Module):
# anchor-free 检测头:分类(80) + 对象性(1) + 回归每条边 16-bin 分布(共 4*16)
def __init__(self, in_ch, n_cls=80, n_bins=16):
super().__init__()
self.cls = nn.Conv2d(in_ch, n_cls, 1) # 分类
self.obj = nn.Conv2d(in_ch, 1, 1) # 对象性
self.reg = nn.Conv2d(in_ch, 4 * n_bins, 1) # 四边距离的分布
self.dfl = DFL(n_bins)
def forward(self, x):
b, _, h, w = x.shape
cls = self.cls(x) # (b,80,h,w)
obj = self.obj(x) # (b,1,h,w)
reg = self.reg(x).view(b, 4, 16, h, w) # (b,4,16,h,w)
dist = self.dfl(reg.permute(0, 1, 3, 4, 2)) # (b,4,h,w) 期望距离
return cls, obj, dist
torch.manual_seed(0)
feat = torch.randn(2, 256, 16, 16)
head = V8DetectHead(256)
cls, obj, dist = head(feat)
print('v8 head: 分类', tuple(cls.shape), '| 对象性', tuple(obj.shape), '| 四边距离', tuple(dist.shape))
assert tuple(cls.shape) == (2, 80, 16, 16) and tuple(obj.shape) == (2, 1, 16, 16) and tuple(dist.shape) == (2, 4, 16, 16)
# DFL 手算对照:bin 6/7 各 50%(logits=10)→ 期望 = (6+7)/2 = 6.5
lg = torch.zeros(1, 16); lg[:, 6:8] = 10.0
d = DFL()(lg).item()
print('DFL 期望 = %.3f(bin 6/7 各半 → 6.5,与上面 numpy 版的 3.03 同一机制)' % d)
assert abs(d - 6.5) < 1e-3
# 完整 decode:中心点 (cx,cy) ± 四边距离 -> 绝对框
def v8_decode_t(cx, cy, dist):
l, t, r, b = dist.unbind(dim=-1) # 左/上/右/下距离 (...,)
x1 = cx - l; y1 = cy - t; x2 = cx + r; y2 = cy + b
return torch.stack([x1, y1, x2, y2], dim=-1)
box = v8_decode_t(torch.tensor(200.), torch.tensor(200.), torch.tensor([40., 30., 60., 50.]))
print('v8 decode: (200,200)+边距(40,30,60,50) ->', box.tolist())
assert torch.allclose(box, torch.tensor([160., 170., 260., 250.]))
print('要点:DFL 期望距离去除 argmax 的量化误差 → 框边界亚像素精度(v8 精度提升的关键之一)')
# ============ YOLOv8 完整网络:C2f 骨干 + 解耦头 + DFL(anchor-free,torch) ============
import torch
import torch.nn as nn
class C2f(nn.Module):
# v8 的 C2f:先 1x1 切两半(一半直连 + 一半过 n 个 3x3 并逐步拼接),再 1x1 投影回
def __init__(self, cin, cout, n=2):
super().__init__()
hid = cin // 2
self.cv0 = nn.Conv2d(cin, hid * 2, 1)
self.cvs = nn.ModuleList([nn.Conv2d(hid, hid, 3, padding=1) for _ in range(n)])
self.out = nn.Conv2d(hid * (n + 2), cout, 1)
def forward(self, x):
a, b = torch.chunk(self.cv0(x), 2, dim=1) # 一半直连、一半过支路
ys = [a]
for cv in self.cvs:
b = cv(b)
ys.append(b)
return self.out(torch.cat(ys + [a], dim=1))
class YOLOv8Net(nn.Module):
def __init__(self, n_cls=80, n_bins=16):
super().__init__()
self.s1 = nn.Sequential(ConvBN(3, 32, 3, 2), C2f(32, 64))
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), C2f(128, 128))
self.s3 = nn.Sequential(ConvBN(128, 256, 3, 2), C2f(256, 256))
self.cls = nn.Conv2d(256, n_cls, 1)
self.obj = nn.Conv2d(256, 1, 1)
self.reg = nn.Conv2d(256, 4 * n_bins, 1)
self.dfl = DFL(n_bins)
def forward(self, x):
f = self.s1(x) # (N,64,32,32)
f = self.s2(f) # (N,128,16,16)
f = self.s3(f) # (N,256,8,8)
b = f.shape[0]
cls = self.cls(f)
obj = self.obj(f)
reg = self.reg(f).view(b, 4, 16, 8, 8)
dist = self.dfl(reg.permute(0, 1, 3, 4, 2)) # (b,4,8,8)
return cls, obj, dist
torch.manual_seed(0)
net = YOLOv8Net()
x = torch.randn(2, 3, 64, 64)
cls, obj, dist = net(x)
print('YOLOv8Net: 分类', tuple(cls.shape), ' 对象性', tuple(obj.shape), ' 四边距离', tuple(dist.shape))
assert tuple(cls.shape) == (2, 80, 8, 8) and tuple(obj.shape) == (2, 1, 8, 8) and tuple(dist.shape) == (2, 4, 8, 8)
print('要点:v8 = C2f(更轻的 CSP)+ 无锚框 + 解耦头 + DFL —— 回归从『点估计』升级为『分布期望』')
# ===== YOLOv8 模型架构图(C2f 骨干 + 解耦头 + DFL 分布回归) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.2))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.8); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.7))
box(0.2, 1.8, 1.4, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(2.0, 1.8, 1.6, 0.8, 'C2f 骨干\n(更轻的 CSP)', fc='lightblue')
arrow(1.6, 2.2, 2.0, 2.2)
# 解耦头:分类/对象性/回归(DFL)
box(4.0, 2.6, 1.8, 0.7, '分类头\n→ 80 类分数', fc='lavender')
box(4.0, 1.8, 1.8, 0.7, '对象性头\n→ 1 维', fc='lavender')
box(4.0, 1.0, 1.8, 0.7, '回归头\n→ 4×16 分布', fc='lavender')
arrow(3.6, 2.2, 4.0, 2.2)
# DFL 分布回归说明
box(6.3, 1.0, 2.0, 0.7, 'DFL 期望距离\n(l,t,r,b)', fc='lightgreen')
arrow(5.8, 1.35, 6.3, 1.35)
ax.text(7.3, 0.45, '16-bin softmax → 期望', ha='center', fontsize=8.5, color='#2E5F9E')
box(8.7, 2.6, 1.1, 1.1, '解码\nx1=cx-l\n...', fc='lightsalmon')
arrow(8.4, 2.2, 8.7, 2.2)
ax.text(6.9, 3.35, 'TaskAlignedAssigner:分类分^α · IoU^β 选正样本', ha='center', fontsize=9, color='#6A5ACD')
ax.set_title('YOLOv8 架构:anchor-free + 解耦头 + DFL 分布回归', fontsize=13)
plt.tight_layout(); plt.show()
第 8 幕 · YOLOv9/v10/v11(2024-25):梯度、注意力与 Mamba¶
痛点(v9):深网络训练时梯度信息会流失——浅层拿不到足够梯度 → 学不好小目标。 方案:PGI(可编程梯度信息)——主网络旁边加一个辅助分支(辅助可逆网络)专门喂梯度, 主网络照常推理,训练时多一个损失;配合 GELAN(更轻的聚合网络)做轻量派极致。
痛点(v10):全通道自注意力太贵。 方案:PSA(Partial Self-Attention)——只对部分通道做自注意力(其余通道走卷积分支), 配 C3k2 块 + 双标签分配(一次训练同时优化两个分配策略)→ 精度/延迟平衡。
痛点(v11):越来越快但还想更轻。 方案:C3k2 + C2PSA 轻量块;并探索 Mamba 主干(状态空间模型,线性复杂度长程建模)—— 检测进入「线性注意力」时代。
旁支:YOLO-NAS(AutoML 搜索结构)、RT-DETR(纯 Transformer + 免 NMS)是两套新范式, 但 YOLO 主线仍是 CNN 系。
v9 的 PGI:把「浅层梯度」喂回来(原理 + 数值模拟)¶
痛点本质:网络越深,反传到浅层的梯度越小(每层乘权重的谱范数,<1 就指数衰减)—— 浅层学不到东西,小目标细节就在浅层,于是漏检。
PGI(可编程梯度信息):主网络训练时旁边挂一个辅助分支(像深监督一样额外的损失出口), 浅层因此拿到直接梯度;推理时辅助分支整个剪掉,主网络结构不变。
记忆:PGI = 给梯度"修一条浅层直达的高速公路",与 09 篇 U-Net++ 的深监督是同一个思想家族。
# ================= PGI 梯度模拟:无辅助分支 vs 有辅助分支(数值演示) =================
import numpy as np
rng = np.random.default_rng(0)
def rand_orth(rng, n, s):
# 谱范数恰为 s 的正交缩放矩阵(确定性)
q, _ = np.linalg.qr(rng.normal(size=(n, n)))
return s * q
depth = 6
Ws = [rand_orth(rng, 16, 0.7) for _ in range(depth)] # 每层谱范数 0.7(<1 → 梯度衰减)
def grad_plain(layer_idx):
return float(np.prod([np.linalg.norm(Ws[i], 2) for i in range(layer_idx, depth)])) # 0.7^(层数差)
plain = [grad_plain(i) for i in range(depth)]
pgi = [plain[i] + (0.35 if i <= 2 else 0.0) for i in range(depth)] # PGI:浅层 3 层旁路直接给梯度
print('层 | 无 PGI 梯度 | 有 PGI 梯度')
for i in range(depth):
print(' %d | %.4f | %.4f' % (i, plain[i], pgi[i]))
assert pgi[0] > plain[0] and pgi[1] > plain[1]
print('结论:无 PGI 时浅层梯度仅剩 0.7^5≈%.3f(几乎饿死);PGI 旁路把浅层梯度补到 %.3f → 浅层充分训练' % (plain[0], pgi[0]))
层 | 无 PGI 梯度 | 有 PGI 梯度 0 | 0.1176 | 0.4676 1 | 0.1681 | 0.5181 2 | 0.2401 | 0.5901 3 | 0.3430 | 0.3430 4 | 0.4900 | 0.4900 5 | 0.7000 | 0.7000 结论:无 PGI 时浅层梯度仅剩 0.7^5≈0.118(几乎饿死);PGI 旁路把浅层梯度补到 0.468 → 浅层充分训练
# ================= YOLOv9:PGI 主-辅双分支(torch 版)——辅助分支训练喂梯度、推理剪掉 =================
import torch
import torch.nn as nn
import torch.nn.functional as F
class AuxHead(nn.Module):
# 辅助检测头:挂在浅层/中间特征上,给被困住的浅层梯度修一条「直达高速公路」
def __init__(self, in_ch, n_out):
super().__init__()
self.conv = nn.Sequential(nn.Conv2d(in_ch, in_ch // 2, 1), nn.SiLU(),
nn.Conv2d(in_ch // 2, n_out, 1))
def forward(self, x):
return self.conv(x)
class PGI(nn.Module):
# 主分支:backbone 主干;辅助分支:浅层特征 + AuxHead(训练时两个损失,推理只用主头)
def __init__(self, backbone, main_head, n_out):
super().__init__()
self.backbone = backbone
self.aux = AuxHead(backbone.out_ch, n_out)
self.main = main_head
def forward(self, x, with_aux=True):
shallow, deep = self.backbone(x) # 浅层(小目标细节)+ 深层(语义)
main_out = self.main(deep)
if not with_aux: # 推理:辅助分支剪掉,零额外开销
return main_out, None
aux_out = self.aux(shallow) # 训练:辅助头让浅层直接拿梯度
return main_out, aux_out
class MiniBackbone(nn.Module):
# 两层小骨干:先出浅层特征(stride2),再出深层特征(stride4)
def __init__(self, out_ch=128):
super().__init__()
self.out_ch = out_ch
self.s1 = nn.Sequential(nn.Conv2d(3, 64, 3, 2, 1), nn.BatchNorm2d(64), nn.SiLU())
self.s2 = nn.Sequential(nn.Conv2d(64, out_ch, 3, 2, 1), nn.BatchNorm2d(out_ch), nn.SiLU())
def forward(self, x):
return self.s1(x), self.s2(x)
torch.manual_seed(0)
bb = MiniBackbone(128)
main_head = nn.Conv2d(128, 85, 1) # 主头:3*(5+80)=255 简化成 85 演示形状
pgi = PGI(bb, main_head, n_out=85)
x = torch.randn(2, 3, 64, 64)
main_out, aux_out = pgi(x)
print('PGI 训练: 主头', tuple(main_out.shape), ' 辅助头', tuple(aux_out.shape))
assert tuple(main_out.shape) == (2, 85, 16, 16) and tuple(aux_out.shape) == (2, 85, 32, 32)
main_only, _ = pgi(x, with_aux=False)
print('PGI 推理: 仅主头', tuple(main_only.shape), '(辅助分支剪掉,参数量=主网络,零额外开销)')
assert tuple(main_only.shape) == (2, 85, 16, 16)
# 训练时辅助损失给浅层补梯度(数值演示:浅层权重梯度变大)
opt = torch.optim.SGD(pgi.parameters(), lr=0.01)
target = torch.zeros(2, 85, 16, 16)
loss = F.smooth_l1_loss(main_out, target) + 0.5 * F.smooth_l1_loss(aux_out[:, :, ::2, ::2], target)
loss.backward()
g_s1 = pgi.backbone.s1[0].weight.grad.abs().mean().item()
print('训练后浅层 s1 卷积梯度均值 = %.5f(PGI 让浅层拿到直接梯度,不再梯度饿死)' % g_s1)
assert g_s1 > 0
print('要点:PGI = 训练时浅层多一个监督出口,推理剪掉——深度网络浅层不再学不到')
# ============ YOLOv9 完整网络:GELAN 骨干 + PGI 辅助分支(torch) ============
import torch
import torch.nn as nn
import torch.nn.functional as F
class GELAN(nn.Module):
# v9 的轻量聚合块:多条 3x3 支路串联、结果与恒等路径拼接(信息聚合 + 梯度多路)
def __init__(self, cin, cout, n=2):
super().__init__()
hid = cin // 2
self.cv0 = nn.Conv2d(cin, hid, 1)
self.cvs = nn.ModuleList([nn.Conv2d(hid, hid, 3, padding=1) for _ in range(n)])
self.out = nn.Conv2d(hid * 2 + hid * n, cout, 1) # 恒等 + 主干 + 各支路
def forward(self, x):
y = self.cv0(x)
ys = [x, y]
for cv in self.cvs:
y = cv(y)
ys.append(y)
return self.out(torch.cat(ys, dim=1))
class YOLOv9Net(nn.Module):
# 主路径:s1/s2/s3 逐步下采样;辅助分支:浅层特征接 AuxHead 拿梯度,推理剪掉
def __init__(self, n_cls=80):
super().__init__()
self.s1 = nn.Sequential(ConvBN(3, 32, 3, 2), GELAN(32, 64))
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), GELAN(128, 128))
self.s3 = nn.Sequential(ConvBN(128, 256, 3, 2), GELAN(256, 256))
self.main_head = nn.Conv2d(256, n_cls + 4, 1)
self.aux = nn.Sequential(nn.Conv2d(64, 32, 1), nn.SiLU(), nn.Conv2d(32, n_cls + 4, 1))
def forward(self, x, with_aux=True):
c1 = self.s1(x) # (N,64,32,32)
c2 = self.s2(c1) # (N,128,16,16)
c3 = self.s3(c2) # (N,256,8,8)
main = self.main_head(c3)
if not with_aux:
return main, None
aux = self.aux(c1) # 辅助头挂在浅层,训练时给 c1 直接梯度
return main, aux
torch.manual_seed(0)
net = YOLOv9Net()
x = torch.randn(2, 3, 64, 64)
main, aux = net(x)
print('YOLOv9Net 训练: 主头', tuple(main.shape), ' 辅助头', tuple(aux.shape))
assert tuple(main.shape) == (2, 84, 8, 8) and tuple(aux.shape) == (2, 84, 32, 32)
main_only, _ = net(x, with_aux=False)
print('YOLOv9Net 推理: 仅主头', tuple(main_only.shape), '(辅助分支剪掉,零额外开销)')
assert tuple(main_only.shape) == (2, 84, 8, 8)
print('要点:GELAN 负责轻量聚合,PGI 负责浅层梯度 —— v9 = 结构轻 + 训练深')
# ===== YOLOv9 模型架构图(GELAN 骨干 + PGI 辅助梯度) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 4.0))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.6); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2, color='#555'):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color=color, lw=1.7))
box(0.2, 1.9, 1.3, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(1.9, 1.9, 1.6, 0.8, 'GELAN 骨干\n(轻量聚合块)', fc='lightblue')
box(3.9, 1.9, 1.6, 0.8, 'GELAN 骨干\n(中间特征)', fc='lightblue')
box(5.9, 1.9, 1.6, 0.8, 'GELAN 骨干\n(深层特征)', fc='lightblue')
arrow(1.5, 2.3, 1.9, 2.3); arrow(3.5, 2.3, 3.9, 2.3); arrow(5.5, 2.3, 5.9, 2.3)
# 主头 + 辅助头
box(7.9, 2.0, 1.7, 0.7, '主检测头', fc='lightsalmon')
arrow(7.5, 2.3, 7.9, 2.3)
box(7.9, 0.7, 1.7, 0.7, '辅助检测头\n(挂在浅层)', fc='khaki')
arrow(3.0, 1.5, 7.9, 1.0, color='#8B6914')
ax.text(5.6, 0.9, 'PGI:训练时浅层拿到直接梯度', fontsize=9, color='#8B6914')
ax.text(8.75, 3.15, '推理:辅助分支剪掉', ha='center', fontsize=9, color='#A0522D')
ax.set_title('YOLOv9 架构:GELAN 轻量聚合 + PGI 可编程梯度信息', fontsize=13)
plt.tight_layout(); plt.show()
v10/v11 的 PSA 与 C2PSA:只对「部分通道」做注意力(原理 + 实现)¶
自注意力能力强但贵:$O(\text{通道}^2 \cdot HW)$。PSA(Partial Self-Attention) 的思路是 ——把通道切两半,一半做轻量注意力、一半走卷积,再拼回去:精度掉得很少、算力省一大半。
C2PSA(v11) = CSP 切分 + PSA + 恒等捷径的组合块:在轻量主干的每个阶段用一次, 整体就是「轻量 + 局部注意力」的混合结构。下面用 torch 定义并验证形状。
# ================= PSA / C2PSA:部分通道自注意力(torch 结构 + 形状 + 前向) =================
import torch
import torch.nn as nn
class PSA(nn.Module):
# 输入通道切两半:前半做「轻量注意力」(通道混合 + 深度可分离卷积的局部建模),
# 后半原样直连 —— 自注意力的"全局性"由前半承担,算力只花一半
def __init__(self, C, attn_ratio=0.5):
super().__init__()
self.split = int(C * attn_ratio)
self.mix = nn.Conv2d(self.split, self.split, 1) # 通道混合
self.spatial = nn.Conv2d(self.split, self.split, 3, padding=1, groups=self.split) # 局部空间
def forward(self, x):
a, b = x[:, :self.split], x[:, self.split:]
at = self.mix(a) + self.spatial(a) # 前半: 通道混合 + 局部建模(教学简化版)
return torch.cat([at, b], dim=1) # 拼回(通道数不变)
class C2PSA(nn.Module):
# v11 主干块:压缩->局部卷积->PSA 的「变换路径」 + 原输入的「恒等捷径」
# 两条路径拼接后投影回 C(CSP 风格:梯度一分为二,互不衰减)
def __init__(self, C, e=0.5):
super().__init__()
mid = int(C * e)
self.cv1 = nn.Conv2d(C, mid, 1) # 压缩
self.cv2 = nn.Conv2d(mid, mid, 3, padding=1) # 局部特征
self.psa = PSA(mid) # 部分自注意力
self.cv3 = nn.Conv2d(C + mid, C, 1) # 拼接后投影回 C
def forward(self, x):
y = self.psa(self.cv2(self.cv1(x))) # 变换路径(压缩后的轻量分支)
return self.cv3(torch.cat([x, y], dim=1)) # 恒等捷径(原x) + 变换路径(y)
torch.manual_seed(2)
x = torch.randn(2, 128, 16, 16)
psa = PSA(128); c2psa = C2PSA(128)
print('PSA: (2,128,16,16) -> %s(前 %d 通道做注意力建模)' % (tuple(psa(x).shape), psa.split))
print('C2PSA: (2,128,16,16) -> %s' % (tuple(c2psa(x).shape),))
assert tuple(psa(x).shape) == (2, 128, 16, 16) and tuple(c2psa(x).shape) == (2, 128, 16, 16)
print('要点:C2PSA = CSP 切分 + 部分自注意力 + 恒等捷径 → 用一半的注意力成本拿到接近全注意力的精度')
PSA: (2,128,16,16) -> (2, 128, 16, 16)(前 64 通道做注意力建模) C2PSA: (2,128,16,16) -> (2, 128, 16, 16) 要点:C2PSA = CSP 切分 + 部分自注意力 + 恒等捷径 → 用一半的注意力成本拿到接近全注意力的精度
# ============ YOLOv10/v11 完整网络:C3k2 + C2PSA 骨干 + 解耦头(torch) ============
import torch
import torch.nn as nn
class C3k2(nn.Module):
# v10/v11 的基础块:1x1 切两半(一半直连、一半过小卷积栈),拼接后投影
def __init__(self, cin, cout, k=3, n=2):
super().__init__()
hid = cin // 2
self.cv0 = nn.Conv2d(cin, hid * 2, 1)
self.cvs = nn.ModuleList([nn.Conv2d(hid, hid, k, padding=k // 2) for _ in range(n)])
self.out = nn.Conv2d(hid * 2 + hid * n, cout, 1)
def forward(self, x):
a, b = torch.chunk(self.cv0(x), 2, dim=1)
ys = [a]
for cv in self.cvs:
b = cv(b)
ys.append(b)
return self.out(torch.cat(ys + [a], dim=1))
class YOLOv11Net(nn.Module):
# mini v11:C3k2 下采样骨干 + C2PSA 局部注意力 + 解耦检测头
def __init__(self, n_cls=80):
super().__init__()
self.s1 = nn.Sequential(ConvBN(3, 32, 3, 2), C3k2(32, 64))
self.s2 = nn.Sequential(ConvBN(64, 128, 3, 2), C3k2(128, 128))
self.attn = C2PSA(128, e=0.5) # 部分自注意力(见上面 PSA cell)
self.cls = nn.Conv2d(128, n_cls, 1)
self.reg = nn.Conv2d(128, 4, 1)
def forward(self, x):
f = self.s1(x) # (N,64,32,32)
f = self.s2(f) # (N,128,16,16)
f = self.attn(f) # (N,128,16,16) 注意力建模
return self.cls(f), self.reg(f)
torch.manual_seed(0)
net = YOLOv11Net()
x = torch.randn(2, 3, 64, 64)
cls, reg = net(x)
print('YOLOv11Net: 分类', tuple(cls.shape), ' 回归', tuple(reg.shape))
assert tuple(cls.shape) == (2, 80, 16, 16) and tuple(reg.shape) == (2, 4, 16, 16)
print('要点:v10/v11 = C3k2(更轻的 C2f)+ C2PSA(部分通道注意力)—— 轻量 + 全局建模兼顾')
print('至此 v1→v11 每个版本都有完整可前向的 torch 网络结构 ✓')
# ===== YOLOv10/v11 模型架构图(C3k2 + C2PSA 部分通道注意力) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(10, 3.8))
ax.set_xlim(0, 10); ax.set_ylim(0, 3.4); ax.axis('off')
def box(x, y, w, h, text, fc='lightblue', ec='#2E5F9E'):
ax.add_patch(plt.Rectangle((x, y), w, h, facecolor=fc, edgecolor=ec, linewidth=1.6))
ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=9.5)
def arrow(x1, y1, x2, y2):
ax.annotate('', xy=(x2, y2), xytext=(x1, y1),
arrowprops=dict(arrowstyle='->', color='#555', lw=1.7))
box(0.2, 1.8, 1.4, 0.8, '输入图像\n640×640×3', fc='lightyellow')
box(2.0, 1.8, 1.6, 0.8, 'C3k2 骨干\n(轻量 CSP)', fc='lightblue')
arrow(1.6, 2.2, 2.0, 2.2)
# C2PSA:部分通道注意力
box(4.0, 1.8, 2.2, 0.8, 'C2PSA\n(部分自注意力)', fc='wheat')
arrow(3.6, 2.2, 4.0, 2.2)
ax.text(5.1, 1.2, '通道切两半:\n一半注意力 + 一半卷积', ha='center', fontsize=8.5, color='#8B6914')
box(6.6, 1.8, 1.5, 0.8, '解耦检测头', fc='lightsalmon')
arrow(6.2, 2.2, 6.6, 2.2)
box(8.5, 1.8, 1.3, 0.8, '解码输出', fc='lightsalmon')
arrow(8.1, 2.2, 8.5, 2.2)
ax.text(8.85, 3.05, 'v11 还有 Mamba 主干探索\n(线性复杂度长程建模)', ha='center', fontsize=9, color='#6A5ACD')
ax.set_title('YOLOv10/v11 架构:C3k2 + C2PSA —— 轻量与注意力兼顾', fontsize=13)
plt.tight_layout(); plt.show()
# ===== YOLO v1→v11 演进总览图(十年技术进化史) =====
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
fig, ax = plt.subplots(figsize=(11, 5.6))
ax.set_xlim(0, 11); ax.set_ylim(0, 5.2); ax.axis('off')
versions = [
('v1', 2016, '网格回归\n7×7×30', 'lightyellow', '#8B6914'),
('v2', 2017, 'Anchor + BN\n+ passthrough', 'khaki', '#8B6914'),
('v3', 2018, '多尺度 FPN\n3 个检测头', 'lightblue', '#2E5F9E'),
('v4', 2020, 'CSP + PANet\nMosaic + CIoU', 'lightblue', '#2E5F9E'),
('v5', 2020, 'Focus + CSP\n工程化', 'wheat', '#8B6914'),
('v6', 2022, '解耦头\nanchor-free', 'lavender', '#6A5ACD'),
('v7', 2022, 'E-ELAN\nRepConv 融合', 'lavender', '#6A5ACD'),
('v8', 2023, 'C2f + DFL\n无锚框', 'lightgreen', '#2E7D32'),
('v9', 2024, 'GELAN\nPGI 梯度', 'lightgreen', '#2E7D32'),
('v10', 2024, 'PSA\n部分注意力', 'lightgreen', '#2E7D32'),
('v11', 2025, 'C2PSA\nMamba 探索', 'lightgreen', '#2E7D32'),
]
y = 4.0
for i, (name, year, feat, fc, ec) in enumerate(versions):
x0 = 0.25 + i * 0.98
# 时间线节点
ax.add_patch(plt.Rectangle((x0, y - 0.45), 0.82, 1.05, facecolor=fc, edgecolor=ec, linewidth=1.5))
ax.text(x0 + 0.41, y + 0.28, name + ' (' + str(year) + ')', ha='center', fontsize=9, fontweight='bold')
ax.text(x0 + 0.41, y - 0.05, feat, ha='center', fontsize=7.8, color='#333')
# 关键创新标注
key = ['开山', 'anchor', 'FPN', '配方', '工程', '解耦', '重参数', 'DFL', 'PGI', 'PSA', 'C2PSA'][i]
ax.text(x0 + 0.41, y + 0.52, key, ha='center', fontsize=8, color=ec)
# 底部演进主线箭头
ax.annotate('', xy=(10.6, 2.3), xytext=(0.4, 2.3),
arrowprops=dict(arrowstyle='->', color='#A0522D', lw=2.2))
ax.text(5.5, 1.75, '痛点 → 方案 → 新痛点:十年迭代主线', ha='center', fontsize=11, color='#A0522D')
ax.text(5.5, 1.25, 'v1 朴素回归 → anchor → 多尺度 → 配方/工程 → 效率 → 无锚框/分布回归 → 梯度/注意力', ha='center', fontsize=9.5, color='#555')
ax.set_title('YOLO v1 → v11 演进总览:每一代解决上一代的痛点', fontsize=14)
plt.tight_layout(); plt.show()
§9 跨版本横向对比与选型指南(背诵级)¶
| 版本 | 核心结构 | 分配/损失 | 一句话选型 |
|---|---|---|---|
| v1 | 7×7 网格回归 | 网格直配 | 考古/面试讲损失 |
| v2 | anchor + BN | IoU 匹配 | 理解 anchor 起源 |
| v3 | FPN 三尺度 | IoU 匹配 | 多尺度必考 |
| v4 | CSP+PANet+Mosaic+CIoU | IoU 匹配 | 配方集大成 |
| v5 | 工程化 | IoU 匹配 | 工业默认(易用) |
| v6 | 解耦头 | SimOTA/TAL | 部署优化 |
| v7 | E-ELAN+RepConv | TAL | 边缘设备 |
| v8 | anchor-free+C2f+DFL | TaskAlignedAssigner | 当前主流(生态) |
| v9 | PGI+GELAN | TAL | 轻量派 |
| v10 | PSA+C3k2 | 双标签分配 | 精度/延迟平衡 |
| v11 | C2PSA+Mamba | TAL | 最新轻量 |
选型口诀:要生态选 v8,要省算力选 v9/v11,要部署选 v6/v7,面试从 v1 背到 v8。
# ========== 图:YOLO 演进时间线(AP50 大致轨迹 + 关键转折点) ==========
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
years = [2016, 2017, 2018, 2020, 2020, 2022, 2022, 2023, 2024, 2025, 2025]
aps = [63.4, 78.6, 57.9, 65.7, 66.8, 52.5, 51.4, 53.9, 55.2, 56.5, 57.5] # 各自报告的最优 AP50 档(COCO,v5 微调示意见)
names = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10', 'v11']
fig, ax = plt.subplots(figsize=(9.6, 4.8))
ax.plot(years, aps, '-o', color='#3182bd', lw=1.6, ms=6)
# 标签直接放在数据坐标(±5 单位交替上下):同年份成对的文本框(高约 1.6 单位)间距 10 单位,绝不叠字
for i, (x, y, n) in enumerate(zip(years, aps, names)):
ly = y + (5.0 if i % 2 == 0 else -5.0)
ax.text(x, ly, n, ha='center', fontsize=10, color='#C44E52')
ax.set_xlabel('年份'); ax.set_ylabel('COCO AP50(大致量级)')
ax.set_title('YOLO 十年:从朴素网格回归到 anchor-free + 分布回归', fontsize=13)
ax.set_ylim(44, 86); ax.grid(alpha=0.3); plt.tight_layout(); plt.show()
print('转折点标注:v3 多尺度(2018)、v5 工程化(2020)、v8 anchor-free(2023) —— 三次范式级变化')
转折点标注:v3 多尺度(2018)、v5 工程化(2020)、v8 anchor-free(2023) —— 三次范式级变化
§10 数字敏感度与易错点(扩展背诵)¶
数字
- v1:S=7、B=2、448 输入、输出 7×7×30(PASCAL 20 类)、λ_coord=5、λ_noobj=0.5
- v2:anchor K=5、Darknet-19、检测分辨率 480
- v3:Darknet-53、stride 8/16/32 → 52/26/13、anchor 9 个(3 尺度 × 3 比例)、COCO 每尺度输出 255
- v4:CSP、Mish、Mosaic、CIoU、自对抗训练
- v8:anchor-free 4 距离 + DFL 16 bin + TaskAlignedAssigner(β=6、α=0.5)
- v9:PGI 辅助可逆分支;v10:PSA 部分通道自注意力;v11:C2PSA/Mamba
易错点
- $w/h$ 开根号是「对 √w、√h 做 MSE」,不是平方根损失本身
- anchor 聚类用 IoU 距离,不是欧氏(大框带偏)
- encode $t_w=\log(w/a_w)$、decode 必须 $\exp$ 回去——漏了框就缩没了
- v3 的大特征图(stride 8)管小物体,别记反
- v8 的 anchor-free 不是没有先验,而是回归「中心到四边」,免去锚框匹配
- DFL 是期望回归:分布集中在某 bin 附近时给出亚 bin 精度
§11 面试速答(30 秒背诵版 · 按故事线)¶
- 为什么 v1 开根号:大小框的相对误差同等重视(绝对误差被大框主导)
- 为什么用 anchor:直接回归绝对坐标难收敛;anchor 把任务变成「预测小偏移」
- v2→v3 最大变化:单尺度 → 多尺度 FPN(小物体漏检)+ 多标签 sigmoid
- v4 的核心:训练配方(Mosaic/CIoU/PANet/CSP),不是网络本身
- v5 为什么流行:工程化(auto-anchor/超参进化/一键部署),易用 > 论文
- 解耦头解决什么:分类与回归任务冲突(共享头互相干扰)
- v8 三件套:anchor-free(四边距离)+ TaskAlignedAssigner(对齐度量 top-k)+ DFL(分布期望)
- v9 PGI 是什么:辅助可逆分支喂梯度,解决深网络梯度信息瓶颈
- anchor-free 怎么做:预测中心点到四边距离,decode 直接得框,无锚框匹配
§12 知识链:本篇 → 哪里去?¶
- 向后:
05/09 图像分割—— 检测是框出物体,分割是像素级;U-Net 家族的跳连 = 检测的 FPN 思想在分割里的投影 - 再向后:
10-SAM—— 检测/分割都被「提示」(box/point)驱动,SAM 把分割做成了零样本对话 - 向前:04 篇的 IoU/NMS/anchor/mAP 是本篇的零件库,不会就回去补
- 自测清单
- 默写 v1 损失五项与两个 λ
- 手写 anchor 编解码 round-trip + 聚类(IoU 距离)
- 手写 CIoU 三惩罚项;画损失随错开量曲线
- 手写 v8 decode(中心到四边)+ DFL 期望回归
- 讲清 v1→v11 每条故事线(痛点→方案→新痛点)
- 口算:416 图 stride 32 → 13×13 网格、每格 255 通道