[目标检测] 如何获取数据集对应的anchor size

背景:由于yolov5需要根据size生成候选anchor,因此用yolov5训练某个特定的数据集时,如果没有设置对应的anchor size。那么可能出现很多乱框的现象。

可以通过.pt文件就能读取到anchor size的参数。输入是.pt文件,输出是

python 复制代码
const int anchor0[6] = {3, 5, 6, 5, 5, 11};
const int anchor1[6] = {10, 9, 10, 17, 21, 11};
const int anchor2[6] = {20, 25, 39, 21, 47, 47};
python 复制代码
import torch
from models.experimental import attempt_load

model = attempt_load('/root/yolov5-master/runs/train/exp8/weights/best.pt')
m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1]

# Convert to CPU for easier manipulation
for i, grid in enumerate(m.anchor_grid):
    grid = grid.cpu()  # Move to CPU if on GPU
    anchor_sets = []

    # Traverse the second dimension (3 anchor sets)
    for j in range(3):  # Since the second dimension is of size 3
        # Extract the first two 'anchors' from each set (assuming we only want the first two for each set)
        anchor_pair = grid[0, j, 0, 0].tolist()  # [0, 0] for spatial dimensions, assuming we want the first anchor
        anchor_sets.append([round(x) for x in anchor_pair])

    # Flatten and format for C-style declaration
    flat_anchors = [item for pair in anchor_sets for item in pair]
    print(f"const int anchor{i}[6] = {{{', '.join(map(str, flat_anchors))}}};")
相关推荐
老猿AI洞察2 小时前
阿里云启用巴西数据中心,AI服务出海落子南半球
人工智能·阿里云·云计算
大金SEO2 小时前
GEO启动的正确顺序:先做信源清理,再谈内容扩张
大数据·人工智能
Bruce_Liuxiaowei2 小时前
从基础理论开始学习人工智能(三):盲目搜索——从状态空间图到生成-测试范式
人工智能·学习
qyz_hr3 小时前
拥抱AI,红海云筑牢企业组织与人力数据底层能力
人工智能
Capricorn19883 小时前
个人知识库接入大模型频现“幻觉引用”?排查 RAG 溯源失效问题,解析知芽构建可信第三大脑的底层架构
大数据·论文阅读·人工智能·笔记·架构·论文笔记
LaughingZhu3 小时前
Product Hunt 每日热榜 | 2026-08-27
人工智能·深度学习·神经网络·搜索引擎·百度
时代分流3 小时前
生成式搜索时代的 GEO 技术体系与落地实践:解析矩擎 GEO 5.0 全栈架构
人工智能
DeepAgent3 小时前
AI Agent 工程实践(35):我的 AI Engineering OS 最终架构
大数据·人工智能·agent
陈年老古董3 小时前
深度学习入门笔记:从神经元到深度神经网络
人工智能·笔记·深度学习·神经网络·学习