You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Detectron2生成与YOLO相同的评估指标?

在Detectron2中生成目标检测评估指标(F1/PR曲线/混淆矩阵等)

Detectron2默认未集成F1曲线、精确率-召回率曲线这类可视化指标输出,但可通过扩展评估流程或结合第三方库实现,以下是具体方案:

1. 提取评估原始数据

首先从Detectron2的评估流程中获取预测结果与标注的原始数据,可基于COCOEvaluator或自定义评估器实现:

from detectron2.evaluation import COCOEvaluator, inference_on_dataset
from detectron2.data import build_detection_test_loader

# 初始化评估器与测试数据加载器
evaluator = COCOEvaluator("your_dataset", cfg, False, output_dir="./eval_results/")
test_loader = build_detection_test_loader(cfg, "your_dataset")

# 执行推理并保留原始结果
inference_results = inference_on_dataset(model, test_loader, evaluator)

# 可自定义Evalu子类,将所有预测的置信度、类别、bbox,以及对应标注的类别、bbox保存为可处理的列表

2. 生成精确率-召回率(PR)与F1曲线

利用scikit-learn计算指标,matplotlib绘图,需先按COCO的IOU匹配规则完成预测与标注的对应关联:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve

# 假设已完成预测-标注匹配,得到:
# scores: 所有有效预测的置信度数组
# matched_flags: 预测是否与标注匹配的布尔数组(1为正确检测,0为误检)

# 计算PR曲线数据
precision, recall, thresholds = precision_recall_curve(matched_flags, scores)
# 计算各阈值对应的F1值
f1_scores = 2 * (precision * recall) / (precision + recall + 1e-8)  # 避免除零

# 绘制PR曲线
plt.figure(figsize=(8, 6))
plt.plot(recall, precision, linewidth=2, label="PR Curve")
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.title("Precision-Recall Curve")
plt.legend()
plt.savefig("./pr_curve.png")

# 绘制F1-置信度阈值曲线
plt.figure(figsize=(8, 6))
plt.plot(thresholds, f1_scores[:-1], linewidth=2, label="F1 vs Confidence")
plt.xlabel("Confidence Threshold")
plt.ylabel("F1 Score")
plt.title("F1 Score vs Confidence Threshold")
plt.legend()
plt.savefig("./f1_curve.png")

3. 生成精确率-置信度曲线

基于上述计算的阈值与精确率数据直接绘图:

plt.figure(figsize=(8, 6))
plt.plot(thresholds, precision[:-1], linewidth=2, label="Precision vs Confidence")
plt.xlabel("Confidence Threshold")
plt.ylabel("Precision")
plt.title("Precision vs Confidence Threshold")
plt.legend()
plt.savefig("./precision_confidence_curve.png")

4. 生成混淆矩阵

需先过滤无效预测,保留匹配成功的预测与标注类别,再用scikit-learn和seaborn可视化:

from sklearn.metrics import confusion_matrix
import seaborn as sns

# 假设已获取匹配后的真实类别数组true_classes、预测类别数组pred_classes
# class_names为你的数据集类别名称列表
cm = confusion_matrix(true_classes, pred_classes)

plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=class_names, yticklabels=class_names)
plt.xlabel("Predicted Class")
plt.ylabel("True Class")
plt.title("Confusion Matrix")
plt.savefig("./confusion_matrix.png")

简化方案

可直接扩展Detectron2的Evaluator类,将上述指标计算与绘图逻辑集成到评估流程中,或参考官方仓库的自定义评估示例,复用COCO的匹配逻辑确保指标准确性。

内容的提问来源于stack exchange,提问作者raj-kapil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:53:20