如何获取自定义TensorFlow模型每个类别的平均精度与召回率
TensorFlow 2.5 下获取SSD MobileNet自定义模型单类别平均精度的实现方法
方法一:使用官方Object Detection API评估脚本(无需额外编码,推荐)
该方法适配TensorFlow 2.x官方目标检测API的原生能力,只需修改配置即可输出单类别AP:
- 打开训练使用的
pipeline.config文件,定位到eval_config配置块 - 新增或修改配置如下:
eval_config { metrics_set: "coco_detection_metrics" include_metrics_per_category: true # 如需同时输出单类别召回率等其他指标,可额外加下面一行 all_metrics_per_category: true # 其余原有配置保持不变 } - 核心配置项
include_metrics_per_category需要设置为true才能开启单类别指标输出 - 运行官方评估脚本
model_main_tf2.py,指定对应配置文件、模型 checkpoint 路径和验证集路径,运行完成后终端会直接打印所有类别的AP值,结果也会同步写入评估日志的tfevent文件中
方法二:手动编码提取单类别AP(适配自定义训练流程场景)
如果你的训练逻辑没有使用官方API的评估流程,可以直接调用API内置的COCO评估器实现单类别AP计算,示例代码如下:
from object_detection.metrics import coco_evaluation from object_detection.core import standard_fields import tensorflow as tf # 替换为你自己的类别列表,顺序和标签映射保持一致 CLASS_NAMES = ["cat", "dog", "car"] # 初始化COCO评估器 evaluator = coco_evaluation.CocoDetectionEvaluator(category_names=CLASS_NAMES) # 遍历验证集所有样本,分别添加标注和预测结果 for sample in val_dataset: # 组装标注数据,坐标格式为[y_min, x_min, y_max, x_max],和预测结果保持单位统一即可 gt_dict = { standard_fields.InputDataFields.groundtruth_boxes: sample["gt_boxes"], standard_fields.InputDataFields.groundtruth_classes: sample["gt_class_ids"], # 类别id从1开始计数 standard_fields.InputDataFields.groundtruth_is_crowd: tf.zeros_like(sample["gt_class_ids"], dtype=tf.bool) } # 组装预测数据 pred_dict = { standard_fields.DetectionResultFields.detection_boxes: sample["pred_boxes"], standard_fields.DetectionResultFields.detection_classes: sample["pred_class_ids"], standard_fields.DetectionResultFields.detection_scores: sample["pred_scores"] } # 写入评估器 evaluator.add_single_ground_truth_image_info(image_id=sample["img_id"], groundtruth_dict=gt_dict) evaluator.add_single_detected_image_info(image_id=sample["img_id"], detections_dict=pred_dict) # 计算所有指标 metrics = evaluator.evaluate() # 提取并打印每个类别的AP for cls_name in CLASS_NAMES: ap_key = f"DetectionBoxes_Precision/mAP/{cls_name}" print(f"类别 {cls_name} 的AP值为:{metrics[ap_key]:.4f}")
注意事项
- 请确保你使用的Object Detection API版本和TensorFlow 2.5匹配,建议拉取API的r2.5.0分支使用,避免接口不兼容
- 标注和预测的坐标格式、类别id映射必须完全一致,否则会出现AP计算异常的问题
内容的提问来源于stack exchange,提问作者skywalker
相关产品推荐
相关产品推荐

