File size: 7,377 Bytes
a17b394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
206
207
208
209
210
211
212
213
214
215
216
217
"""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())