Spaces:
Running on Zero
Running on Zero
Download develop.py from wqerer/ctg-escalate: direct link, hf CLI and curl.
- Browser
- Download file 7 kB
-
https://huggingface.co/spaces/wqerer/ctg-escalate/resolve/main/develop.py
- Command line
-
hf download hf://spaces/wqerer/ctg-escalate/develop.py
-
curl -L -o develop.py https://huggingface.co/spaces/wqerer/ctg-escalate/resolve/main/develop.py
7 kB
| """Development: everything that involves a choice happens here, on the 70% development set ONLY. | |
| - repeated stratified 5-fold CV (5 repeats) for B0, B1, B2, full-feature LR and the CTG-Escalate ensemble | |
| - Platt calibration of the ensemble on out-of-fold scores | |
| - abstention (signal-loss) cut-off and operating threshold, chosen by pre-stated rules on out-of-fold dev data | |
| - final models fitted on all dev records; config.yaml frozen | |
| Usage: python develop.py | |
| """ | |
| from __future__ import annotations | |
| import datetime as dt | |
| import hashlib | |
| import json | |
| import pickle | |
| import numpy as np | |
| import pandas as pd | |
| import yaml | |
| from sklearn.model_selection import RepeatedStratifiedKFold | |
| from ctg.data import ROOT | |
| from ctg.features import FIGO_FEATURES, model_feature_names | |
| from ctg.metrics import auroc, auprc, confusion, sens_at_spec | |
| from ctg.models import Ensemble, _logit, fit_calibrator, make_gbm, make_lr | |
| SEED = 20261204 | |
| LABEL = "y_primary" | |
| LOSS_CANDIDATES = [0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60] | |
| MAX_ABSTAIN = 0.15 # pre-stated: the gate may set aside at most 15% of dev traces | |
| def load_dev(): | |
| df = pd.read_csv(ROOT / "data" / "features.csv", dtype={"record": str}).set_index("record") | |
| dev = (ROOT / "splits" / "dev_ids.txt").read_text().split() | |
| hold = set((ROOT / "splits" / "holdout_ids.txt").read_text().split()) | |
| assert not hold.intersection(dev), "dev/holdout overlap" | |
| return df.loc[dev] | |
| def main(): | |
| d = load_dev() | |
| y = d[LABEL].values | |
| feats = model_feature_names(d.columns.drop(["ph", "y_primary", "y_secondary", "caesarean"])) | |
| print(f"dev n={len(d)} positives={y.sum()} | {len(feats)} model features, {len(FIGO_FEATURES)} FIGO features") | |
| cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=SEED) | |
| names = ["B1_logreg_figo", "B2_gbm_full", "LR_full", "CTG_Escalate_raw"] | |
| oof = {k: np.zeros((5, len(d))) for k in names} | |
| per_repeat = {k: [] for k in names} | |
| for i, (tr, te) in enumerate(cv.split(d, y)): | |
| r = i // 5 | |
| Xtr, Xte, ytr = d.iloc[tr], d.iloc[te], y[tr] | |
| b1 = make_lr(C=1.0).fit(Xtr[FIGO_FEATURES], ytr) | |
| oof["B1_logreg_figo"][r, te] = b1.predict_proba(Xte[FIGO_FEATURES])[:, 1] | |
| ens = Ensemble(feats, seed=SEED + i).fit(Xtr, ytr) | |
| oof["B2_gbm_full"][r, te] = ens.gbm.predict_proba(Xte[feats])[:, 1] | |
| oof["LR_full"][r, te] = ens.lr.predict_proba(Xte[feats])[:, 1] | |
| oof["CTG_Escalate_raw"][r, te] = ens.raw_score(Xte) | |
| for k in names: | |
| per_repeat[k] = [auroc(y, oof[k][r]) for r in range(5)] | |
| oof_mean = {k: v.mean(axis=0) for k, v in oof.items()} | |
| cv_report = {"B0_figo_rule": {"auroc": auroc(y, d["figo_class"]), "auprc": auprc(y, d["figo_class"])}} | |
| for k in names: | |
| cv_report[k] = {"auroc_mean": float(np.mean(per_repeat[k])), "auroc_sd": float(np.std(per_repeat[k])), | |
| "auprc_mean": float(np.mean([auprc(y, oof[k][r]) for r in range(5)]))} | |
| print(json.dumps(cv_report, indent=1)) | |
| # Model selection (dev CV only): the LR+GBM mean was the first design; the rule is "highest mean | |
| # dev-CV AUROC among the two CTG-Escalate candidates". Logged in config.yaml. | |
| cand = {"mean": "CTG_Escalate_raw", "lr": "LR_full"} | |
| mode = max(cand, key=lambda m: cv_report[cand[m]]["auroc_mean"]) | |
| chosen = cand[mode] | |
| selection = {"candidates": {m: cv_report[k]["auroc_mean"] for m, k in cand.items()}, "chosen_mode": mode, | |
| "rule": "highest mean dev-CV AUROC (5x5 repeated stratified folds)"} | |
| print("model selection:", selection) | |
| # Calibration on out-of-fold raw scores | |
| calibrator = fit_calibrator(oof_mean[chosen], y) | |
| p_oof = calibrator.predict_proba(_logit(oof_mean[chosen])[:, None])[:, 1] | |
| # Abstention cut-off: among cut-offs that set aside <= 15% of dev traces, pick the one maximizing | |
| # out-of-fold AUROC on answered traces; ties within 0.005 go to the larger cut-off (abstain less). | |
| loss = d["fhr_loss"].values | |
| curve = [] | |
| for c in LOSS_CANDIDATES: | |
| ans = loss <= c | |
| curve.append({"cutoff": c, "abstain_rate": float(1 - ans.mean()), | |
| "auroc_answered": auroc(y[ans], p_oof[ans]), | |
| "auroc_abstained": auroc(y[~ans], p_oof[~ans]) if (~ans).sum() > 5 else None}) | |
| ok = [r for r in curve if r["abstain_rate"] <= MAX_ABSTAIN] | |
| best = max(r["auroc_answered"] for r in ok) | |
| cutoff = max(r["cutoff"] for r in ok if r["auroc_answered"] >= best - 0.005) | |
| print("abstention curve:", json.dumps(curve, indent=1)) | |
| print(f"chosen signal-loss cut-off: {cutoff}") | |
| # Operating threshold: match the FIGO rule's dev specificity on answered traces (same false-alarm burden), | |
| # so the comparison asks "at the same alert burden, who misses fewer acidemic births?" | |
| ans = loss <= cutoff | |
| b0_alert = d["figo_class"].values == 2 | |
| b0_spec = confusion(y[ans], b0_alert[ans])["specificity"] | |
| sens, thr = sens_at_spec(y[ans], p_oof[ans], b0_spec) | |
| dev_policy = confusion(y[ans], p_oof[ans] > thr) | |
| print(f"B0 dev specificity (answered) {b0_spec:.3f}; threshold {thr:.4f} -> dev OOF sensitivity {sens:.3f}") | |
| # Final models on all dev records | |
| final = Ensemble(feats, seed=SEED, mode=mode).fit(d, y) | |
| final.calibrator = calibrator | |
| b1 = make_lr(C=1.0).fit(d[FIGO_FEATURES], y) | |
| b2 = make_gbm(SEED).fit(d[feats], y) | |
| (ROOT / "models").mkdir(exist_ok=True) | |
| with open(ROOT / "models" / "models.pkl", "wb") as fh: | |
| pickle.dump({"ctg_escalate": final, "b1": b1, "b2": b2, "features": feats, | |
| "figo_features": FIGO_FEATURES}, fh) | |
| hold_sha = hashlib.sha256((ROOT / "splits" / "holdout_ids.txt").read_bytes()).hexdigest() | |
| model_sha = hashlib.sha256((ROOT / "models" / "models.pkl").read_bytes()).hexdigest() | |
| cfg = { | |
| "frozen_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), | |
| "seed": SEED, | |
| "label": "umbilical artery pH < 7.15 (primary); pH < 7.05 secondary", | |
| "window_minutes": 60, | |
| "holdout_ids_sha256": hold_sha, | |
| "models_sha256": model_sha, | |
| "abstain_if_fhr_loss_above": float(cutoff), | |
| "escalate_if_probability_above": float(thr), | |
| "threshold_rule": "match B0 (FIGO pathological) specificity on answered dev traces, out-of-fold", | |
| "model_selection": selection, | |
| "dev": {"n": int(len(d)), "positives": int(y.sum()), "cv": cv_report, | |
| "abstention_curve": curve, "b0_specificity_answered": b0_spec, | |
| "policy_at_threshold_oof": dev_policy}, | |
| } | |
| (ROOT / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False)) | |
| pd.DataFrame({"record": d.index, "y": y, "fhr_loss": loss, "figo_class": d["figo_class"].values, | |
| **{k: v for k, v in oof_mean.items()}, "p_calibrated": p_oof}).to_csv( | |
| ROOT / "results" / "dev_oof_predictions.csv", index=False) | |
| print("froze config.yaml and models/models.pkl") | |
| if __name__ == "__main__": | |
| main() | |