iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >yolov5中anchors设置实例详解
  • 172
分享到

yolov5中anchors设置实例详解

2024-04-02 19:04:59 172人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录一、默认锚定框二、自定义锚定框1、训练时自动计算锚定框2、训练前手动计算锚定框参考的博文(表示感谢!):总结yolov5中增加了自适应锚定框(Auto Learning Boun

yolov5中增加了自适应锚定框(Auto Learning Bounding Box Anchors),而其他yolo系列是没有的。

一、默认锚定框

Yolov5 中默认保存了一些针对 coco数据集的预设锚定框,在 yolov5 的配置文件*.yaml 中已经预设了640×640图像大小下锚定框的尺寸(以 yolov5s.yaml 为例):

# anchors
anchors:
  - [10,13, 16,30, 33,23]  # P3/8
  - [30,61, 62,45, 59,119]  # P4/16
  - [116,90, 156,198, 373,326]  # P5/32

 anchors参数共有三行,每行9个数值;且每一行代表应用不同的特征图;

1、第一行是在最大的特征图上的锚框

2、第二行是在中间的特征图上的锚框

3、第三行是在最小的特征图上的锚框;

在目标检测任务中,一般希望在大的特征图上去检测小目标,因为大特征图才含有更多小目标信息,因此大特征图上的anchor数值通常设置为小数值,而小特征图上数值设置为大数值检测大的目标。

二、自定义锚定框

1、训练时自动计算锚定框

yolov5 中不是只使用默认锚定框,在开始训练之前会对数据集中标注信息进行核查,计算此数据集标注信息针对默认锚定框的最佳召回率,当最佳召回率大于或等于0.98,则不需要更新锚定框;如果最佳召回率小于0.98,则需要重新计算符合此数据集的锚定框。

核查锚定框是否适合要求的函数在 /utils/autoanchor.py 文件中:

def check_anchors(dataset, model, thr=4.0, imgsz=640):

 其中 thr 是指 数据集中标注框宽高比最大阈值,默认是使用 超参文件 hyp.scratch.yaml 中的 “anchor_t” 参数值。

核查主要代码如下:

    def metric(k):  # compute metric
        r = wh[:, None] / k[None]
        x = torch.min(r, 1. / r).min(2)[0]  # ratio metric
        best = x.max(1)[0]  # best_x
        aat = (x > 1. / thr).float().sum(1).mean()  # anchors above threshold
        bpr = (best > 1. / thr).float().mean()  # best possible recall
        return bpr, aat
 
    bpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))

其中两个指标需要解释一下(bpr 和 aat):

bpr(best possible recall) 

aat(anchors above threshold) 

 其中 bpr 参数就是判断是否需要重新计算锚定框的依据(是否小于 0.98)。

重新计算符合此数据集标注框的锚定框,是利用 kmean聚类方法实现的,代码在  /utils/autoanchor.py 文件中:

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
            verbose: print all results
        Return:
            k: kmeans evolved anchors
        Usage:
            from utils.autoanchor import *; _ = kmean_anchors()
    """
    thr = 1. / thr
    prefix = colorstr('autoanchor: ')
 
    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 anchor_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(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
        print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
              f'past_thr={x[x > thr].mean():.3f}-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.SafeLoader)  # 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(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
    wh = wh0[(wh0 >= 2.0).any(1)]  # filter > 2 pixels
    # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1)  # multiply by random scale 0-1
 
    # Kmeans calculation
    print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
    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)  # unfiltered
    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), tight_layout=True)
    # 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.savefig('wh.png', dpi=200)
 
    # Evolve
    npr = np.random
    f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1  # fitness, generations, mutation prob, sigma
    pbar = tqdm(range(gen), desc=f'{prefix}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 = anchor_fitness(kg)
        if fg > f:
            f, k = fg, kg.copy()
            pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
            if verbose:
                print_results(k)
 
    return print_results(k)

对 kmean_anchors()函数中的参数做一下简单解释(代码中已经有了英文注释):

  • path:包含数据集文件路径等相关信息的 yaml 文件(比如 coco128.yaml), 或者 数据集张量(yolov5 自动计算锚定框时就是用的这种方式,先把数据集标签信息读取再处理)
  • n:锚定框的数量,即有几组;默认值是9
  • img_size:图像尺寸。计算数据集样本标签框的宽高比时,是需要缩放到 img_size 大小后再计算的;默认值是640
  • thr:数据集中标注框宽高比最大阈值,默认是使用 超参文件 hyp.scratch.yaml 中的 “anchor_t” 参数值;默认值是4.0;自动计算时,会自动根据你所使用的数据集,来计算合适的阈值。
  • gen:kmean聚类算法迭代次数,默认值是1000
  • verbose:是否打印输出所有计算结果,默认值是true

如果你不想自动计算锚定框,可以在 train.py 中设置参数即可:

parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')

2、训练前手动计算锚定框

如果使用 yolov5 训练效果并不好(排除其他原因,只考虑 “预设锚定框” 这个因素), yolov5在核查默认锚定框是否符合要求时,计算的最佳召回率大于0.98,没有自动计算锚定框;此时你可以自己手动计算锚定框。【即使自己的数据集中目标宽高比最大值小于4,默认锚定框也不一定是最合适的】

 首先可以自行编写一个程序,统计一下你所训练的数据集所有标签框宽高比,看下宽高比主要分布在哪个范围、最大宽高比是多少? 比如:你使用的数据集中目标宽高比最大达到了 5:1(甚至 10:1) ,那肯定需要重新计算锚定框了,针对coco数据集的最大宽高比是 4:1 。

然后在 yolov5 程序中创建一个新的 python 文件 test.py,手动计算锚定框:

import utils.autoanchor as autoAC
 
# 对数据集重新计算 anchors
new_anchors = autoAC.kmean_anchors('./data/mydata.yaml', 9, 640, 5.0, 1000, True)
print(new_anchors)

输入信息如下(只截取了部分):

autoanchor: Evolving anchors with Genetic Algorithm: fitness = 0.6604:  87%|████████▋ | 866/1000 [00:00<00:00, 2124.00it/s]autoanchor: thr=0.25: 0.9839 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.662-mean/best, past_thr=0.476-mean: 15,20,  38,25,  55,65,  131,87,  97,174,  139,291,  256,242,  368,382,  565,422
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  39,26,  54,64,  127,87,  97,176,  142,286,  257,245,  374,379,  582,424
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  39,26,  54,63,  126,86,  97,176,  143,285,  258,241,  369,381,  583,424
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  39,26,  54,63,  127,86,  97,176,  143,285,  258,241,  369,380,  583,424
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  39,26,  53,63,  127,86,  97,175,  143,284,  257,243,  369,381,  582,422
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  40,26,  53,62,  129,85,  96,175,  143,287,  256,240,  370,378,  582,419
autoanchor: Evolving anchors with Genetic Algorithm: fitness = 0.6605: 100%|██████████| 1000/1000 [00:00<00:00, 2170.29it/s]
Scanning '..\coco128\labels\train2017.cache' for images and labels... 128 found, 0 missing, 2 empty, 0 corrupted: 100%|██████████| 128/128 [00:00<?, ?it/s]
autoanchor: thr=0.25: 0.9849 best possible recall, 3.84 anchors past thr
autoanchor: n=9, img_size=640, metric_all=0.267/0.663-mean/best, past_thr=0.476-mean: 15,20,  40,26,  53,62,  129,85,  96,175,  143,287,  256,240,  370,378,  582,419
[[     14.931      20.439]
 [     39.648       25.53]
 [     53.371       62.35]
 [     129.07      84.774]
 [     95.719      175.08]
 [     142.69      286.95]
 [     256.46      239.83]
 [      369.9       378.3]
 [     581.87      418.56]]
 
Process finished with exit code 0

输出的 9 组新的锚定框即是根据自己的数据集来计算的,可以按照顺序替换到你所使用的配置文件*.yaml中(比如 yolov5s.yaml)。就可以重新训练了。

参考的博文(表示感谢!):

https://GitHub.com/ultralytics/yolov5

Https://blog.csdn.net/flyfish1986/article/details/117594265

https://zhuanlan.zhihu.com/p/183838757

https://blog.csdn.net/aabbcccDDD01/article/details/109578614

总结

到此这篇关于yolov5中anchors设置详解的文章就介绍到这了,更多相关yolov5 anchors设置内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: yolov5中anchors设置实例详解

本文链接: https://www.lsjlt.com/news/118861.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • yolov5中anchors设置实例详解
    目录一、默认锚定框二、自定义锚定框1、训练时自动计算锚定框2、训练前手动计算锚定框参考的博文(表示感谢!):总结yolov5中增加了自适应锚定框(Auto Learning Boun...
    99+
    2024-04-02
  • Spring boot跨域设置实例详解
    定义:跨域是指从一个域名的网页去请求另一个域名的资源1.原由公司内部有多个不同的子域,比如一个是location.company.com ,而应用是放在app.company.com , 这时想从 app.company.com去访问 lo...
    99+
    2023-05-30
    springboot 跨域设置 spring boo
  • ASP.NET session.timeout设置案例详解
    session.timeout 方法一: asp.net Session的默认时间设置是20分钟,即超过20分钟后,服务器会自动放弃Session信息. 当我们在asp.net程序中...
    99+
    2024-04-02
  • Vue组件如何设置Props实例详解
    目录属性类型属性默认值属性值验证Composition API 中设置属性总结在 Vue 中构建组件通常需要定义一些属性,以使组件可以更好复用,在这种情况下会使用 props 来自定...
    99+
    2024-04-02
  • yolov5模型配置yaml文件详细讲解
    目录以models/yolov5s.yaml为例我们一个一个来解释:补充:模型 yaml 文件中第四参数解释总结 yolov5的代码模型构建是通过.yaml文件实现的,初次...
    99+
    2024-04-02
  • java中设计模式(多例)的实例详解
    java中设计模式(多例)的实例详解多例:单例设计模式的变形,可以看成是一个缓存池的单例,而缓存池里面可以存多个数据实例代码://单例+缓存---没有控制池大小public class A { //1创建一个单例的池(private即把池...
    99+
    2023-05-31
    java 多例 ava
  • Web应用中设置Context Path案例详解
    URL:http://hostname.com/contextPath/servletPath/pathInfo Jetty 如果没有contextPath,则默认使用root上下文...
    99+
    2024-04-02
  • yolov5中head修改为decouple head详解
    目录yolox的decoupled head结构对于decouple head的改进特点疑问总结yolov5的head修改为decouple head yolox的decoupled...
    99+
    2024-04-02
  • Nginx缓存设置案例详解
    在开发调试web的时候,经常会碰到因浏览器缓存(cache)而经常要去清空缓存或者强制刷新来测试的烦恼,提供下apache不缓存配置和nginx不缓存配置的设置。在常用的缓存设置里面...
    99+
    2024-04-02
  • SpringBoot中YAML配置文件实例详解
    目录一、YAML 简介1、什么是 YAML ?2、优点3、扩展名4、语法规则5、格式二、三种配置文件1、properties 类型2、yml 类型3、yaml 类型4、优先级三、YA...
    99+
    2023-05-15
    spring boot yaml yaml配置文件 springboot yaml配置文件
  • Pandas中八个常用option设置的示例详解
    目录前言1. 显示更多行2. 显示更多列3. 改变列宽4. 设置float列的精度5. 数字格式化显示用逗号格式化大值数字设置数字精度百分号格式化6. 更改绘图方法7. 配置info...
    99+
    2024-04-02
  • itext生成PDF设置页眉页脚的实例详解
    itext生成PDF设置页眉页脚的实例详解实例代码: package com.labci.itext.test; import java.awt.Color; import java.io.FileNotFoundException; im...
    99+
    2023-05-31
    itext pdf te
  • Vue的Props实例配置详解
    目录1、Prop 的大小写2、Prop 类型3、Prop验证4、传递静态|动态 Prop5、修改Prop数据适用于:父子组件通信。 如果父组件给子组件传递(函数)数据:本质是子组件给...
    99+
    2022-11-13
    Vue Props Vue Props配置 Vue Props设置
  • java 中file.encoding的设置详解
    java 中file.encoding的设置详解昨天有人在讨论关于设置System的property,file.encoding 修改defaultcharset无效Properties pps=System.getProperties()...
    99+
    2023-05-31
    java file.encoding ava
  • PyTorch中torch.nn.Linear实例详解
    目录前言1. nn.Linear的原理:2. nn.Linear的使用:3. nn.Linear的源码定义:补充:许多细节需要声明总结前言 在学习transformer时,遇到过非常...
    99+
    2024-04-02
  • spring中aop的xml配置方法实例详解
    前言AOP:即面向切面编程,是一种编程思想,OOP的延续。在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等等。aop,面向切面编程的目标就是分离关注点,比如:一个骑士只需要关注守护安全,或者远征,而骑士辉煌一生的事迹由谁...
    99+
    2023-05-31
    spring aop xml配置
  • mysql中workbench实例详解
    MySQL Workbench - 建模和设计工具 1.模型是大多数有效和高性能数据库的核心。MySQL workbench具有允许开发人员和数据库管理员可视化地创建物理数据库设计模型的工具,这些模型可以使...
    99+
    2024-04-02
  • PyTorch中torch.utils.data.DataLoader实例详解
    1、dataset:(数据类型 dataset) 输入的数据类型,这里是原始数据的输入。PyTorch内也有这种数据结构。 2、batch_size:(数据类型 int) 批训练数...
    99+
    2024-04-02
  • Java 用反射设置对象的属性值实例详解
    Java 用反射设置对象的属性值实例详解private Object invoke(Object obj, String fieldName, Object value) { String firstWord = fieldName.su...
    99+
    2023-05-31
    java 反射 对象
  • three.js响应式设计实例详解
    目录1-canvas 的响应式布局示例:三维插图2-自适应设备分辨率总结源码地址:github.com/buglas/thre… 1-canvas 的响应式布局 can...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作