fairtalking-second-work / scripts /compute_extra_metrics.py
huahua123313's picture
Add files using upload-large-folder tool
a17b394 verified
Raw
History Blame Contribute Delete
7.38 kB
"""Post-hoc compute additional binary classification metrics from a
test_predictions CSV produced by BaseMethod._dump_test_predictions.
Metrics computed
----------------
acc : threshold-0.5 accuracy (recomputed from score, label).
auc : ROC-AUC.
ap : Average Precision (area under PR curve).
acc_at_eer : accuracy at the threshold where FPR == FNR (Equal Error Rate).
Found by scanning the ROC curve for the operating point that
minimizes |FPR - FNR|.
Output
------
Default: a single line of `key=value key=value ...` to stdout, easy to grep
from a shell script. Pass --json to emit a JSON object instead.
Returns code 0 on success even if the CSV has only a single class — in that
case AUC is reported as NaN. Returns rc=2 if the CSV is missing or empty.
Usage
-----
python3 scripts/compute_extra_metrics.py /path/to/test_predictions.csv
python3 scripts/compute_extra_metrics.py /path/to/test_predictions.csv --json
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import sys
from pathlib import Path
from typing import List, Tuple
def _numpy_roc_pr(scores: List[float], labels: List[int]):
"""Fallback ROC/PR computation using only the standard library + numpy.
Returns (auc, ap, fpr_list, tpr_list, thr_list) sorted by descending
threshold, mirroring sklearn.metrics.roc_curve's output ordering.
"""
# Pair-and-sort by descending score. Ties: count carefully via run-length.
order = sorted(range(len(scores)), key=lambda i: -scores[i])
s_sorted = [scores[i] for i in order]
y_sorted = [labels[i] for i in order]
P = sum(1 for y in labels if y == 1)
N = len(labels) - P
# Walk through unique thresholds in descending order, accumulating TP/FP.
fpr_list: List[float] = [0.0]
tpr_list: List[float] = [0.0]
thr_list: List[float] = [float("inf")]
tp = 0
fp = 0
i = 0
n = len(s_sorted)
# PR curve: precision @ each recall step (for AP via step-AUC, the
# "interpolated" form sklearn uses for average_precision_score).
prev_recall = 0.0
ap = 0.0
while i < n:
j = i
while j < n and s_sorted[j] == s_sorted[i]:
if y_sorted[j] == 1:
tp += 1
else:
fp += 1
j += 1
thr = float(s_sorted[i])
tpr = tp / P if P else 0.0
fpr = fp / N if N else 0.0
fpr_list.append(fpr)
tpr_list.append(tpr)
thr_list.append(thr)
# AP increment: precision * (recall - prev_recall)
precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
ap += precision * (tpr - prev_recall)
prev_recall = tpr
i = j
# AUC via trapezoidal integration over fpr (already sorted ascending in
# the appended list because thresholds are descending → fpr only grows).
auc = 0.0
for k in range(1, len(fpr_list)):
auc += (fpr_list[k] - fpr_list[k - 1]) * (tpr_list[k] + tpr_list[k - 1]) / 2.0
return auc, ap, fpr_list, tpr_list, thr_list
def load_scores_labels(csv_path: Path) -> Tuple[List[float], List[int]]:
scores: List[float] = []
labels: List[int] = []
with open(csv_path, "r", newline="") as f:
reader = csv.DictReader(f)
if reader.fieldnames is None or "score" not in reader.fieldnames or "label" not in reader.fieldnames:
raise ValueError(
f"CSV {csv_path} missing required columns 'score' and 'label'. "
f"Found: {reader.fieldnames}"
)
for row in reader:
try:
s = float(row["score"])
y = int(row["label"])
except (TypeError, ValueError):
continue
scores.append(s)
labels.append(y)
return scores, labels
def compute_metrics(scores: List[float], labels: List[int]) -> dict:
n = len(scores)
if n == 0:
return {"n": 0, "acc": float("nan"), "auc": float("nan"),
"ap": float("nan"), "acc_at_eer": float("nan"), "eer_threshold": float("nan")}
# threshold-0.5 accuracy
correct = sum(1 for s, y in zip(scores, labels) if int(s > 0.5) == int(y))
acc = correct / n
# Need both classes for AUC / AP / EER
pos = sum(1 for y in labels if y == 1)
neg = n - pos
if pos == 0 or neg == 0:
return {
"n": n, "n_pos": pos, "n_neg": neg,
"acc": acc,
"auc": float("nan"), "ap": float("nan"),
"acc_at_eer": float("nan"), "eer_threshold": float("nan"),
}
# Use sklearn for AUC / AP / ROC curve when available; fall back to a
# pure-numpy implementation otherwise. The project's requirements.txt
# pins scikit-learn>=1.3, so on a fully bootstrapped server sklearn
# is available and we follow the canonical implementation.
try:
from sklearn.metrics import roc_auc_score, average_precision_score, roc_curve
auc = float(roc_auc_score(labels, scores))
ap = float(average_precision_score(labels, scores))
fpr, tpr, thr = roc_curve(labels, scores)
fpr = list(map(float, fpr))
tpr = list(map(float, tpr))
thr = list(map(float, thr))
except ImportError:
auc, ap, fpr, tpr, thr = _numpy_roc_pr(scores, labels)
fnr = [1.0 - t for t in tpr]
diffs = [abs(a - b) for a, b in zip(fpr, fnr)]
idx = min(range(len(diffs)), key=lambda i: diffs[i])
eer_threshold = float(thr[idx])
# NB: sklearn occasionally inserts a sentinel threshold of +inf at idx 0.
if not math.isfinite(eer_threshold):
ranked = sorted(range(len(diffs)), key=lambda i: diffs[i])
for j in ranked:
if math.isfinite(float(thr[j])):
idx = j
eer_threshold = float(thr[j])
break
# acc at that threshold (predict positive iff score >= threshold)
correct_eer = sum(
1 for s, y in zip(scores, labels)
if int(float(s) >= eer_threshold) == int(y)
)
acc_at_eer = correct_eer / n
return {
"n": n,
"n_pos": pos,
"n_neg": neg,
"acc": acc,
"auc": auc,
"ap": ap,
"acc_at_eer": acc_at_eer,
"eer_threshold": eer_threshold,
}
def format_kv(metrics: dict) -> str:
parts = []
for k, v in metrics.items():
if isinstance(v, float):
parts.append(f"{k}={v:.6f}")
else:
parts.append(f"{k}={v}")
return " ".join(parts)
def main() -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("csv_path", help="Path to test_predictions CSV.")
p.add_argument("--json", action="store_true", help="Emit JSON instead of key=value.")
args = p.parse_args()
csv_path = Path(args.csv_path)
if not csv_path.exists():
print(f"[compute_extra_metrics] CSV not found: {csv_path}", file=sys.stderr)
return 2
scores, labels = load_scores_labels(csv_path)
if not scores:
print(f"[compute_extra_metrics] CSV is empty: {csv_path}", file=sys.stderr)
return 2
metrics = compute_metrics(scores, labels)
if args.json:
print(json.dumps(metrics))
else:
print(format_kv(metrics))
return 0
if __name__ == "__main__":
raise SystemExit(main())