Spaces:
Running on Zero
Running on Zero
Download evaluate.py from wqerer/ctg-escalate: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/wqerer/ctg-escalate/resolve/main/evaluate.py
- Command line
-
hf download hf://spaces/wqerer/ctg-escalate/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/wqerer/ctg-escalate/resolve/main/evaluate.py
10.5 kB
| """Score the frozen CTG-Escalate system and baselines on a split. | |
| python evaluate.py --split holdout --seed 20261204 # the single locked held-out run | |
| python evaluate.py --split dev # in-sample smoke test of the code path | |
| The holdout run checks that splits/holdout_ids.txt and models/models.pkl match the hashes frozen in | |
| config.yaml, and every holdout run is appended to results/holdout_runs.log. A second holdout run is refused | |
| unless --rerun-reason is given; that reason is logged and must be reported. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import datetime as dt | |
| import hashlib | |
| import json | |
| import pickle | |
| import sys | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| import pandas as pd # noqa: E402 | |
| import yaml # noqa: E402 | |
| from sklearn.metrics import roc_curve # noqa: E402 | |
| from ctg.data import ROOT # noqa: E402 | |
| from ctg.metrics import (auprc, auroc, bootstrap_ci, confusion, ece, # noqa: E402 | |
| paired_auroc_diff, sens_at_spec) | |
| LOG = ROOT / "results" / "holdout_runs.log" | |
| def sha(p): | |
| return hashlib.sha256(p.read_bytes()).hexdigest() | |
| def per100(k, n): | |
| return round(100 * k / n, 1) | |
| def decide(p, loss, cfg): | |
| return np.where(loss > cfg["abstain_if_fhr_loss_above"], "abstain", | |
| np.where(p > cfg["escalate_if_probability_above"], "escalate", "continue")) | |
| def evaluate(split: str, seed: int, rerun_reason: str | None): | |
| cfg = yaml.safe_load((ROOT / "config.yaml").read_text()) | |
| if split == "holdout": | |
| assert sha(ROOT / "splits" / "holdout_ids.txt") == cfg["holdout_ids_sha256"], "holdout list changed!" | |
| assert sha(ROOT / "models" / "models.pkl") == cfg["models_sha256"], "models changed since freeze!" | |
| prior = LOG.read_text().strip().splitlines() if LOG.exists() else [] | |
| if prior and not rerun_reason: | |
| sys.exit(f"Holdout already scored {len(prior)} time(s); see {LOG}. " | |
| "Pass --rerun-reason to re-run (it will be logged and must be reported).") | |
| ids = (ROOT / "splits" / f"{split}_ids.txt").read_text().split() | |
| df = pd.read_csv(ROOT / "data" / "features.csv", dtype={"record": str}).set_index("record").loc[ids] | |
| with open(ROOT / "models" / "models.pkl", "rb") as fh: | |
| M = pickle.load(fh) | |
| y = df["y_primary"].values | |
| y2 = df["y_secondary"].values | |
| loss = df["fhr_loss"].values | |
| s = { | |
| "B0_figo_rule": df["figo_class"].values.astype(float), | |
| "B1_logreg_figo": M["b1"].predict_proba(df[M["figo_features"]])[:, 1], | |
| "B2_gbm_full": M["b2"].predict_proba(df[M["features"]])[:, 1], | |
| "CTG_Escalate": M["ctg_escalate"].predict_proba(df), | |
| } | |
| p = s["CTG_Escalate"] | |
| decision = decide(p, loss, cfg) | |
| ans = decision != "abstain" | |
| n = len(df) | |
| R = {"split": split, "n": n, "positives_pH_lt_7.15": int(y.sum()), "positives_pH_lt_7.05": int(y2.sum()), | |
| "caesarean": int(df["caesarean"].sum()), "config_frozen_at": cfg["frozen_at"], | |
| "chosen_model": cfg["model_selection"]["chosen_mode"]} | |
| # Discrimination | |
| R["discrimination_all"] = {k: {"auroc": bootstrap_ci(y, v, auroc, seed=seed), | |
| "auprc": bootstrap_ci(y, v, auprc, seed=seed)} for k, v in s.items()} | |
| R["discrimination_answered"] = {k: {"auroc": bootstrap_ci(y[ans], v[ans], auroc, seed=seed)} | |
| for k, v in s.items()} | |
| R["paired_auroc_difference_all"] = { | |
| f"CTG_Escalate_minus_{b}": paired_auroc_diff(y, p, s[b], seed=seed) | |
| for b in ["B0_figo_rule", "B1_logreg_figo", "B2_gbm_full"]} | |
| # Policy in clinical units (per 100 labours, all n records in the split) | |
| esc, abst, cont = decision == "escalate", decision == "abstain", decision == "continue" | |
| c_ans = confusion(y[ans], esc[ans]) | |
| R["ctg_escalate_policy"] = { | |
| "threshold": cfg["escalate_if_probability_above"], | |
| "abstain_if_fhr_loss_above": cfg["abstain_if_fhr_loss_above"], | |
| "escalate_per_100": per100(esc.sum(), n), | |
| "check_transducer_per_100": per100(abst.sum(), n), | |
| "continue_per_100": per100(cont.sum(), n), | |
| "missed_acidemic_per_100": per100((cont & (y == 1)).sum(), n), | |
| "acidemic_routed_to_check_transducer_per_100": per100((abst & (y == 1)).sum(), n), | |
| "missed_acidemic": f"{int((cont & (y == 1)).sum())} of {int(y.sum())}", | |
| "answered_confusion": c_ans, | |
| } | |
| b0_alert = s["B0_figo_rule"] == 2 | |
| R["b0_policy_all"] = {"escalate_per_100": per100(b0_alert.sum(), n), | |
| "missed_acidemic_per_100": per100((~b0_alert & (y == 1)).sum(), n), | |
| "missed_acidemic": f"{int((~b0_alert & (y == 1)).sum())} of {int(y.sum())}", | |
| "confusion": confusion(y, b0_alert)} | |
| R["b0_policy_answered"] = confusion(y[ans], b0_alert[ans]) | |
| b0_spec = R["b0_policy_answered"]["specificity"] | |
| R["sensitivity_at_b0_specificity_answered"] = { | |
| "b0_specificity": b0_spec, "b0_sensitivity": R["b0_policy_answered"]["sensitivity"], | |
| **{k: sens_at_spec(y[ans], s[k][ans], b0_spec)[0] for k in ["CTG_Escalate", "B1_logreg_figo", "B2_gbm_full"]}} | |
| # Secondary label (same scores, no retraining) | |
| R["secondary_pH_lt_7.05"] = { | |
| "auroc": {k: bootstrap_ci(y2, v, auroc, seed=seed) for k, v in s.items()}, | |
| "ctg_escalate_missed": f"{int((cont & (y2 == 1)).sum())} of {int(y2.sum())}", | |
| "ctg_escalate_check_transducer": int((abst & (y2 == 1)).sum()), | |
| "b0_missed": f"{int((~b0_alert & (y2 == 1)).sum())} of {int(y2.sum())}", | |
| } | |
| # Calibration | |
| R["calibration"] = {"ece_10bin": ece(y, p), "mean_predicted": float(p.mean()), "observed_rate": float(y.mean())} | |
| # Abstained subset and subgroups | |
| R["abstained"] = {"n": int(abst.sum()), "positives": int(y[abst].sum()), | |
| "ctg_escalate_auroc_if_scored": auroc(y[abst], p[abst]), | |
| "would_have_escalated": int((p[abst] > cfg["escalate_if_probability_above"]).sum())} | |
| R["subgroups"] = {} | |
| for name, m in [("vaginal", df["caesarean"].values == 0), ("caesarean", df["caesarean"].values == 1)]: | |
| R["subgroups"][name] = {"n": int(m.sum()), "positives": int(y[m].sum()), | |
| "auroc_ctg_escalate": auroc(y[m], p[m]), "auroc_b0": auroc(y[m], s["B0_figo_rule"][m]), | |
| "missed": int((cont & m & (y == 1)).sum()), | |
| "escalate_per_100": per100((esc & m).sum(), m.sum())} | |
| out = ROOT / "results" / split | |
| out.mkdir(parents=True, exist_ok=True) | |
| (out / "results.json").write_text(json.dumps(R, indent=2)) | |
| pd.DataFrame({"record": df.index, "ph": df["ph"].values, "y": y, "fhr_loss": loss, "decision": decision, | |
| "p_ctg_escalate": p, "figo_class": s["B0_figo_rule"].astype(int), | |
| "p_b1": s["B1_logreg_figo"], "p_b2": s["B2_gbm_full"]}).to_csv(out / "predictions.csv", index=False) | |
| _figures(out, y, s, ans, cfg, R) | |
| if split == "holdout": | |
| with open(LOG, "a") as fh: | |
| fh.write(json.dumps({"utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), | |
| "seed": seed, "rerun_reason": rerun_reason, | |
| "holdout_sha256": cfg["holdout_ids_sha256"], "models_sha256": cfg["models_sha256"], | |
| "auroc_ctg_escalate": R["discrimination_all"]["CTG_Escalate"]["auroc"]["point"]}) + "\n") | |
| return R | |
| def _figures(out, y, s, ans, cfg, R): | |
| fig, ax = plt.subplots(1, 2, figsize=(11, 4.6)) | |
| colors = {"CTG_Escalate": "#1f3b73", "B1_logreg_figo": "#e08a00", "B2_gbm_full": "#6a1b9a", | |
| "B0_figo_rule": "#c62828"} | |
| for k, v in s.items(): | |
| a = R["discrimination_all"][k]["auroc"] | |
| fpr, tpr, _ = roc_curve(y, v) | |
| ax[0].plot(fpr, tpr, color=colors[k], lw=2 if k == "CTG_Escalate" else 1.2, | |
| ls="--" if k == "B0_figo_rule" else "-", | |
| label=f"{k} {a['point']:.3f} ({a['lo']:.2f}-{a['hi']:.2f})") | |
| b0 = R["b0_policy_all"]["confusion"] | |
| ax[0].plot(1 - b0["specificity"], b0["sensitivity"], "o", color=colors["B0_figo_rule"], label="FIGO pathological") | |
| pol = R["ctg_escalate_policy"]["answered_confusion"] | |
| ax[0].plot(1 - pol["specificity"], pol["sensitivity"], "s", color=colors["CTG_Escalate"], | |
| label="CTG-Escalate threshold (answered)") | |
| ax[0].plot([0, 1], [0, 1], color="#999", lw=0.8) | |
| ax[0].set(xlabel="1 - specificity", ylabel="sensitivity", title=f"ROC, pH < 7.15 ({R['split']}, n={R['n']})") | |
| ax[0].legend(fontsize=7, loc="lower right") | |
| p = s["CTG_Escalate"] | |
| q = np.quantile(p, np.linspace(0, 1, 6)) | |
| idx = np.clip(np.searchsorted(q, p, side="right") - 1, 0, 4) | |
| mp = [p[idx == b].mean() for b in range(5)] | |
| ob = [y[idx == b].mean() for b in range(5)] | |
| ax[1].plot([0, 1], [0, 1], color="#999", lw=0.8) | |
| ax[1].plot(mp, ob, "o-", color=colors["CTG_Escalate"]) | |
| ax[1].set(xlabel="predicted probability (quintiles)", ylabel="observed acidemia rate", | |
| title=f"Calibration (ECE {R['calibration']['ece_10bin']:.3f})", xlim=(0, 0.8), ylim=(0, 0.8)) | |
| fig.tight_layout() | |
| fig.savefig(out / "roc_calibration.png", dpi=130) | |
| plt.close(fig) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--split", choices=["holdout", "dev"], required=True) | |
| ap.add_argument("--seed", type=int, default=20261204) | |
| ap.add_argument("--rerun-reason", default=None) | |
| a = ap.parse_args() | |
| R = evaluate(a.split, a.seed, a.rerun_reason) | |
| da = R["discrimination_all"] | |
| print(f"[{a.split}] n={R['n']} positives={R['positives_pH_lt_7.15']}") | |
| for k, v in da.items(): | |
| x = v["auroc"] | |
| print(f" {k:16s} AUROC {x['point']:.3f} ({x['lo']:.3f}-{x['hi']:.3f}) AUPRC {v['auprc']['point']:.3f}") | |
| pol = R["ctg_escalate_policy"] | |
| print(f" CTG-Escalate: escalate {pol['escalate_per_100']}/100, check transducer {pol['check_transducer_per_100']}/100," | |
| f" missed acidemic {pol['missed_acidemic_per_100']}/100 ({pol['missed_acidemic']})") | |
| b0 = R["b0_policy_all"] | |
| print(f" FIGO rule: escalate {b0['escalate_per_100']}/100, missed acidemic {b0['missed_acidemic_per_100']}/100" | |
| f" ({b0['missed_acidemic']})") | |
| print(f" results -> results/{a.split}/results.json") | |
| if __name__ == "__main__": | |
| main() | |