300 lines
12 KiB
Python
300 lines
12 KiB
Python
"""Per horizon, two models of recurrence by then: a logistic regression (LR) on the dummies a
|
|
stepwise selection keeps, and a Bayesian network (HBN) whose outcome's parents a greedy BDeu
|
|
search picks, predicting by its conditional probability table. Each is validated on a
|
|
stratified 70/30 split of the horizon's cohort (AUC) and on bootstrap resamples of it (each
|
|
replicate its own 70/30 split); a penalized Cox model's C-index rates the whole follow-up.
|
|
|
|
Resamples are drawn in order from one seeded generator and fitted in parallel, so every
|
|
replicate is the same however many workers run them."""
|
|
|
|
import warnings
|
|
from dataclasses import dataclass, field
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import statsmodels.api as sm
|
|
from joblib import Parallel, delayed
|
|
from lifelines import CoxPHFitter
|
|
from lifelines.utils import concordance_index
|
|
from pgmpy.structure_score import BDeu
|
|
from sklearn.metrics import roc_auc_score
|
|
from sklearn.model_selection import train_test_split
|
|
|
|
from models.cama.recurrence.cohorts import Cohort, at_horizon
|
|
|
|
HORIZONS = (12, 36, 60) # months
|
|
SEED = 42
|
|
TEST_SIZE = 0.3
|
|
ESS = 10 # BDeu's equivalent sample size, also the CPT's pseudo-count
|
|
MAX_PARENTS = 6
|
|
ALPHA_PREFILTER, ALPHA_IN, ALPHA_OUT = 0.10, 0.10, 0.15
|
|
MAX_STEPS = 200
|
|
COX_PENALIZER = 0.05
|
|
COX_MIN_COUNT = 10 # a Cox dummy needs this many patients on each side
|
|
N_BOOTSTRAP = {"metabric": 100, "scanb": 40}
|
|
|
|
|
|
# ---------------------------------------------------------------- logistic regression
|
|
|
|
|
|
def encode(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
|
|
"""Dummies (each covariate's alphabetically first level is the reference), the
|
|
non-constant ones; a term is `{covariate}_{level}`."""
|
|
X = pd.get_dummies(frame[covariates], drop_first=True).astype(float)
|
|
return X.loc[:, X.nunique() > 1]
|
|
|
|
|
|
def logit(y, X: pd.DataFrame, has_constant: str = "skip"):
|
|
"""Maximum-likelihood logistic regression with an intercept, or None when it fails."""
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("ignore")
|
|
X = sm.add_constant(X, has_constant=has_constant)
|
|
return sm.Logit(y, X).fit(disp=0, method="bfgs", maxiter=300)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def stepwise(X: pd.DataFrame, y) -> list[str]:
|
|
"""Forward (the smallest Wald p < ALPHA_IN enters) then backward (the largest p >
|
|
ALPHA_OUT leaves) until nothing changes; the terms in the order they entered."""
|
|
included = []
|
|
for _ in range(MAX_STEPS):
|
|
changed, best, best_p = False, None, ALPHA_IN
|
|
for c in X.columns:
|
|
if c in included:
|
|
continue
|
|
m = logit(y, X[included + [c]])
|
|
if m is not None and m.pvalues[c] < best_p:
|
|
best, best_p = c, m.pvalues[c]
|
|
if best is not None:
|
|
included.append(best)
|
|
changed = True
|
|
if included and (m := logit(y, X[included])) is not None:
|
|
p = m.pvalues.drop("const")
|
|
if p.max() > ALPHA_OUT:
|
|
included.remove(p.idxmax())
|
|
changed = True
|
|
if not changed:
|
|
break
|
|
return included
|
|
|
|
|
|
def lr(train: pd.DataFrame, test: pd.DataFrame, covariates: list[str]):
|
|
"""The terms selected on `train` (univariate prefilter, then stepwise) and the test
|
|
rows' predicted probabilities (the training rate when no term is selected)."""
|
|
X = encode(pd.concat([train, test]), covariates)
|
|
X_train = X.loc[train.index]
|
|
X_train = X_train.loc[:, X_train.nunique() > 1]
|
|
y = train["y"]
|
|
candidates = [
|
|
c
|
|
for c in X_train.columns
|
|
if (m := logit(y, X_train[[c]])) is not None and m.pvalues[c] < ALPHA_PREFILTER
|
|
]
|
|
terms = stepwise(X_train[candidates], y) if candidates else []
|
|
if not terms:
|
|
return [], np.full(len(test), y.mean())
|
|
m = logit(y, X_train[terms])
|
|
X_test = sm.add_constant(X.loc[test.index, terms], has_constant="add")
|
|
return terms, m.predict(X_test).to_numpy()
|
|
|
|
|
|
# ---------------------------------------------------------------- Bayesian network
|
|
|
|
|
|
def bn_table(frame: pd.DataFrame, covariates: list[str]) -> pd.DataFrame:
|
|
table = frame[covariates].astype(str)
|
|
table["outcome"] = frame["y"].astype(int).astype(str)
|
|
return table
|
|
|
|
|
|
def parents(table: pd.DataFrame, covariates: list[str]) -> list[str]:
|
|
"""Greedy: the covariate whose addition most raises the outcome's BDeu score, while
|
|
any does (up to MAX_PARENTS); the parents in the order chosen."""
|
|
score = BDeu(table, equivalent_sample_size=ESS)
|
|
chosen, current = [], score.local_score("outcome", ())
|
|
while len(chosen) < MAX_PARENTS:
|
|
best, gain = None, 0.0
|
|
for c in [c for c in covariates if c not in chosen]:
|
|
g = score.local_score("outcome", (*chosen, c)) - current
|
|
if g > gain:
|
|
best, gain = c, g
|
|
if best is None:
|
|
break
|
|
chosen.append(best)
|
|
current += gain
|
|
return chosen
|
|
|
|
|
|
def cpt(table: pd.DataFrame, chosen: list[str], q: int | None = None) -> dict[tuple, float]:
|
|
"""P(recurrence | parents) for each configuration seen, smoothed by ESS / (2 q) per cell;
|
|
`q`, the number of configurations, defaults to the levels seen in `table`."""
|
|
q = q or int(np.prod([table[p].nunique() for p in chosen]))
|
|
a = ESS / (2 * q)
|
|
counts = table.groupby(chosen)["outcome"].agg(n1=lambda s: (s == "1").sum(), n="size")
|
|
return {
|
|
(k if isinstance(k, tuple) else (k,)): float((r.n1 + a) / (r.n + 2 * a))
|
|
for k, r in counts.iterrows()
|
|
}
|
|
|
|
|
|
def hbn(train: pd.DataFrame, test: pd.DataFrame, chosen: list[str]) -> np.ndarray:
|
|
"""The test rows' probabilities by the CPT of `train`; unseen configurations (or no
|
|
parents) get the training rate."""
|
|
rate = (train["outcome"] == "1").mean()
|
|
if not chosen:
|
|
return np.full(len(test), rate)
|
|
table = cpt(train, chosen)
|
|
return np.array([table.get(k, rate) for k in map(tuple, test[chosen].to_numpy())])
|
|
|
|
|
|
# ---------------------------------------------------------------- one split, one cohort
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Split:
|
|
"""The two models' selection and AUC on one 70/30 split."""
|
|
|
|
terms: list[str]
|
|
parents: list[str]
|
|
auc_lr: float
|
|
auc_hbn: float
|
|
|
|
|
|
def split_fit(frame: pd.DataFrame, covariates: list[str], seed: int = SEED) -> Split:
|
|
train, test = train_test_split(
|
|
frame, test_size=TEST_SIZE, random_state=seed, stratify=frame["y"]
|
|
)
|
|
terms, p_lr = lr(train, test, covariates)
|
|
bn_train, bn_test = bn_table(train, covariates), bn_table(test, covariates)
|
|
chosen = parents(bn_train, covariates)
|
|
p_hbn = hbn(bn_train, bn_test, chosen)
|
|
return Split(terms, chosen, roc_auc_score(test["y"], p_lr), roc_auc_score(test["y"], p_hbn))
|
|
|
|
|
|
def _replicate(frame, covariates, rows, b) -> Split | None:
|
|
"""Bootstrap replicate `b`: the split (seed SEED + b) of the resample `rows`; None when
|
|
any fit fails (the replicate is then not counted)."""
|
|
try:
|
|
return split_fit(frame.iloc[rows].reset_index(drop=True), covariates, SEED + b)
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def c_index(cohort: Cohort) -> float:
|
|
"""Harrell's C of a ridge-penalized Cox model on the whole follow-up, by a 70/30 split
|
|
stratified by event; dummies with fewer than COX_MIN_COUNT patients on a side are left out."""
|
|
time_event = ["tiempo_meses", "evento"]
|
|
X = pd.get_dummies(
|
|
cohort.frame[time_event + cohort.covariates], columns=cohort.covariates, drop_first=True
|
|
).astype(float)
|
|
X = X.loc[:, X.nunique() > 1]
|
|
train, test = train_test_split(X, test_size=TEST_SIZE, random_state=SEED, stratify=X["evento"])
|
|
n = len(train)
|
|
keep = [
|
|
c
|
|
for c in X.columns
|
|
if c in time_event or COX_MIN_COUNT <= train[c].sum() <= n - COX_MIN_COUNT
|
|
]
|
|
cox = CoxPHFitter(penalizer=COX_PENALIZER)
|
|
cox.fit(train[keep], "tiempo_meses", "evento", fit_options={"step_size": 0.5})
|
|
risk = cox.predict_partial_hazard(test[keep])
|
|
return float(concordance_index(test["tiempo_meses"], -risk, test["evento"]))
|
|
|
|
|
|
def variable_of(term: str, covariates: list[str]) -> str:
|
|
"""The covariate a dummy belongs to (the longest name it starts with)."""
|
|
found = [c for c in covariates if term.startswith(c + "_")]
|
|
return max(found, key=len) if found else term
|
|
|
|
|
|
@dataclass
|
|
class Horizon:
|
|
"""A horizon's cohort size, split fit and bootstrap (AUC pairs, and how often each
|
|
covariate entered the LR and the HBN)."""
|
|
|
|
n: int
|
|
events: int
|
|
split: Split
|
|
replicates: list[Split] = field(default_factory=list)
|
|
|
|
@property
|
|
def aucs(self) -> np.ndarray:
|
|
return np.array([(r.auc_lr, r.auc_hbn) for r in self.replicates]).reshape(-1, 2)
|
|
|
|
def selection(self, covariates: list[str]) -> dict[str, float] | None:
|
|
"""Share of the replicates whose final LR has a term of each covariate."""
|
|
if not self.replicates:
|
|
return None
|
|
counts = {}
|
|
for r in self.replicates:
|
|
for v in {variable_of(t, covariates) for t in r.terms}:
|
|
counts[v] = counts.get(v, 0) + 1
|
|
return {v: k / len(self.replicates) for v, k in counts.items()}
|
|
|
|
|
|
@dataclass
|
|
class CohortFit:
|
|
cohort: Cohort
|
|
c_index: float
|
|
horizons: dict[int, Horizon]
|
|
|
|
|
|
def fit(cohorts: dict[str, Cohort], n_bootstrap: dict[str, int]) -> dict[str, CohortFit]:
|
|
"""Every cohort's split fits, bootstrap replicates and C-index, in one pool of workers.
|
|
Each horizon's resamples come from a fresh generator seeded SEED."""
|
|
frames = {(s, h): at_horizon(c.frame, h) for s, c in cohorts.items() for h in HORIZONS}
|
|
tasks = []
|
|
for (s, h), frame in frames.items():
|
|
rng = np.random.default_rng(SEED)
|
|
rows = [rng.integers(0, len(frame), len(frame)) for _ in range(n_bootstrap.get(s, 0))]
|
|
tasks += [
|
|
((s, h, b), _replicate, (frame, cohorts[s].covariates, r, b))
|
|
for b, r in enumerate(rows)
|
|
]
|
|
tasks.append(((s, h, "split"), split_fit, (frame, cohorts[s].covariates)))
|
|
tasks += [((s, None, "cox"), c_index, (c,)) for s, c in cohorts.items()]
|
|
done = Parallel(n_jobs=-1)(delayed(f)(*args) for _, f, args in reversed(tasks))
|
|
results = dict(zip([key for key, _, _ in reversed(tasks)], done, strict=True))
|
|
out = {}
|
|
for s, cohort in cohorts.items():
|
|
horizons = {}
|
|
for h in HORIZONS:
|
|
frame = frames[(s, h)]
|
|
reps = [results[(s, h, b)] for b in range(n_bootstrap.get(s, 0))]
|
|
horizons[h] = Horizon(
|
|
len(frame),
|
|
int(frame["y"].sum()),
|
|
results[(s, h, "split")],
|
|
[r for r in reps if r is not None],
|
|
)
|
|
out[s] = CohortFit(cohort, results[(s, None, "cox")], horizons)
|
|
return out
|
|
|
|
|
|
def tables(fitted: CohortFit) -> dict[int, dict]:
|
|
"""What the saved model keeps per horizon: the split's LR terms refitted on the whole
|
|
horizon cohort, and the split's HBN parents with their CPT on it."""
|
|
found = {}
|
|
for h, hz in fitted.horizons.items():
|
|
frame = at_horizon(fitted.cohort.frame, h)
|
|
covariates, terms, chosen = fitted.cohort.covariates, hz.split.terms, hz.split.parents
|
|
prior = float(frame["y"].mean())
|
|
entry = {
|
|
"lr_prior": prior,
|
|
"lr_terms": terms,
|
|
"lr_constant": 0.0,
|
|
"lr_coefficients": [],
|
|
"hbn_parents": chosen,
|
|
"hbn_prior": prior,
|
|
"hbn_cpt": {},
|
|
}
|
|
if terms and (m := logit(frame["y"], encode(frame, covariates)[terms])) is not None:
|
|
entry["lr_constant"] = float(m.params["const"])
|
|
entry["lr_coefficients"] = [float(m.params[t]) for t in terms]
|
|
if chosen:
|
|
entry["hbn_cpt"] = cpt(bn_table(frame, covariates), chosen)
|
|
found[h] = entry
|
|
return found
|