Files
models/models/cama/recurrence/__init__.py
T

94 lines
4.3 KiB
Python

"""CaMa recurrence (v1): the probability of breast cancer recurring by 12, 36 and 60 months,
learned from two public reference cohorts, METABRIC and SCAN-B, as the platform loaded their
published files (the `cama_reference` pipeline). Per cohort and 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. The saved model is METABRIC's,
refitted on each whole horizon cohort."""
from dataclasses import dataclass
import joblib
import numpy as np
import pandas as pd
from models.cama.recurrence import calculator, cohorts, factors, modeling, reports
SOURCES = ("metabric", "scanb")
HORIZONS = modeling.HORIZONS # months
SAVED = "metabric"
def cohort(source: str, rows: pd.DataFrame) -> pd.DataFrame:
"""The source's cohort table, from its dataset's rows: fixed columns, then its
covariates as categories."""
return cohorts.prepare(source, rows).frame
@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(raws: dict[str, pd.DataFrame], bootstrap: bool = True) -> tuple[Recurrence, dict, dict]:
"""Both cohorts' models, validation, calculator and risk factors, from their datasets'
rows.
Without `bootstrap`, the AUC bootstrap is skipped (its metrics, and the risk factors'
stability criterion, are then missing)."""
found = {s: cohorts.prepare(s, raws[s]) for s in SOURCES}
n_bootstrap = modeling.N_BOOTSTRAP if bootstrap else {}
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]]
saved = fits[SAVED]
model = Recurrence(SAVED, HORIZONS, saved.cohort.covariates, modeling.tables(saved))
technical = {
"model": "recurrence",
"cohort": "metabric+scanb",
"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_