92 lines
4.2 KiB
Python
92 lines
4.2 KiB
Python
"""CaMa recurrence: the probability of breast cancer recurring by 12, 36 and 60 months, learned
|
|
from the site's own patients (site). Per horizon, a stepwise logistic regression and a Bayesian
|
|
network (BDeu parents of the outcome) are fitted and validated (cohorts, modeling); a calculator
|
|
gives the recurrence-free probability of clinical scenarios with bootstrap intervals and
|
|
survival curves (calculator, curves); risk factors are rated by four criteria (factors); reports
|
|
gives the tables and figures."""
|
|
|
|
from dataclasses import dataclass
|
|
|
|
import joblib
|
|
import numpy as np
|
|
import pandas as pd
|
|
|
|
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
|
|
|
|
HORIZONS = modeling.HORIZONS # months
|
|
|
|
|
|
@dataclass
|
|
class Recurrence:
|
|
"""Per horizon: the LR (intercept and coefficients of its terms) and the HBN (CPT over
|
|
its parents, keyed by their categories); the recurrence probability is their mean, and an
|
|
unseen parent configuration takes the horizon's recurrence rate."""
|
|
|
|
cohort: str
|
|
horizons: tuple[int, ...]
|
|
covariates: list[str]
|
|
tables: dict[int, dict]
|
|
|
|
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
|
|
"""The probability of recurrence by each horizon (`recurrence_{H}m`) for each row
|
|
of `X`, whose covariates are categories as in `cohort()` (missing: UNKNOWN)."""
|
|
found = X[self.covariates].astype(object)
|
|
found = found.where(found.notna(), cohorts.UNKNOWN).astype(str)
|
|
dummies = pd.get_dummies(found).astype(float)
|
|
out = {}
|
|
for h in self.horizons:
|
|
t = self.tables[h]
|
|
p_lr = np.full(len(found), t["lr_prior"])
|
|
if t["lr_terms"]:
|
|
x = dummies.reindex(columns=t["lr_terms"], fill_value=0.0).to_numpy()
|
|
logit = t["lr_constant"] + x @ np.asarray(t["lr_coefficients"])
|
|
p_lr = 1 / (1 + np.exp(-logit))
|
|
p_hbn = np.full(len(found), t["hbn_prior"])
|
|
if t["hbn_parents"]:
|
|
keys = map(tuple, found[t["hbn_parents"]].to_numpy())
|
|
p_hbn = np.array([t["hbn_cpt"].get(k, t["hbn_prior"]) for k in keys])
|
|
out[f"recurrence_{h}m"] = (p_lr + p_hbn) / 2
|
|
return pd.DataFrame(out, index=X.index)
|
|
|
|
|
|
def train_site(rows: pd.DataFrame, bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
|
|
"""The model of the site's own cohort (models.cama.recurrence.site), its metrics and its
|
|
reports. Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk
|
|
factors' stability criterion, are then missing)."""
|
|
from models.cama.recurrence import site
|
|
|
|
return fit({"site": site.prepare(rows)}, "site", "site",
|
|
modeling.N_BOOTSTRAP if bootstrap else {}) # fmt: skip
|
|
|
|
|
|
def fit(found: dict, saved: str, label: str,
|
|
n_bootstrap: dict[str, int]) -> tuple[Recurrence, dict, dict]: # fmt: skip
|
|
"""The models of each prepared cohort, their validation, calculator and risk factors;
|
|
the `saved` cohort's is the model kept."""
|
|
sources = list(found)
|
|
try:
|
|
fits = modeling.fit(found, n_bootstrap)
|
|
drawn = {s: calculator.calculator(fits[s]) for s in sources}
|
|
finally:
|
|
joblib.externals.loky.get_reusable_executor().shutdown(wait=True)
|
|
table = pd.concat([factors.risk_factors(fits[s]) for s in sources], ignore_index=True)
|
|
summary = [row for s in sources for row in factors.scenario_summary(fits[s], table)]
|
|
auc = [row for s in sources for row in reports.auc_rows(fits[s])]
|
|
points = [row for s in sources for row in drawn[s][1]]
|
|
kept = fits[saved]
|
|
model = Recurrence(saved, HORIZONS, kept.cohort.covariates, modeling.tables(kept))
|
|
technical = {
|
|
"model": "recurrence",
|
|
"cohort": label,
|
|
"method": "stepwise logistic regression + Bayesian network (BDeu), averaged",
|
|
"rutinas": reports.routines(found, n_bootstrap),
|
|
"recurrencia_desarrollo": reports.development(auc, table, points, summary),
|
|
}
|
|
interpretability = {
|
|
"model": "recurrence",
|
|
"kind": "scenarios",
|
|
"recurrencia": reports.figures([r for s in sources for r in drawn[s][0]]),
|
|
}
|
|
reports_ = {"technical_validation": technical, "interpretability": interpretability}
|
|
return model, reports.metrics(auc), reports_
|