Spaces:
Running on Zero

File size: 6,999 Bytes
755f67e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()