赞
踩
在YOLOV5算法之中,针对不同的数据集,一般会预先设置固定的Anchor;
首先,在网络训练中,网络在初始锚框的基础上输出预测框,进而和Ground Truth进行比对,计算两者差距,再反向更新,迭代网络参数;
可以看出Anchor也是比较重要的一部分,比如Yolov5在Coco数据集上初始设定的锚框:
- anchors:
- - [10,13, 16,30, 33,23] # P3/8 第1行是在最小的特征图上的锚框;
- - [30,61, 62,45, 59,119] # P4/16
- - [116,90, 156,198, 373,326] # P5/32
其中:
注:阅读其它人的博客发现,原来yolov5也可以不预设anchor,也可以直接写个3,此时yolov5就会自动按照训练集聚类anchor,如下:
- # Parameters
- nc: 80 # number of classes
- depth_multiple: 1.0 # model depth multiple
- width_multiple: 1.0 # layer channel multiple
- anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
为啥anchor一行是六个数呢,xywh个数也不对啊?
这里就要说一下anchor是怎么生成的了。
对于输出层(Prediction),经过前面的一系列特征提取和计算操作后,会生成三个特定大小的特征,大小分别为608/8=76,608/16=38,608/32=19,可能这也是输入图像大小要求是32的倍数的原因。
下面是v5代码中采用kmeans计算anchor的过程。
path代表数据yaml路径,n代表聚类数,img_size代表模型输入图片的大小,thr代表长宽比的阈值(将长宽比限定在一定的范围内,这个可以自己统计一下数据集),gen代表kmeans迭代次数。
- def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
- """ Creates kmeans-evolved anchors from training dataset
- Arguments:
- path: path to dataset *.yaml, or a loaded dataset
- n: number of anchors
- img_size: image size used for training
- thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
- gen: generations to evolve anchors using genetic algorithm
- Return:
- k: kmeans evolved anchors
- Usage:
- from utils.general import *; _ = kmean_anchors()
- """
- thr = 1. / thr
-
- def metric(k, wh): # compute metrics
- r = wh[:, None] / k[None]
- x = torch.min(r, 1. / r).min(2)[0] # ratio metric
- # x = wh_iou(wh, torch.tensor(k)) # iou metric
- return x, x.max(1)[0] # x, best_x
-
- def fitness(k): # mutation fitness
- _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
- return (best * (best > thr).float()).mean() # fitness
-
- def print_results(k):
- k = k[np.argsort(k.prod(1))] # sort small to large
- x, best = metric(k, wh0)
- bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
- print('thr=%.2f: %.4f best possible recall, %.2f anchors past thr' % (thr, bpr, aat))
- print('n=%g, img_size=%s, metric_all=%.3f/%.3f-mean/best, past_thr=%.3f-mean: ' %
- (n, img_size, x.mean(), best.mean(), x[x > thr].mean()), end='')
- for i, x in enumerate(k):
- print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
- return k
-
- if isinstance(path, str): # *.yaml file
- with open(path) as f:
- data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
- from utils.datasets import LoadImagesAndLabels
- dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
- else:
- dataset = path # dataset
-
- # Get label wh
- shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
- wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
-
- # Filter
- i = (wh0 < 3.0).any(1).sum()
- if i:
- print('WARNING: Extremely small objects found. '
- '%g of %g labels are < 3 pixels in width or height.' % (i, len(wh0)))
- wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
-
- # Kmeans calculation
- print('Running kmeans for %g anchors on %g points...' % (n, len(wh)))
- s = wh.std(0) # sigmas for whitening
- k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
- k *= s
- wh = torch.tensor(wh, dtype=torch.float32) # filtered
- wh0 = torch.tensor(wh0, dtype=torch.float32) # unflitered
- k = print_results(k)
-
- # Plot
- # k, d = [None] * 20, [None] * 20
- # for i in tqdm(range(1, 21)):
- # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
- # fig, ax = plt.subplots(1, 2, figsize=(14, 7))
- # ax = ax.ravel()
- # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
- # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
- # ax[0].hist(wh[wh[:, 0]<100, 0],400)
- # ax[1].hist(wh[wh[:, 1]<100, 1],400)
- # fig.tight_layout()
- # fig.savefig('wh.png', dpi=200)
-
- # Evolve
- npr = np.random
- f, sh, mp, s = fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
- pbar = tqdm(range(gen), desc='Evolving anchors with Genetic Algorithm') # progress bar
- for _ in pbar:
- v = np.ones(sh)
- while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
- v = ((npr.random(sh) < mp) * npr.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
- kg = (k.copy() * v).clip(min=2.0)
- fg = fitness(kg)
- if fg > f:
- f, k = fg, kg.copy()
- pbar.desc = 'Evolving anchors with Genetic Algorithm: fitness = %.4f' % f
- if verbose:
- print_results(k)
-
- return print_results(k)
-

上面的计算过程相当于将我画的长宽比先转化到resize640大小的长宽比下,再进行聚类,得到9个聚类中心,每个聚类中心包含(x,y)坐标就是我们需要的anchor如下:
134,38, 172,35, 135,48, 175,43, 209,38, 174,62, 254,69, 314,82, 373,95
将其放入list
- #anchors:
- #1. [10,13, 16,30, 33,23] # P3/8 608/8=76
- #2. [30,61, 62,45, 59,119] # P4/16 608/16=38
- #3. [116,90, 156,198, 373,326] # P5/32 608/32=19
- 1. [134,38,135,48,172,35] # P3/8 608/8=76
- 2. [174,62,175,43,209,38] # P4/16 608/16=38
- 3. [254,69,314,82,373,95] # P5/32 608/32=19
-
这里的thr其实是和hyp.scratch.yaml文件中的anchor_t一样,代表了anchor放大的scale,我的标注框长宽比最大在8左右,因此设置为8。
接下来就是anchor在模型中的应用了。这就涉及到了yolo系列目标框回归的过程了。
yolov5中的detect模块沿用了v3检测方式,这里就用这种方式来阐述了。
1.检测到的不是框,是偏移量。
- tx,ty指的是针对所在grid的左上角坐标的偏移量
- tw,th指的是相对于anchor的宽高的偏移量
通过如下图的计算方式,得到bx,by,bw,bh就是最终的检测结果。
2. 前面经过backbone,neck, head是panet的三个分支,可见特征图size不同,每个特征图分了13个网格,同一尺度的特征图对应了3个anchor,检测了[c,x,y,w,h]和num_class个的one-hot类别标签。3个尺度的特征图,总共就有9个anchor。
参考:
(173条消息) YOLOv5的Backbone详解_Marlowee的博客-CSDN博客_yolov5 backbone
Yolov5-模型配置文件(yolov5l.yaml)讲解 - 知乎 (zhihu.com)
YOLOv5-Lite 详解教程 | 嚼碎所有原理和思想、训练自己数据集、TensorRT部署落地应有尽有 - 知乎 (zhihu.com)
(11条消息) yolov5的anchor详解_anny_jra的博客-CSDN博客_yolov5的anchor
(3条消息) YOLOv5的anchor设定_Marlowee的博客-CSDN博客_yolov5 anchor设置
(13条消息) YOLO系列详解:YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5_AI小白一枚的博客-CSDN博客_yolo
(14条消息) 【目标检测】yolo系列:从yolov1到yolov5之YOLOv3详解及复现_看星星的月儿的博客-CSDN博客_yolo 输出维度 (14条消息) YOLOv1——YOLOX系列及FCOS目标检测算法详解_神洛华的博客-CSDN博客_fcos和yolo
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。