YOLOV5源代码学习之check_anchors()函数

article/2025/11/5 14:50:48

该函数主要在train.py中调用

 为了方便直观的阅读代码,对代码中的变量值进行了输出

def check_anchors(dataset, model, thr=4.0, imgsz=640):# Check anchor fit to data, recompute if necessaryprefix = colorstr('autoanchor: ')print(f'\n{prefix}Analyzing anchors... ', end='')m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1]  shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1))  # augment scalewh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float()  # wh

dataset中有697张图片,imgsz=640

prefix='[34m[1mautoanchor: [0m'

m=Detect(
  (m): ModuleList(
    (0): Conv2d(128, 21, kernel_size=(1, 1), stride=(1, 1))
    (1): Conv2d(256, 21, kernel_size=(1, 1), stride=(1, 1))
    (2): Conv2d(512, 21, kernel_size=(1, 1), stride=(1, 1))
  )
)

shapes中的数据如下(共计697张图片,图片从0开始计数到696)

scale中的数据如下

 for循环中的第一个s=[     646.25      363.51],这两个数是scale和shapes的乘积

第一个l=[[          0     0.50703     0.45451     0.51719     0.24792]],这是数据集的标签

wh用来存储训练数据中所有gt框的宽高,其shape为(N,2),N为gt框的总个数,此处N=697

wh=tensor([ [334.23145,  90.12132],
                    [350.72150, 153.06581],
                    [349.53928, 101.28985],
                    ...,
                    [349.43201, 202.97702],
                    [358.07135, 103.62663],
                    [356.24854, 120.78210]])

    def metric(k):  # compute metricr = wh[:, None] / k[None]x = torch.min(r, 1. / r).min(2)[0]  # ratio metricbest = x.max(1)[0]  # best_xaat = (x > 1. / thr).float().sum(1).mean()  # anchors above thresholdbpr = (best > 1. / thr).float().mean()  # best possible recallreturn bpr, aatanchors = m.anchor_grid.clone().cpu().view(-1, 2)  # current anchorsbpr, aat = metric(anchors)

此处由后一行代码调用的metric()函数,因此按代码执行顺序来看

anchors=tensor([ [ 10.,  13.],
                            [ 16.,  30.],
                            [ 33.,  23.],
                            [ 30.,  61.],
                            [ 62.,  45.],
                            [ 59., 119.],
                            [116.,  90.],
                            [156., 198.],
                            [373., 326.]])

进入metric()函数,通过anchors和wh来计算bpr,aat(anchors above threshold) 两个指标

r=tensor([ [ [33.42315,  6.93241],
                   ...,
                   [ 0.89606,  0.27645]],
                   ...,

                 [ [35.62486,  9.29093],
                   ...,
                   [ 0.95509,  0.37050]]])

x的shape[N,9],即[697,9]

x=tensor([ [0.02992, 0.04787, 0.09873,  ..., 0.34706, 0.45516, 0.27645],
                 ...,
                 [0.02807, 0.04491, 0.09263,  ..., 0.32562, 0.43790, 0.37050]])

best=tensor([0.45516, 0.46953, 0.44630, 0.49288, 0.41652, 0.43961, 0.42956, ..., 0.43790])

best的shape为N,即697

thr=4.0

aat=tensor(2.94835)

bpr=tensor(1.)

  • bpr(best possible recall): 最多能被召回的gt框数量 / 所有gt框数量 最大值为1 越大越好 小于0.98就需要使用k-means + 遗传进化算法选择出与数据集更匹配的anchors框。
print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
if bpr < 0.98:  # threshold to recomputeprint('. Attempting to improve anchors, please wait...')na = m.anchor_grid.numel() // 2  # number of anchorstry:anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)except Exception as e:print(f'{prefix}ERROR: {e}')new_bpr = metric(anchors)[0]if new_bpr > bpr:  # replace anchorsanchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid)  # for inferencem.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1)  # losscheck_anchor_order(m)print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')else:print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
print('')  # newline

此处bpr=1.0>0.98,因此不进入if判断语句

如果进入if判断语句,就会调用kmean_anchors()函数


http://chatgpt.dhexx.cn/article/GBPN9vok.shtml

相关文章

QML入门教程(3): anchors的用法

QML的布局方法是anchors,锚。 例如界面上四个按钮,可以用绝对坐标 (x, y) 设置他们的位置, 代码如下: import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.5Window {visible: truewidth: 320height: 480title: qsTr("Hello World")co…

目标检测2——借Detectron2源码理解Anchors与RPN

文章目录 1.Regionn Proposal Network背景2.Regionn Proposal Network的结构3.Anchors4.Regionn Proposal Network的训练参考资料 欢迎访问个人网络日志&#x1f339;&#x1f339;知行空间&#x1f339;&#x1f339; 1.Regionn Proposal Network背景 RPN&#xff0c;Region …

QML基础:锚anchors

正文 除了传统的Grid、Row和Column外,Qt Quick还提供了一种使用锚点的方法来布局。可以将每个元素视为具有7条不可见的“锚定线”的集合:left、horizontalCenter、right、top、verticalCenter、baseline和bottom。 baseline(上图未展示)对应于文本所在的虚线。对于没有文…

细说目标检测中的Anchors

本文转载自AI公园。 作者&#xff1a;Raghul Asokan 编译&#xff1a;ronghuaiyang 导读 给大家再次解释一下Anchors在物体检测中的作用。 今天&#xff0c;我将讨论在物体检测器中引入的一个优雅的概念 —— Anchors&#xff0c;它是如何帮助检测图像中的物体&#xff0c;以及…

anchors布局

anchors布局 import QtQuick 2.2 import QtQuick.Window 2.2 Window {visible: truewidth: 640height: 480title: qsTr("Hello World")Rectangle {width: 300;height: 200;color: "blue";Rectangle {id: rectl;anchors.left: parent.left;anchors.leftMar…

PDU Session Anchors

在同一时刻&#xff0c;UE可以建立多条到同一个DN或不同DN的PDU会话&#xff1b;建立到同一个DN的多个PDU会话时&#xff0c;通过不同的UPF&#xff1b;每条PDU会话对应的SMF可以不同。 为了支持到DN的可选择路由功能或支持SSC mode 3模式&#xff0c;SMF可以控制PDU session的…

kmeans++聚类生成anchors

kmeans聚类生成anchors 说明 使用yolo系列通常需要通过kmeans聚类算法生成anchors&#xff0c; 但kmeans算法本身具有一定的局限性&#xff0c;聚类结果容易受初始值选取影响。 因此通过改进原kmeans_for_anchors.py实现 kmeans聚类生成anchors。具体实现如下&#xff1a; i…

anchors如何获得_Yolov3通过k-means聚类得到自己数据的anchors

本文代码参考: https://github.com/lars76/kmeans-anchor-boxes Yolov3中默认的9个anchors是作者通过对voc数据聚类得到的。 anchors 10,14, 23,27, 37,58, 81,82, 135,169, 344,319 不过&#xff0c;当我们训练自己的数据时&#xff0c;如果也采用默认的anchors&#xff0c;可…

Unity 锚点 Anchors

锚点介绍 锚点是Rect Transform组件中的属性&#xff0c;用于描述当前物体相对于父物体的对齐方式。 选中一个UI元素&#xff0c;就会显示其父物体的矩形框以及相对于父物体的锚点。 锚点只能位于父物体的矩形框之内。 锚点表现为四个相对出现的小三角形&#xff0c; 它们时而…

QML anchors 锚布局

锚布局 锚布局有7种锚线 anchors.leftanchors.rightanchors.topanchors.bottomanchors.horizontalCenteranchors.verticalCenteranchors.baseline 5种锚边距 anchors.leftMarginanchors.rightMarginanchors.topMarginanchors.bottomMarginanchors.margins 3种锚偏移 anchor…

anchors生成

关于修改anchor anchor与图片的输入分辨率有关系。 You should use this repository to get anchors: https://github.com/AlexeyAB/darknet By using this command for Yolo v3 (or v2): ./darknet detector calc_anchors data/hand.data -num_of_clusters 9 -width 720 -he…

使用k-means聚类anchors

在之前讲yolo理论基础知识时有提到过&#xff0c;从yolov2开始使用的anchors都是通过聚类得到的。如果想了解更多yolo相关的知识可以看看我在bilibili上录得视频&#xff1a;https://www.bilibili.com/video/BV1yi4y1g7ro 今天补下之前没有细讲的聚类anchors相关知识&#xff…

细说物体检测中的Anchors

点击上方“AI公园”&#xff0c;关注公众号&#xff0c;选择加“星标“或“置顶” 作者&#xff1a;Raghul Asokan 编译&#xff1a;ronghuaiyang 导读 给大家再次解释一下Anchors在物体检测中的作用。 今天&#xff0c;我将讨论在物体检测器中引入的一个优雅的概念 —— Ancho…

带图讲解,深度学习YOLO里面的anchors的进阶理解

如果有了解过yolo网络&#xff0c;那肯定也听说过anchors&#xff0c;当然anchors这个概念布置在YOLO里面才有&#xff0c;在其他的目标检测中也存在anchors这个概念。对于anchors计算的一些公式这篇文章就不进行讲解了&#xff0c;这篇文章主要是讲在训练网络模型过程中anchor…

Linux终端的网易云音乐——musicbox

网易云音乐是听歌的不错的选择&#xff0c;如果能够在命令行听歌就更cool了。特来推荐musicbox。 网易云音乐的musicbox是网易云音乐命令行版本&#xff0c;这款命令行的客户端使用 Python 构建&#xff0c;以 mpg123 作为播放后端。提供了很多使用的功能&#xff0c;如&#x…

MusicStore-2

1.按照MusicStore-1步骤创建mvc项目&#xff0c;并初始化数据库 2.修改HomeController using Chapter8.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc;namespace Chapter8.Controllers {public class…

音乐i网站

开发工具(eclipse/idea/vscode等)&#xff1a; 数据库(sqlite/mysql/sqlserver等)&#xff1a; 功能模块(请用文字描述&#xff0c;至少200字) &#xff1a;

musicbox(暂停/启动,停止,下一曲上一首)

主界面 按下开始 按下暂停 按下停止 下一首 上一首 代码 activity_main.xml <?xml version"1.0" encoding"utf-8"?> <LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"android:orientation"vertical&…

node-webkit-MusicBox 基于nwjs ,html5 ,制作的音乐盒子

太长&#xff1f;单击目录直接去看最终效果&#xff0c;在最下边 文件下载地址&#xff1a;http://download.csdn.net/detail/u013934914/9180053 1.思路&#xff08;简单设想&#xff09; index.html 实现 对页面的显示&#xff0c;并调用绑定ymusic.js中的方法 需要&…

算数计算机音乐模拟器,Musicalculator

musicalculatorapp它是一个音乐旋律软件&#xff0c;在这上面你可以随时随地的记录你有灵感时创作出来的乐谱&#xff0c;还可以放好听的音色包进行自动的弹奏&#xff0c;还可以根据自己的想法设定速度音长&#xff0c;这一款非常的适合喜爱音乐的用户。该应用只是一款音乐计算…