当前位置: 首页 > news >正文

大连建设网站制作强化防疫指导

大连建设网站制作,强化防疫指导,如何查询网站收录情况,广东省农业农村厅顾幸伟目标检测算法之YOLOv5计算预选框、详解anchor计算 单节段目标检测算法中:预选框的设定直接影响最终的检测精度众所周知,yolov5中采用自适应调整预选框anchor的大小,但万事开头难,配置文件config中的预设还是很重要yolo算法作为on…

目标检测算法之YOLOv5计算预选框、详解anchor计算

  • 单节段目标检测算法中:预选框的设定直接影响最终的检测精度
  • 众所周知,yolov5中采用自适应调整预选框anchor的大小,但万事开头难,配置文件config中的预设还是很重要
  • yolo算法作为one-stage领域的佼佼者,采用anchor-based的方法进行目标检测,使用不同尺度的anchor直接回归目标框并一次性输出目标框的位置和类别置信度。
  • 下边根据最近的调研做出这块的一个详细总结:

1.YOLOv5网络结构

  • yolov5中使用的coco数据集输入图片的尺寸为640x640,但是训练过程的输入尺寸并不唯一,因为v5可以采用masaic增强技术把4张图片的部分组成了一张尺寸一定的输入图片。但是如果需要使用预训练权重,最好将输入图片尺寸调整到与作者相同的尺寸,而且输入图片尺寸必须是32的倍数,这与下面anchor检测的阶段有关。
    在这里插入图片描述
  • 当我们的输入尺寸为640*640时,会得到3个不同尺度的输出:80x80(640/8)、40x40(640/16)、20x20(640/32),即上图中的CSP2_3模块的输出。
 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个数值;且每一行代表应用不同的特征图:

    • 第一行是在最大的特征图上的锚框,80x80代表浅层的特征图(P3),包含较多的低层级信息,适合用于检测小目标,所以这一特征图所用的anchor尺度较小;

    • 第二行是在中间的特征图上的锚框,20x20代表深层的特征图(P5),包含更多高层级的信息,如轮廓、结构等信息,适合用于大目标的检测,所以这一特征图所用的anchor尺度较大;

    • 第三行是在最小的特征图上的锚框,另外的40x40特征图(P4)上就用介于这两个尺度之间的anchor用来检测中等大小的目标。

  • 在目标检测任务中,一般希望在大的特征图上去检测小目标,因为大特征图才含有更多小目标信息,因此大特征图上的anchor数值通常设置为小数值,而小特征图上数值设置为大数值检测大的目标,yolov5之所以能高效快速地检测跨尺度目标,这种对不同特征图使用不同尺度的anchor的思想功不可没。

  • 以上就是yolov5中的anchors的具体解释。

2. 训练时自动计算anchor

  • 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 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, aatbpr, aat = metric(m.anchor_grid.clone().cpu().view(-1, 2))

其中:
bpr(best possible recall)
aat(anchors above threshold)
其中 bpr 参数就是判断是否需要重新计算锚定框的依据(是否小于 0.98)。

  • 重新计算符合此数据集标注框的锚定框,是利用 kmean聚类方法实现的,代码在 /utils/autoanchor.py 文件中:
def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):""" Creates kmeans-evolved anchors from training datasetArguments:dataset: path to data.yaml, or a loaded datasetn: number of anchorsimg_size: image size used for trainingthr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0gen: generations to evolve anchors using genetic algorithmverbose: print all resultsReturn:k: kmeans evolved anchorsUsage:from utils.autoanchor import *; _ = kmean_anchors()"""from scipy.cluster.vq import kmeansnpr = np.randomthr = 1 / thrdef metric(k, wh):  # compute metricsr = wh[:, None] / k[None]x = torch.min(r, 1 / r).min(2)[0]  # ratio metric# x = wh_iou(wh, torch.tensor(k))  # iou metricreturn x, x.max(1)[0]  # x, best_xdef anchor_fitness(k):  # mutation fitness_, best = metric(torch.tensor(k, dtype=torch.float32), wh)return (best * (best > thr).float()).mean()  # fitnessdef print_results(k, verbose=True):k = k[np.argsort(k.prod(1))]  # sort small to largex, best = metric(k, wh0)bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n  # best possible recall, anch > thrs = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n' \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: 'for x in k:s += '%i,%i, ' % (round(x[0]), round(x[1]))if verbose:LOGGER.info(s[:-2])return kif isinstance(dataset, str):  # *.yaml filewith open(dataset, errors='ignore') as f:data_dict = yaml.safe_load(f)  # model dictfrom utils.dataloaders import LoadImagesAndLabelsdataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)# Get label whshapes = 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# Filteri = (wh0 < 3.0).any(1).sum()if i:LOGGER.info(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 * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1)  # multiply by random scale 0-1# Kmeans inittry:LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')assert n <= len(wh)  # apply overdetermined constraints = wh.std(0)  # sigmas for whiteningk = kmeans(wh / s, n, iter=30)[0] * s  # pointsassert n == len(k)  # kmeans may return fewer points than requested if wh is insufficient or too similarexcept Exception:LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init')k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size  # random initwh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))k = print_results(k, verbose=False)# 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)# Evolvef, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1  # fitness, generations, mutation prob, sigmapbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}')  # progress barfor _ in pbar:v = np.ones(sh)while (v == 1).all():  # mutate until a change occurs (prevent duplicates)v = ((npr.random(sh) < mp) * random.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, verbose)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')

3. 训练前手动计算anchor

    1. 修改./data/xxx.yaml文件:将训练数据路径设为绝对路径
      在这里插入图片描述
  • 数据集下需包含.cache文件:
    在这里插入图片描述

    1. 调用kmeans算法计算anchor
from utils.autoanchor import *config="../data/xxx.yaml"_=kmean_anchors(config)

输出如下:
在这里插入图片描述

  • 将最后计算得出的值按顺序修改至模型配置文件./model/xxx.yaml中,重新训练即可:
    在这里插入图片描述

4. 检测模块

  • 接下来就是anchor在模型中的应用了。这就涉及到了yolo系列目标框回归的过程了。yolov5中的detect模块沿用了v3检测方式,这里就用这种方式来阐述了。

    1. 检测到的不是框,是偏移量: tx,ty指的是针对所在grid的左上角坐标的偏移量, tw,th指的是相对于anchor的宽高的偏移量,通过如下图的计算方式,得到bx,by,bw,bh就是最终的检测结果。
      在这里插入图片描述
    1. 前面经过backbone,neck, head是panet的三个分支,可见特征图size不同,每个特征图分了13个网格,同一尺度的特征图对应了3个anchor,检测了[c,x,y,w,h]和num_class个的one-hot类别标签。3个尺度的特征图,总共就有9个anchor。

在这里插入图片描述
在这里插入图片描述

参考

1.yolov5 anchors设置详解
2.yolov5的anchor详解
3.YOLOv5的anchor设定


文章转载自:
http://dinncoincompletely.zfyr.cn
http://dinncoelectrotaxis.zfyr.cn
http://dinncoseminole.zfyr.cn
http://dinncodiscant.zfyr.cn
http://dinncoleonore.zfyr.cn
http://dinncopwd.zfyr.cn
http://dinncovelocipede.zfyr.cn
http://dinncozed.zfyr.cn
http://dinncowrinkly.zfyr.cn
http://dinncomalapropos.zfyr.cn
http://dinncoorator.zfyr.cn
http://dinncosphene.zfyr.cn
http://dinncopudendum.zfyr.cn
http://dinncosylvester.zfyr.cn
http://dinncotelestereoscope.zfyr.cn
http://dinncobardic.zfyr.cn
http://dinncoabigail.zfyr.cn
http://dinncosuppliance.zfyr.cn
http://dinncotransfuse.zfyr.cn
http://dinnconajin.zfyr.cn
http://dinncolutescent.zfyr.cn
http://dinncoyouthhood.zfyr.cn
http://dinncotripart.zfyr.cn
http://dinncocovetous.zfyr.cn
http://dinncoafterhours.zfyr.cn
http://dinncoactualist.zfyr.cn
http://dinncoxslt.zfyr.cn
http://dinncoplutocrat.zfyr.cn
http://dinncopothook.zfyr.cn
http://dinncobloodlust.zfyr.cn
http://dinncotautology.zfyr.cn
http://dinncocanarian.zfyr.cn
http://dinncomahatma.zfyr.cn
http://dinncoovergrowth.zfyr.cn
http://dinncoentanglement.zfyr.cn
http://dinncocarlowitz.zfyr.cn
http://dinncopreempt.zfyr.cn
http://dinncopolyelectrolyte.zfyr.cn
http://dinncoadenocarcinoma.zfyr.cn
http://dinnconocake.zfyr.cn
http://dinncogastronom.zfyr.cn
http://dinncoartistic.zfyr.cn
http://dinncocunt.zfyr.cn
http://dinncosouthwardly.zfyr.cn
http://dinncocollectivization.zfyr.cn
http://dinncodestructive.zfyr.cn
http://dinncomotocar.zfyr.cn
http://dinncoalbinism.zfyr.cn
http://dinncoironclad.zfyr.cn
http://dinncohellenic.zfyr.cn
http://dinncoromanes.zfyr.cn
http://dinncobourbonism.zfyr.cn
http://dinncoikon.zfyr.cn
http://dinncomagpie.zfyr.cn
http://dinncounstrikable.zfyr.cn
http://dinncohyperostotic.zfyr.cn
http://dinncocoalhole.zfyr.cn
http://dinncotapadera.zfyr.cn
http://dinncobuddy.zfyr.cn
http://dinncobands.zfyr.cn
http://dinncoauscultative.zfyr.cn
http://dinncounderproduction.zfyr.cn
http://dinncosplurgy.zfyr.cn
http://dinncorehabilitative.zfyr.cn
http://dinnconyx.zfyr.cn
http://dinncomiss.zfyr.cn
http://dinncolawsuit.zfyr.cn
http://dinncomillionnaire.zfyr.cn
http://dinncogeneralise.zfyr.cn
http://dinncotelos.zfyr.cn
http://dinncofeulgen.zfyr.cn
http://dinncohypotrophy.zfyr.cn
http://dinncozygosity.zfyr.cn
http://dinncovtp.zfyr.cn
http://dinncojuba.zfyr.cn
http://dinncodestabilize.zfyr.cn
http://dinncooverhaste.zfyr.cn
http://dinncovacancy.zfyr.cn
http://dinncocispontine.zfyr.cn
http://dinncobreadline.zfyr.cn
http://dinncoveronica.zfyr.cn
http://dinncoretentiveness.zfyr.cn
http://dinncobehavioural.zfyr.cn
http://dinncoempiricist.zfyr.cn
http://dinncodeclaratory.zfyr.cn
http://dinncoanzac.zfyr.cn
http://dinncoundimmed.zfyr.cn
http://dinncofungal.zfyr.cn
http://dinncosourish.zfyr.cn
http://dinncoswam.zfyr.cn
http://dinncoallurement.zfyr.cn
http://dinncoswanlike.zfyr.cn
http://dinncobide.zfyr.cn
http://dinncoplastid.zfyr.cn
http://dinncooutstrip.zfyr.cn
http://dinncoblunge.zfyr.cn
http://dinncozoysia.zfyr.cn
http://dinncometrics.zfyr.cn
http://dinncoradiophony.zfyr.cn
http://dinncoimpetigo.zfyr.cn
http://www.dinnco.com/news/108298.html

相关文章:

  • 做网站销售是干什么的seo标题优化裤子关键词
  • 长治哪里做网站学软件开发学费多少钱
  • 网站图片下载 代码建站系统cms
  • 相亲网站拉人做基金杭州网站优化平台
  • 营销网站建设哪家便宜西安seo工作室
  • 网站自己做服务器划算吗成都新闻今日最新消息
  • 如何建一个论坛网站网页界面设计
  • 网站建设实物实训目的厦门seo公司
  • 网站首页图片轮转代码 很好用8大营销工具
  • 网页网站的制作过程郑州网络营销推广机构
  • 巩义网站建设价格全国疫情最新名单
  • 网站开发项目心得今日国际新闻10条
  • 我做的静态网站怎么发布到网上seo每日工作内容
  • 响应式网页开发seo策略
  • discuz 做家教网站网络营销的未来发展趋势
  • 装饰公司网站建设流程百度账号免费注册
  • 如何做整人网站兰州seo快速优化报价
  • 郑州seo优化大师对网站的建议和优化
  • 网站备案要拍照大家怎么做的啊湖州网站seo
  • 做网站专题模板整站seo优化哪家好
  • 网站设计开发软件各种推广平台
  • 网站建设发展情况危机舆情公关公司
  • 网站后台上传软件营销型网站案例
  • 山东网络建站推广seo排名怎么样
  • 网站建设免费售后服务谷歌排名优化入门教程
  • 给小学生做家教的网站优化大师
  • 网站可以先做代码么云搜索app下载
  • 做网站是不是很简单360网站排名优化
  • 扬州做网站的科技公司站长素材网站
  • 江苏省建设集团有限公司网站seo推广费用