222 lines
14 KiB
Python
222 lines
14 KiB
Python
"""CaMa survival prototype: the mortality of a woman with an invasive carcinoma at 6, 12 and 18 months from the first
|
|
invasive biopsy report.
|
|
|
|
The scenario starts from the total cohort and indexes it in its own pipeline (`models.steps.indexing`,
|
|
`[config.index]`): the index is the first biopsy report graded invasive. Each member's covariates are the results of
|
|
that report (histological type, Nottingham grade, ER, PR, HER2, Ki-67, lesion size) and her age at the index; her outcome is the
|
|
months from the index to her death or, with none by the build's cut-off, to the cut-off (`survival.cap_months` cuts
|
|
the follow-up). The fit is the SEER pipeline's interval survival (`models.cama.seer_survival.survival_models`): per
|
|
interval a logistic regression and a Bayesian network, stacked. A member without a result has it as a category of its
|
|
own, as the pipeline does with its unknowns.
|
|
|
|
The split, the metrics and the routines (ML-01a) are here; the temporal split is `models.steps.model_fitting`'s.
|
|
`fitted_model` puts `MemberFeatures` in front of the fitted estimator, so the registered model is one scikit-learn
|
|
`Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through loaders, and
|
|
registering is the driver's saver (`models.dags.training`).
|
|
"""
|
|
|
|
import json
|
|
from datetime import date
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
import pandera.pandas as pandera
|
|
from hamilton.function_modifiers import extract_fields
|
|
from sklearn.metrics import roc_auc_score
|
|
from sklearn.pipeline import Pipeline
|
|
|
|
from models.annotations import checked_frame
|
|
from models.cama.seer_survival.settings import SurvivalSettings
|
|
from models.cama.survival import estimator
|
|
from models.cama.survival.estimator import FEATURES, IntervalSurvival, MemberFeatures
|
|
from models.steps import model_fitting
|
|
|
|
LABELLED_MEMBERS = pandera.DataFrameSchema(
|
|
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
|
|
"fecha_indice": pandera.Column(nullable=False),
|
|
"months": pandera.Column(int, pandera.Check.ge(0)),
|
|
"event": pandera.Column(bool),
|
|
**{name: pandera.Column(nullable=True) for name in FEATURES}},
|
|
name="labelled members")
|
|
|
|
|
|
def cohort_cutoff(cohort_lineage: dict) -> date:
|
|
"""The build's cut-off: no event after it is in the file, and a member without a death is followed to it."""
|
|
return date.fromisoformat(cohort_lineage["datos_as_of"])
|
|
|
|
|
|
def survival_settings(survival: dict, horizons_years: list[float]) -> SurvivalSettings:
|
|
"""The pipeline's survival settings; its horizons, in months, must be `horizons_years`."""
|
|
settings = estimator.survival_settings(survival)
|
|
if [h / 12 for h in settings.horizons] != list(horizons_years):
|
|
raise ValueError(f"survival.horizons {list(settings.horizons)} and horizons_years {horizons_years} differ")
|
|
return settings
|
|
|
|
|
|
def member_features(cohort: pd.DataFrame, age_cuts: list[int], ki67_cuts: list[int], result_days: int,
|
|
size_cuts: list[int]) -> pd.DataFrame:
|
|
"""One row per member of the indexed cohort, by `pac_id`: her index date and covariates."""
|
|
return estimator.member_table(cohort, age_cuts, ki67_cuts, result_days, size_cuts)
|
|
|
|
|
|
def member_outcomes(cohort: pd.DataFrame, cohort_cutoff: date, survival_settings: SurvivalSettings) -> pd.DataFrame:
|
|
"""One row per member, by `pac_id`: months of follow-up and whether she died in them."""
|
|
return estimator.outcome_table(cohort, cohort_cutoff, survival_settings.cap_months)
|
|
|
|
|
|
@checked_frame(LABELLED_MEMBERS)
|
|
def labelled_members(member_features: pd.DataFrame, member_outcomes: pd.DataFrame) -> pd.DataFrame:
|
|
"""Every member of the indexed cohort with her covariates, her follow-up and whether she died."""
|
|
return member_features.join(member_outcomes).reset_index()
|
|
|
|
|
|
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
|
|
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> dict:
|
|
"""`models.steps.model_fitting`'s temporal split: the oldest index dates train, the newest test."""
|
|
return model_fitting.train_test_split(labelled_members, train_fraction, target_column="event")
|
|
|
|
|
|
def fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float]) -> IntervalSurvival:
|
|
"""The interval survival fitted on the training members."""
|
|
return IntervalSurvival(survival, tuple(horizons_years)).fit(train_set[FEATURES], train_set[["months", "event"]])
|
|
|
|
|
|
def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray:
|
|
"""The test members' probability of surviving each interval, given they are alive at its start."""
|
|
return fitted_survival.interval_proba(test_set[FEATURES])
|
|
|
|
|
|
def _interval_outcomes(frame: pd.DataFrame, borders: list[int], probabilities: np.ndarray) -> pd.DataFrame:
|
|
"""One row per member and interval she was at risk in: the model's probability of surviving it, whether she did
|
|
(`survived`) and its weight (a censoring inside the interval counts half, as in the fit)."""
|
|
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
|
|
rows = []
|
|
for j, (a, b) in enumerate(zip(borders[:-1], borders[1:])):
|
|
at_risk = months >= a
|
|
died = event & (months < b)
|
|
rows.append(pd.DataFrame({"interval": f"{a}-{b}", "p": probabilities[at_risk, j],
|
|
"survived": (~died[at_risk]).astype(float),
|
|
"weight": np.where((~event & (months < b))[at_risk], 0.5, 1.0)}))
|
|
return pd.concat(rows, ignore_index=True)
|
|
|
|
|
|
def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray:
|
|
"""The training members' mortality at each horizon (apparent performance: they are what the model was fitted on)."""
|
|
return fitted_survival.predict_proba(train_set[FEATURES])
|
|
|
|
|
|
def _known_status_auc(frame: pd.DataFrame, mortality: np.ndarray, horizon_months: int, column: int) -> dict:
|
|
"""The AUC of the mortality at one horizon among the members whose status there is known (died before it, or
|
|
followed to it), and how many they are; empty without both outcomes in at least 20 members."""
|
|
months, event = frame["months"].to_numpy(), frame["event"].to_numpy()
|
|
died = event & (months < horizon_months)
|
|
known = died | (months >= horizon_months)
|
|
if known.sum() < 20 or len(np.unique(died[known])) < 2:
|
|
return {}
|
|
return {"auc": float(roc_auc_score(died[known], mortality[known, column])), "n": int(known.sum())}
|
|
|
|
|
|
def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray,
|
|
train_mortality: np.ndarray, survival_settings: SurvivalSettings, fitted_survival: IntervalSurvival) -> dict:
|
|
"""Aggregates only: the members and deaths in each part and, over the member-intervals of the test members (every
|
|
month they were followed, not only the members whose status at a horizon is known), their number, the observed and
|
|
expected survival, the weighted Brier score and, with both outcomes, the AUC. A temporal split leaves the newest
|
|
members little follow-up, so a metric at one horizon would be of the few that died. The `auc_train_*` are the
|
|
apparent discrimination at each horizon, on the members the model was fitted on: they say the covariates were
|
|
used, not how it will do on new patients."""
|
|
found = {"n_train": len(train_set), "n_test": len(test_set), "events_train": int(train_set["event"].sum()),
|
|
"events_test": int(test_set["event"].sum())}
|
|
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
|
|
found["n_member_intervals_test"] = len(pairs)
|
|
if len(pairs):
|
|
w, y, p = pairs["weight"].to_numpy(), pairs["survived"].to_numpy(), pairs["p"].to_numpy()
|
|
found.update(observed_survival=float(np.average(y, weights=w)), expected_survival=float(np.average(p, weights=w)),
|
|
brier_interval=float(np.average((p - y) ** 2, weights=w)))
|
|
if len(np.unique(y)) == 2:
|
|
found["auc_interval"] = float(roc_auc_score(y, p, sample_weight=w))
|
|
for column, months in enumerate(survival_settings.horizons):
|
|
apparent = _known_status_auc(train_set, train_mortality, months, column)
|
|
if apparent:
|
|
found[f"auc_train_{months}m"], found[f"n_known_train_{months}m"] = apparent["auc"], apparent["n"]
|
|
for row, months in zip(fitted_survival.stacking_, survival_settings.horizons):
|
|
found[f"stack_w_lr_{months}m"] = float(row["w_LR"])
|
|
return found
|
|
|
|
|
|
def _dates(frame: pd.DataFrame) -> dict:
|
|
if frame.empty:
|
|
return {"n": 0}
|
|
return {"n": len(frame), "first_index_date": str(frame["fecha_indice"].min()),
|
|
"last_index_date": str(frame["fecha_indice"].max())}
|
|
|
|
|
|
def sampling(index_attrition: list, prior_observation: dict, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
|
train_fraction: float) -> dict:
|
|
"""MUESTREO: who could be used (the scenario's index and rules, step by step, and their prior history), and how
|
|
they were split."""
|
|
return {"method": "temporal: las fechas índice más antiguas entrenan y las más recientes prueban",
|
|
"index_attrition": [[step, int(n)] for step, n in index_attrition], "prior_observation": prior_observation,
|
|
"train_fraction": train_fraction, "train": _dates(train_set), "test": _dates(test_set)}
|
|
|
|
|
|
def missing_data(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
|
|
"""DATOS_FALTANTES: how many members lacked each covariate, and what was done about it."""
|
|
def missing(frame: pd.DataFrame) -> dict:
|
|
return {name: int(frame[name].isna().sum()) for name in FEATURES}
|
|
|
|
return {"method": "un resultado ausente es una categoría más (NA); no se imputa ni se descarta al miembro",
|
|
"train": missing(train_set), "test": missing(test_set)}
|
|
|
|
|
|
def analytic_method(fitted_survival: IntervalSurvival, survival_settings: SurvivalSettings) -> dict:
|
|
"""METODO_ANALITICO: the intervals, how the two models are stacked and which covariates the network kept."""
|
|
s = survival_settings
|
|
return {"method": "supervivencia por intervalos: regresión logística y red bayesiana (CPT tabular) por intervalo, "
|
|
"combinadas con pesos fuera de muestra; la supervivencia es el producto de los intervalos",
|
|
"intervals_months": [0, *s.horizons], "censoring": s.censoring, "cap_months": s.cap_months,
|
|
"hbn_ess": s.hbn_ess, "hbn_max_parents": s.hbn_max_parents, "covariates": FEATURES,
|
|
"stacking": [{k: (float(v) if isinstance(v, (int, float, np.floating)) else str(v)) for k, v in row.items()}
|
|
for row in fitted_survival.stacking_],
|
|
"hbn_parents": [[FEATURES[j] for j in model[0]] for _, model in fitted_survival.fitted_]}
|
|
|
|
|
|
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame) -> dict:
|
|
"""BALANCE_CLASES: deaths and members followed without one in each part; the classes are used as observed."""
|
|
def counts(frame: pd.DataFrame) -> dict:
|
|
return {"muertes": int(frame["event"].sum()), "sin muerte": int((~frame["event"]).sum())}
|
|
|
|
return {"method": "ninguno: no se remuestrea ni se pondera por clase; una censura dentro de un intervalo pesa medio "
|
|
"riesgo", "train": counts(train_set), "test": counts(test_set)}
|
|
|
|
|
|
def output_confidence(test_set: pd.DataFrame, test_interval_survival: np.ndarray, survival_settings: SurvivalSettings,
|
|
calibration_bins: int = 5) -> dict:
|
|
"""CONFIANZA_SALIDA: over the test members' member-intervals, the predicted survival of the interval against the
|
|
observed one, by quantiles."""
|
|
pairs = _interval_outcomes(test_set, [0, *survival_settings.horizons], test_interval_survival)
|
|
if len(pairs) == 0 or pairs["p"].nunique() < 2:
|
|
return {"method": "calibración en la prueba: sin dispersión suficiente para formar cuantiles", "n": len(pairs)}
|
|
bins = pd.qcut(pairs["p"], q=min(calibration_bins, pairs["p"].nunique()), duplicates="drop")
|
|
table = pairs.assign(py=pairs["p"] * pairs["weight"], sy=pairs["survived"] * pairs["weight"]).groupby(
|
|
bins, observed=True).agg(n=("p", "size"), w=("weight", "sum"), py=("py", "sum"), sy=("sy", "sum"))
|
|
return {"method": "calibración en la prueba por intervalo: supervivencia media prevista contra observada, por "
|
|
"cuantiles de los miembro-intervalos",
|
|
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.py / row.w),
|
|
"observed_rate": float(row.sy / row.w)} for interval, row in table.iterrows()]}
|
|
|
|
|
|
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
|
|
output_confidence: dict) -> dict:
|
|
"""Each routine's record, by the kind it's stored under (ML-01a)."""
|
|
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
|
|
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
|
|
|
|
|
|
def fitted_model(fitted_survival: IntervalSurvival, cohort_lineage: dict, index: dict, age_cuts: list[int],
|
|
ki67_cuts: list[int], result_days: int, size_cuts: list[int]) -> Pipeline:
|
|
"""What's registered: the fitted estimator behind `MemberFeatures`, which indexes the build as training did."""
|
|
parameters = json.loads(cohort_lineage.get("parametros") or "{}")
|
|
window = {key: parameters[key] for key in estimator.WINDOW_KEYS if key in parameters}
|
|
return Pipeline([("members", MemberFeatures(dict(index), window, tuple(age_cuts), tuple(ki67_cuts), result_days, tuple(size_cuts))),
|
|
("survival", fitted_survival)])
|