Datasets:
File size: 8,245 Bytes
6c30276 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | #!/usr/bin/env python3
"""RipBench binary classification evaluator (framework-agnostic).
HOW TO USE (no CLI args - edit CONFIG below, then: python evaluate_classification.py)
1. Point PRED_DIR at a predictions/ folder (predict_ultralytics.py writes
one next to the checkpoints) of <stem>_preds_val.json / <stem>_preds_test.json
files (created by predict_ultralytics.py; each is a dict
{image basename: P(rip)}). Only stems containing _cls_ are evaluated -
a mixed folder is fine. Single model: PRED_DIR=None + PRED_VAL/PRED_TEST.
2. Run (numpy only). One TSV row per model x split appends to
eval/results/classification_eval.tsv (Sheets-ready).
PROTOCOL: the P(rip) decision threshold is selected PER MODEL on val (best
F2; rip = positive class - missing a rip is the costly error), frozen,
applied to test. Test-only: USE_VAL_SELECTION=False + FIXED_THRESHOLD.
AUROC and AP are threshold-free (computed from raw probabilities).
"""
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
# --- configuration -----------------------------------------------------------
DATASET_ROOT = _RIPBENCH_ROOT
# EITHER a folder of prediction files (batch mode) ...
PRED_DIR = "/path/to/best_models/predictions" # None -> use the single pair below
TASK_TOKEN = "_cls_" # stems must contain this; "" = 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
FIXED_THRESHOLD = 0.5 # used only when USE_VAL_SELECTION = False
THRESHOLD_SWEEP = [round(x / 100, 2) for x in range(1, 96)] # 0.01..0.95 step 0.01 (same grid as detection)
MODEL_TAG = None # None = derived from PRED_TEST filename
OUT_TSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", "classification_eval.tsv")
# ------------------------------------------------------------------------------
HEADER = ("timestamp\tmodel\ttask\tsplit\tselected_thr\tselected_on"
"\tn_images\tn_rip\tn_no_rip\tAUROC\tAP"
"\taccuracy\tP\tR\tF1\tF2\tspecificity\tTP\tFP\tFN\tTN\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 load_gt(split):
path = os.path.join(DATASET_ROOT, "labels", "classification", f"{split}.txt")
gt = {}
for line in open(path).read().splitlines():
if not line:
continue
image_rel, label = line.rsplit(" ", 1)
gt[os.path.basename(image_rel)] = int(label)
return gt
def load_preds(path, gt):
with open(path) as f:
preds = json.load(f)
assert isinstance(preds, dict), f"{path}: expected dict basename -> P(rip)"
missing = set(gt) - set(preds)
assert not missing, f"{path}: predictions missing for {len(missing)} GT images, e.g. {sorted(missing)[:3]}"
y = np.array([gt[k] for k in sorted(gt)], dtype=int)
s = np.array([float(preds[k]) for k in sorted(gt)], dtype=float)
return y, s
def counts_at(y, s, thr):
pred = s >= thr
tp = int(((pred == 1) & (y == 1)).sum())
fp = int(((pred == 1) & (y == 0)).sum())
fn = int(((pred == 0) & (y == 1)).sum())
tn = int(((pred == 0) & (y == 0)).sum())
return tp, fp, fn, tn
def metrics_at(y, s, thr):
tp, fp, fn, tn = counts_at(y, s, thr)
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, "TN": tn, "P": p, "R": r,
"F1": f_beta(p, r, 1.0), "F2": f_beta(p, r, 2.0),
"acc": (tp + tn) / len(y), "spec": tn / (tn + fp) if tn + fp else 0.0}
def auroc(y, s):
"""Rank-based AUROC (equals Mann-Whitney U / (n_pos * n_neg)); ties get
average ranks."""
n_pos, n_neg = int((y == 1).sum()), int((y == 0).sum())
if n_pos == 0 or n_neg == 0:
return float("nan")
order = np.argsort(s, kind="mergesort")
ranks = np.empty(len(s), dtype=float)
sorted_s = s[order]
i = 0
while i < len(s):
j = i
while j + 1 < len(s) and sorted_s[j + 1] == sorted_s[i]:
j += 1
ranks[order[i:j + 1]] = (i + j) / 2 + 1 # average rank, 1-based
i = j + 1
return float((ranks[y == 1].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg))
def average_precision(y, s):
"""Step-wise area under the precision-recall curve."""
order = np.argsort(-s, kind="mergesort")
y_sorted = y[order]
tp_cum = np.cumsum(y_sorted)
n_pos = int((y == 1).sum())
if n_pos == 0:
return float("nan")
precision = tp_cum / np.arange(1, len(y) + 1)
recall = tp_cum / n_pos
# sum precision at each new TP (step integration)
return float(precision[y_sorted == 1].sum() / n_pos)
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, thr, selected_on, y, s):
m = metrics_at(y, s, thr)
return [datetime.now().strftime("%Y-%m-%d %H:%M"), model, "classification", split,
f"{thr:.2f}", selected_on, len(y), int((y == 1).sum()), int((y == 0).sum()),
f"{auroc(y, s):.6f}", f"{average_precision(y, s):.6f}",
f"{m['acc']:.6f}", f"{m['P']:.6f}", f"{m['R']:.6f}",
f"{m['F1']:.6f}", f"{m['F2']:.6f}", f"{m['spec']:.6f}",
m["TP"], m["FP"], m["FN"], m["TN"]]
def evaluate_pair(gt_val, gt_test, pred_val, pred_test, model):
if USE_VAL_SELECTION:
y_v, s_v = load_preds(pred_val, gt_val)
sweep = [(t, metrics_at(y_v, s_v, t)) for t in THRESHOLD_SWEEP]
best_thr, _ = max(sweep, key=lambda x: (x[1]["F2"], x[1]["R"], x[1]["P"], x[0]))
selected_on = "val"
print(f"[val] {model}: selected threshold={best_thr:.2f}")
append_row(make_row(model, "val", best_thr, selected_on, y_v, s_v))
else:
best_thr = FIXED_THRESHOLD
selected_on = "fixed"
y_t, s_t = load_preds(pred_test, gt_test)
append_row(make_row(model, "test", best_thr, selected_on, y_t, s_t))
m = metrics_at(y_t, s_t, best_thr)
print(f"[test] {model}: thr={best_thr:.2f} ({selected_on}) acc={m['acc']:.4f} "
f"P={m['P']:.4f} R={m['R']:.4f} F2={m['F2']:.4f} "
f"TP/FP/FN/TN={m['TP']}/{m['FP']}/{m['FN']}/{m['TN']} "
f"AUROC={auroc(y_t, s_t):.4f}\n")
def discover_pairs(pred_dir):
for f in sorted(os.listdir(pred_dir)):
if not f.endswith("_preds_test.json"):
continue
stem = f[: -len("_preds_test.json")]
if TASK_TOKEN and TASK_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():
gt_val = load_gt("val") if USE_VAL_SELECTION else None
gt_test = load_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_val, gt_test, 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_val, gt_test, PRED_VAL, PRED_TEST, model)
print(f"rows appended to {OUT_TSV}")
if __name__ == "__main__":
main()
|