yolov3聚类自己数据的anchor box

本文介绍如何使用K-means算法基于自定义数据集为YOLOv3模型聚类生成更合适的Anchor Box尺寸,提高目标检测精度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

yolov3是一个很优秀的object-detection模型,其中的anchor box机制在多尺度检测上取得了不错的效果。然而,作者提供的anchor box值是基于voc和coco数据集上的,如果应用到自己数据集可能不完全适用,那么如何基于自己的训练数据聚类anchor box呢?好吧,源代码如下所示。

kemans.py

import numpy as np


def iou(box, clusters):
    """
    Calculates the Intersection over Union (IoU) between a box and k clusters.
    :param box: tuple or array, shifted to the origin (i. e. width and height)
    :param clusters: numpy array of shape (k, 2) where k is the number of clusters
    :return: numpy array of shape (k, 0) where k is the number of clusters
    """
    x = np.minimum(clusters[:, 0], box[0])
    y = np.minimum(clusters[:, 1], box[1])
    if np.count_nonzero(x == 0) > 0 or np.count_nonzero(y == 0) > 0:
        raise ValueError("Box has no area")

    intersection = x * y
    box_area = box[0] * box[1]
    cluster_area = clusters[:, 0] * clusters[:, 1]

    iou_ = intersection / (box_area + cluster_area - intersection)

    return iou_


def avg_iou(boxes, clusters):
    """
    Calculates the average Intersection over Union (IoU) between a numpy array of boxes and k clusters.
    :param boxes: numpy array of shape (r, 2), where r is the number of rows
    :param clusters: numpy array of shape (k, 2) where k is the number of clusters
    :return: average IoU as a single float
    """
    return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])])


def translate_boxes(boxes):
    """
    Translates all the boxes to the origin.
    :param boxes: numpy array of shape (r, 4)
    :return: numpy array of shape (r, 2)
    """
    new_boxes = boxes.copy()
    for row in range(new_boxes.shape[0]):
        new_boxes[row][2] = np.abs(new_boxes[row][2] - new_boxes[row][0])
        new_boxes[row][3] = np.abs(new_boxes[row][3] - new_boxes[row][1])
    return np.delete(new_boxes, [0, 1], axis=1)


def kmeans(boxes, k, dist=np.median):
    """
    Calculates k-means clustering with the Intersection over Union (IoU) metric.
    :param boxes: numpy array of shape (r, 2), where r is the number of rows
    :param k: number of clusters
    :param dist: distance function
    :return: numpy array of shape (k, 2)
    """
    rows = boxes.shape[0]

    distances = np.empty((rows, k))
    last_clusters = np.zeros((rows,))

    np.random.seed()

    # the Forgy method will fail if the whole array contains the same rows
    clusters = boxes[np.random.choice(rows, k, replace=False)]

    while True:
        for row in range(rows):
            distances[row] = 1 - iou(boxes[row], clusters)

        nearest_clusters = np.argmin(distances, axis=1)

        if (last_clusters == nearest_clusters).all():
            break

        for cluster in range(k):
            clusters[cluster] = dist(boxes[nearest_clusters == cluster], axis=0)

        last_clusters = nearest_clusters

    return clusters

cluster.py


import glob
import xml.etree.ElementTree as ET
import numpy as np
from kemans import kmeans, avg_iou

ANNOTATIONS_PATH = "F:/garbage/annotations"
CLUSTERS = 12


def load_dataset(path):
    dataset = []
    for xml_file in glob.glob("{}/*xml".format(path)):
        tree = ET.parse(xml_file)

        height = int(tree.findtext("./size/height"))
        width = int(tree.findtext("./size/width"))

        for obj in tree.iter("object"):
            xmin = int(obj.findtext("bndbox/xmin")) / width
            ymin = int(obj.findtext("bndbox/ymin")) / height
            xmax = int(obj.findtext("bndbox/xmax")) / width
            ymax = int(obj.findtext("bndbox/ymax")) / height

            xmin = np.float64(xmin)
            ymin = np.float64(ymin)
            xmax = np.float64(xmax)
            ymax = np.float64(ymax)
            if xmax == xmin or ymax == ymin:
                print(xml_file)
            dataset.append([xmax - xmin, ymax - ymin])
    return np.array(dataset)


if __name__ == '__main__':
    # print(__file__)
    data = load_dataset(ANNOTATIONS_PATH)
    out = kmeans(data, k=CLUSTERS)
    # clusters = [[10,13],[16,30],[33,23],[30,61],[62,45],[59,119],[116,90],[156,198],[373,326]]
    # out= np.array(clusters)/416.0
    print(out)
    print("Accuracy: {:.2f}%".format(avg_iou(data, out) * 100))
    print("Boxes:\n {}-{}".format(out[:, 0] * 608, out[:, 1] * 608))

    ratios = np.around(out[:, 0] / out[:, 1], decimals=2).tolist()
    print("Ratios:\n {}".format(sorted(ratios)))

最终聚类的结果:

[[0.3770724  0.15486111]
 [0.03958333 0.0375    ]
 [0.20677083 0.13686314]
 [0.0703125  0.05347222]
 [0.17916667 0.08472222]
 [0.47375    0.24791667]
 [0.08489583 0.08819444]
 [0.125      0.0625    ]
 [0.12447917 0.11319444]
 [0.28541667 0.1025    ]
 [0.2640625  0.21597222]
 [0.14942708 0.1875    ]]
Accuracy: 75.99%
Boxes:
 [229.26001999  24.06666667 125.71666667  42.75       108.93333333
 288.04        51.61666667  76.          75.68333333 173.53333333
 160.55        90.85166667]-[ 94.15555556  22.8         83.21278721  32.51111111  51.51111111
 150.73333333  53.62222222  38.          68.82222222  62.32
 131.31111111 114.        ]
Ratios:
 [0.8, 0.96, 1.06, 1.1, 1.22, 1.31, 1.51, 1.91, 2.0, 2.11, 2.43, 2.78]
### YOLOv5 中的聚类实现或通过聚类算法优化模型 #### 聚类在目标检测中的作用 在目标检测任务中,尤其是像YOLOv5这样的单阶段检测器中,锚框(anchor boxes)的设计至关重要。锚框用于表示图像中可能的目标位置和大小。为了设计合适的锚框,可以利用聚类算法分析训练集中对象的真实边界框分布。 K-Means 是一种常用的聚类方法,在YOLO系列模型中被广泛应用于锚框生成。其核心思想是最小化同一簇内的距离平方误差 (Sum of Squared Errors, SSE)[^3]。然而,传统的欧几里得距离并不适合衡量边界框之间的差异,因为它们不仅取决于宽度和高度,还依赖于IoU(Intersection over Union)。因此,改进版的距离度量方式——基于 IoU 的 K-Means 方法被引入到 YOLO 模型中[^1]。 #### 使用 K-Means 进行锚框生成 以下是基于 K-Means 和 IoU 度量生成锚框的具体过程: ```python import numpy as np def iou(box, clusters): """ 计算一个box与所有clusters之间的iou值 :param box: 单个真实框(宽高), shape=(2,) :param clusters: 所有候选anchors集合, shape=(k, 2) :return: ious, shape=(k,) """ x = np.minimum(clusters[:, 0], box[0]) y = np.minimum(clusters[:, 1], box[1]) intersection = x * y area_box = box[0] * box[1] areas_clusters = clusters[:, 0] * clusters[:, 1] ious = intersection / (area_box + areas_clusters - intersection) return ious def avg_iou(boxes, clusters): """ 计算所有boxes相对于clusers的平均iou :param boxes: 真实框集合, shape=(N, 2) :param clusters: anchor集合, shape=(k, 2) :return: 平均iou值 """ return np.mean([np.max(iou(boxes[i], clusters)) for i in range(boxes.shape[0])]) def kmeans(boxes, k=9, dist=np.median): """ 利用k-means计算最佳anchors尺寸 :param boxes: 真实框集合, shape=(N, 2) :param k: anchors数量 :param dist: 距离函数,默认取中位数作为最终结果 :return: 最佳anchors集合, shape=(k, 2) """ rows = boxes.shape[0] distances = np.empty((rows, k)) last_clusters = np.zeros((rows,)) np.random.seed() clusters = boxes[np.random.choice(rows, k, replace=False)] # 随机初始化k个中心 while True: for row_idx in range(rows): distances[row_idx] = 1 - iou(boxes[row_idx], clusters) nearest_clusters = np.argmin(distances, axis=1) # 寻找最近的cluster if (last_clusters == nearest_clusters).all(): break for cluster_idx in range(k): clusters[cluster_idx] = dist(boxes[nearest_clusters == cluster_idx], axis=0) # 更新center last_clusters = nearest_clusters return clusters ``` 上述代码实现了基于 IoU 的 K-Means 锚框生成逻辑。它能够有效减少预测偏移并提高定位精度。 #### 多视图特征学习增强模型性能 除了传统意义上的锚框优化外,还可以借鉴多视图聚类的思想进一步提升模型表现。例如,可以通过构建多层次特征提取网络来捕捉不同尺度下的细节信息,并结合对比损失函数强化区分能力[^5]。具体来说,可以在 backbone 后面加入额外分支专门处理特定类型的输入数据流(如颜色空间转换后的版本),从而形成互补视角以辅助决策制定过程。 最后值得注意的是,虽然进化算法提供了另一种解决复杂多目标问题的可能性[^4],但在实际工程实践中往往更倾向于选择简单高效的传统方法除非遇到特别困难的情况才考虑尝试前者。 ---
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值