from __future__ import annotations import math import json import csv from pathlib import Path def roc_auc(scores: list[float], labels: list[int]) -> float: pairs = [(float(s), int(y)) for s, y in zip(scores, labels)] pos = [s for s, y in pairs if y == 1] neg = [s for s, y in pairs if y == 0] if not pos or not neg: return float("nan") wins = 0.0 for p in pos: wins += sum(1.0 for n in neg if p < n) wins += 0.5 * sum(1.0 for n in neg if p == n) return float(wins / (len(pos) * len(neg))) def enrichment_factor(scores: list[float], labels: list[int], fraction: float) -> float: pairs = [(float(s), int(y)) for s, y in zip(scores, labels)] n = len(pairs) total_actives = sum(y for _, y in pairs) if n == 0 or total_actives == 0: return float("nan") k = max(1, int(math.ceil(n * fraction))) top = sorted(pairs, key=lambda item: item[0])[:k] hit_rate_top = float(sum(y for _, y in top)) / float(k) hit_rate_all = float(total_actives) / float(n) return float(hit_rate_top / hit_rate_all) if hit_rate_all > 0 else float("nan") def bedroc(scores: list[float], labels: list[int], alpha: float = 20.0) -> float: pairs = sorted([(float(s), int(y)) for s, y in zip(scores, labels)], key=lambda item: item[0]) n = len(pairs) n_act = sum(y for _, y in pairs) if n == 0 or n_act == 0 or n_act == n: return float("nan") ranks = [idx + 1 for idx, (_, y) in enumerate(pairs) if y == 1] denom = (1 - math.exp(-alpha)) / (math.exp(alpha / n) - 1) rie = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in ranks) / denom rie_min = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(n - n_act + 1, n + 1)) / denom rie_max = (n / n_act) * sum(math.exp(-alpha * rank / n) for rank in range(1, n_act + 1)) / denom return float((rie - rie_min) / (rie_max - rie_min)) def enrichment_rows(scores: list[float], labels: list[int]) -> list[dict[str, float]]: rows = [] for frac in (0.01, 0.05, 0.10, 0.20): rows.append({"fraction": frac, "enrichment_factor": enrichment_factor(scores, labels, frac)}) return rows def validation_metrics_from_rows(rows: list[dict[str, object]], score_col: str = "SCORE", label_col: str = "label") -> dict[str, float]: scores = [float(row[score_col]) for row in rows] labels = [int(float(row.get(label_col, 0) or 0)) for row in rows] return { "roc_auc": roc_auc(scores, labels), "ef1": enrichment_factor(scores, labels, 0.01), "ef5": enrichment_factor(scores, labels, 0.05), "ef10": enrichment_factor(scores, labels, 0.10), "ef20": enrichment_factor(scores, labels, 0.20), "bedroc20": bedroc(scores, labels, alpha=20.0), } def write_metrics(rows: list[dict[str, object]], metrics_json: str | Path, enrichment_csv: str | Path) -> dict[str, float]: metrics = validation_metrics_from_rows(rows) Path(metrics_json).parent.mkdir(parents=True, exist_ok=True) Path(metrics_json).write_text(json.dumps(metrics, indent=2), encoding="utf-8") scores = [float(row["SCORE"]) for row in rows] labels = [int(float(row.get("label", 0) or 0)) for row in rows] with Path(enrichment_csv).open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["fraction", "enrichment_factor"]) writer.writeheader() writer.writerows(enrichment_rows(scores, labels)) return metrics validation_metrics_from_table = validation_metrics_from_rows enrichment_table = enrichment_rows