RipBench / tooling /eval /evaluate_detection.py
Irikos's picture
Add files using upload-large-folder tool
6c30276 verified
Raw History Blame Contribute Delete
13.5 kB
#!/usr/bin/env python3
"""RipBench detection / instance-segmentation evaluator (framework-agnostic).
HOW TO USE (no CLI args - edit CONFIG below, then: python evaluate_detection.py)
1. TASK="bbox" + MODE="bbox" for detection; TASK="instance_segmentation" +
MODE="segm" for masks; TASK="bbox_from_instance" + MODE="bbox" scores
against the polygon-derived boxes (for the trimmed-vs-derived ablation,
any detector's predictions can be evaluated against either bbox GT -
image ids are identical across the two passes).
2. Point PRED_DIR at a predictions/ folder of <stem>_preds_val.json /
<stem>_preds_test.json files (predict_ultralytics.py writes one next to
the checkpoints). Only stems containing the task
token (_det_ / _bfi_ / _seg_) are evaluated - a mixed folder is fine.
For a single model instead: PRED_DIR=None + PRED_VAL/PRED_TEST.
3. Run (env with numpy + pycocotools, e.g. conda yoloV26). One TSV row per
model x split appends to eval/results/<TASK>_eval.tsv (Sheets-ready).
PROTOCOL: the confidence threshold is selected PER MODEL on val (best
F2@IoU0.50; ties: higher R, P, threshold), frozen, then applied to test.
selected_conf / selected_on columns record it. For test-only evaluation set
USE_VAL_SELECTION=False and FIXED_CONF_THRESHOLD.
DEFINITIONS: AP50/AP75/AP50_95 via pycocotools (threshold-free). Counts via
COCO-style greedy matching: predictions in descending score order, each
matched to the highest-IoU still-UNMATCHED GT with IoU >= threshold (fixes
the argmax-then-veto bug of train/eval_scripts/, which counted a prediction
FP whenever its single best-overlap GT was taken). avg*_50_95 columns are
MEANS over IoU 0.50..0.95 - fractional, not counts; avgP is the mean of
per-threshold precisions. Predictions must be dumped at a low confidence
floor (predictor uses 0.001) so the sweep and AP see the full curve.
"""
import json
import os
_RIPBENCH_ROOT = os.environ.get("RIPBENCH_ROOT", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))) # release root (env RIPBENCH_ROOT overrides)
from datetime import datetime
import numpy as np
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
# --- CONFIG -------------------------------------------------------------------
DATASET_ROOT = _RIPBENCH_ROOT
TASK = "bbox" # "bbox" | "bbox_from_instance" | "instance_segmentation" (picks GT jsons + TSV name)
MODE = "bbox" # "bbox" | "segm" ("segm" needs segmentation fields in predictions)
# EITHER a folder of prediction files (batch mode) ...
PRED_DIR = _RIPBENCH_ROOT + "/models/bbox/best_models/predictions" # None -> use the single pair below
TASK_TOKEN = None # None = auto by TASK (_det_/_bfi_/_seg_); "" = take every pair in PRED_DIR
# ... OR a single pair:
PRED_VAL = "/path/to/<model>_preds_val.json" # ignored if USE_VAL_SELECTION = False
PRED_TEST = "/path/to/<model>_preds_test.json"
USE_VAL_SELECTION = True # True: select conf on val, apply to test (default protocol)
FIXED_CONF_THRESHOLD = 0.25 # used only when USE_VAL_SELECTION = False
CONF_SWEEP = [round(x / 100, 2) for x in range(1, 96)] # 0.01..0.95 step 0.01
# (dense + low start on purpose: yolo confidences can be very low, and the
# F2-optimal operating points have landed around 0.05-0.15)
IOU_THRESHOLDS = [round(x / 100, 2) for x in range(50, 96, 5)] # 0.50..0.95
MODEL_TAG = None # single-pair mode only; None = derived from PRED_TEST filename
OUT_TSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", f"{TASK}_eval.tsv")
SAVE_SWEEP = True # also writes the full val sweep next to each _preds_val.json
SWEEP_SUFFIX = "_sweep.tsv" # drivers scoring a dump against a non-native GT set their own suffix so the native sweep survives
# ------------------------------------------------------------------------------
GT_VAL = os.path.join(DATASET_ROOT, "labels", TASK, "coco", "val.json")
GT_TEST = os.path.join(DATASET_ROOT, "labels", TASK, "coco", "test.json")
HEADER = ("timestamp\tmodel\ttask\tmode\tsplit\tselected_conf\tselected_on"
"\tn_images\tn_gt\tAP50\tAP75\tAP50_95"
"\tP50\tR50\tF1_50\tF2_50\tTP50\tFP50\tFN50"
"\tavgP_50_95\tavgR_50_95\tavgF1_50_95\tavgF2_50_95"
"\tavgTP_50_95\tavgFP_50_95\tavgFN_50_95\n")
def f_beta(p, r, beta):
denom = beta * beta * p + r
return (1 + beta * beta) * p * r / denom if denom > 0 else 0.0
def greedy_match(ious, iou_thr):
"""COCO-style greedy one-to-one matching. Rows = predictions sorted by
descending score, columns = GT. Each prediction matches the highest-IoU
GT among those still unmatched and >= iou_thr."""
n_pred, n_gt = ious.shape
matched = np.zeros(n_gt, dtype=bool)
tp = fp = 0
for i in range(n_pred):
cand = np.where(~matched & (ious[i] >= iou_thr))[0]
if len(cand):
matched[cand[np.argmax(ious[i][cand])]] = True
tp += 1
else:
fp += 1
return tp, fp, int(n_gt - matched.sum())
def bbox_iou_matrix(pred_boxes, gt_boxes):
"""IoU matrix for xywh boxes: rows preds, cols GT."""
p = np.asarray(pred_boxes, dtype=np.float64)
g = np.asarray(gt_boxes, dtype=np.float64)
px1, py1, px2, py2 = p[:, 0], p[:, 1], p[:, 0] + p[:, 2], p[:, 1] + p[:, 3]
gx1, gy1, gx2, gy2 = g[:, 0], g[:, 1], g[:, 0] + g[:, 2], g[:, 1] + g[:, 3]
ix1 = np.maximum(px1[:, None], gx1[None, :])
iy1 = np.maximum(py1[:, None], gy1[None, :])
ix2 = np.minimum(px2[:, None], gx2[None, :])
iy2 = np.minimum(py2[:, None], gy2[None, :])
inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None)
union = (p[:, 2] * p[:, 3])[:, None] + (g[:, 2] * g[:, 3])[None, :] - inter
return np.where(union > 0, inter / union, 0.0)
def build_cache(gt_coco, pred_coco, mode):
"""Per image, per category: (pred scores desc, IoU matrix in that order,
n_gt). IoU matrices are computed ONCE; every (conf, iou_thr) evaluation
slices the top-k rows (scores sorted desc -> a conf threshold keeps a
prefix)."""
from pycocotools import mask as maskUtils
cache = []
for img_id in gt_coco.getImgIds():
gt_anns = gt_coco.loadAnns(gt_coco.getAnnIds(imgIds=img_id))
pred_anns = pred_coco.loadAnns(pred_coco.getAnnIds(imgIds=img_id)) if pred_coco else []
per_cat = {}
cats = {a["category_id"] for a in gt_anns} | {a["category_id"] for a in pred_anns}
for cat in cats:
g = [a for a in gt_anns if a["category_id"] == cat]
p = sorted((a for a in pred_anns if a["category_id"] == cat),
key=lambda a: -float(a.get("score", 0.0)))
scores = np.array([float(a.get("score", 0.0)) for a in p])
if not p or not g:
per_cat[cat] = (scores, np.zeros((len(p), len(g))), len(g))
continue
if mode == "bbox":
ious = bbox_iou_matrix([a["bbox"] for a in p], [a["bbox"] for a in g])
else:
g_rle = [gt_coco.annToRLE(a) for a in g]
p_rle = [pred_coco.annToRLE(a) for a in p]
iscrowd = [int(a.get("iscrowd", 0)) for a in g]
ious = np.atleast_2d(maskUtils.iou(p_rle, g_rle, iscrowd))
per_cat[cat] = (scores, ious, len(g))
cache.append(per_cat)
return cache
def metrics_at(cache, conf, iou_thr):
TP = FP = FN = 0
for per_cat in cache:
for scores, ious, n_gt in per_cat.values():
k = int((scores >= conf).sum()) # scores sorted desc -> prefix
tp, fp, fn = greedy_match(ious[:k], iou_thr) if k or n_gt else (0, 0, 0)
TP += tp
FP += fp
FN += fn
p = TP / (TP + FP) if TP + FP else 0.0
r = TP / (TP + FN) if TP + FN else 0.0
return {"TP": TP, "FP": FP, "FN": FN, "P": p, "R": r,
"F1": f_beta(p, r, 1.0), "F2": f_beta(p, r, 2.0)}
def evaluate_split(cache, conf):
"""@0.50 metrics + means over IOU_THRESHOLDS (the avg* columns)."""
at50 = metrics_at(cache, conf, 0.50)
per_iou = [metrics_at(cache, conf, t) for t in IOU_THRESHOLDS]
avg = {k: float(np.mean([m[k] for m in per_iou])) for k in per_iou[0]}
return at50, avg
def ap_metrics(gt_coco, preds_list, iou_type):
"""Threshold-free AP via pycocotools. stats: [0]=AP50-95 [1]=AP50 [2]=AP75."""
if not preds_list:
return {"AP50": 0.0, "AP75": 0.0, "AP50_95": 0.0}
pred_coco = gt_coco.loadRes(preds_list)
ev = COCOeval(gt_coco, pred_coco, iouType=iou_type)
ev.evaluate()
ev.accumulate()
ev.summarize()
return {"AP50": float(ev.stats[1]), "AP75": float(ev.stats[2]), "AP50_95": float(ev.stats[0])}
def append_row(row):
os.makedirs(os.path.dirname(OUT_TSV), exist_ok=True)
write_header = not os.path.isfile(OUT_TSV)
with open(OUT_TSV, "a") as f:
if write_header:
f.write(HEADER)
f.write("\t".join(str(x) for x in row) + "\n")
def make_row(model, split, selected_conf, selected_on, gt, at50, avg, ap):
n_gt = sum(len(gt.getAnnIds(imgIds=i)) for i in gt.getImgIds())
return [datetime.now().strftime("%Y-%m-%d %H:%M"), model, TASK, MODE, split,
f"{selected_conf:.2f}", selected_on, len(gt.getImgIds()), n_gt,
f"{ap['AP50']:.6f}", f"{ap['AP75']:.6f}", f"{ap['AP50_95']:.6f}",
f"{at50['P']:.6f}", f"{at50['R']:.6f}", f"{at50['F1']:.6f}", f"{at50['F2']:.6f}",
at50["TP"], at50["FP"], at50["FN"],
f"{avg['P']:.6f}", f"{avg['R']:.6f}", f"{avg['F1']:.6f}", f"{avg['F2']:.6f}",
f"{avg['TP']:.3f}", f"{avg['FP']:.3f}", f"{avg['FN']:.3f}"]
def evaluate_pair(gt_v, gt_t, pred_val, pred_test, model):
if USE_VAL_SELECTION:
print(f"[val] {model}")
with open(pred_val) as f:
preds_v = json.load(f)
pred_coco_v = gt_v.loadRes(preds_v) if preds_v else None
cache_v = build_cache(gt_v, pred_coco_v, MODE)
sweep = []
for conf in CONF_SWEEP:
at50, avg = evaluate_split(cache_v, conf)
sweep.append((conf, at50, avg))
best_conf, best_at50, best_avg = max(
sweep, key=lambda s: (s[1]["F2"], s[1]["R"], s[1]["P"], s[0]))
selected_on = "val"
print(f"[val] {model}: selected conf={best_conf:.2f} (F2@50={best_at50['F2']:.4f})")
if SAVE_SWEEP:
sweep_path = os.path.splitext(pred_val)[0] + SWEEP_SUFFIX
with open(sweep_path, "w") as f:
f.write("conf\tP50\tR50\tF1_50\tF2_50\tTP50\tFP50\tFN50\n")
for conf, a, _ in sweep:
f.write(f"{conf:.2f}\t{a['P']:.6f}\t{a['R']:.6f}\t{a['F1']:.6f}"
f"\t{a['F2']:.6f}\t{a['TP']}\t{a['FP']}\t{a['FN']}\n")
ap_v = ap_metrics(gt_v, preds_v, "bbox" if MODE == "bbox" else "segm")
append_row(make_row(model, "val", best_conf, selected_on, gt_v, best_at50, best_avg, ap_v))
else:
best_conf = FIXED_CONF_THRESHOLD
selected_on = "fixed"
print(f"[test-only] {model}: fixed conf={best_conf:.2f}")
with open(pred_test) as f:
preds_t = json.load(f)
pred_coco_t = gt_t.loadRes(preds_t) if preds_t else None
cache_t = build_cache(gt_t, pred_coco_t, MODE)
at50_t, avg_t = evaluate_split(cache_t, best_conf)
ap_t = ap_metrics(gt_t, preds_t, "bbox" if MODE == "bbox" else "segm")
append_row(make_row(model, "test", best_conf, selected_on, gt_t, at50_t, avg_t, ap_t))
print(f"[test] {model}: conf={best_conf:.2f} ({selected_on}) "
f"AP50={ap_t['AP50']:.4f} AP50_95={ap_t['AP50_95']:.4f} "
f"P={at50_t['P']:.4f} R={at50_t['R']:.4f} F2={at50_t['F2']:.4f} "
f"TP/FP/FN={at50_t['TP']}/{at50_t['FP']}/{at50_t['FN']}\n")
def discover_pairs(pred_dir):
token = TASK_TOKEN
if token is None:
token = {"bbox": "_det_", "bbox_from_instance": "_bfi_",
"instance_segmentation": "_seg_"}[TASK]
for f in sorted(os.listdir(pred_dir)):
if not f.endswith("_preds_test.json"):
continue
stem = f[: -len("_preds_test.json")]
if token and token not in stem:
continue
val = os.path.join(pred_dir, stem + "_preds_val.json")
yield stem, (val if os.path.isfile(val) else None), os.path.join(pred_dir, f)
def main():
print(f"GT: {GT_VAL}\n {GT_TEST}")
gt_v = COCO(GT_VAL) if USE_VAL_SELECTION else None
gt_t = COCO(GT_TEST)
if PRED_DIR:
pairs = list(discover_pairs(PRED_DIR))
print(f"batch mode: {len(pairs)} model(s) in {PRED_DIR}\n")
failed = []
for stem, pred_val, pred_test in pairs:
if USE_VAL_SELECTION and pred_val is None:
print(f"SKIP {stem}: no _preds_val.json (needed for threshold selection)")
continue
try:
evaluate_pair(gt_v, gt_t, pred_val, pred_test, stem)
except Exception as e: # keep the batch going
failed.append((stem, repr(e)))
print(f"ERROR {stem}: {e!r}")
print(f"done: {len(pairs) - len(failed)}/{len(pairs)} ok -> {OUT_TSV}")
for stem, err in failed:
print(f" FAILED {stem}: {err}")
else:
model = MODEL_TAG or os.path.splitext(os.path.basename(PRED_TEST))[0]
evaluate_pair(gt_v, gt_t, PRED_VAL, PRED_TEST, model)
print(f"rows appended to {OUT_TSV}")
if __name__ == "__main__":
main()