74 lines
2.9 KiB
Python
74 lines
2.9 KiB
Python
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
|
|
|
|
|
|
@dataclass
|
|
class Recurrence:
|
|
cohort: str
|
|
horizons: tuple[int, ...]
|
|
covariates: list[str]
|
|
tables: dict[int, dict]
|
|
|
|
def predict(self, X: pd.DataFrame) -> pd.DataFrame:
|
|
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]:
|
|
from models.cama.recurrence import site
|
|
|
|
return fit(
|
|
{"site": site.prepare(rows)}, "site", "site", modeling.N_BOOTSTRAP if bootstrap else {}
|
|
)
|
|
|
|
|
|
def fit(
|
|
found: dict, saved: str, label: str, n_bootstrap: dict[str, int]
|
|
) -> tuple[Recurrence, dict, dict]:
|
|
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_)
|