55d675c8a8
The covariates are categorical, so every member of a combination gets the same mortality. Training keeps, per combination of its members, the percentiles of the mortality of `risk_interval_replicas` refits on bootstrap resamples (`risk_interval_level`, 0.95), and estimating writes it as each risk's interval. A combination training never saw has none.
200 lines
12 KiB
Python
200 lines
12 KiB
Python
"""What the CaCu survival model is made of: the member table a build's events give, and the interval survival estimator.
|
|
|
|
`MemberFeatures` turns a build's long frame into one row per member, in `pac_id` order: the members the scenario's index
|
|
and rules leave get their covariates and the index date; the rest keep their row, empty. The index is the diagnosis
|
|
(provisionally the first biopsy reported as invasive carcinoma) and the covariates are the member's most recent
|
|
observations up to it: her age group at the index, the cytology of her latest sample (KPNC's categories, the more severe
|
|
of its squamous and glandular results) and her latest HPV result. `IntervalSurvival` is CaMa's
|
|
(`models.cama.survival.estimator`): per interval of `survival.horizons`, a logistic regression and a Bayesian network
|
|
with a tabular CPT on the patients alive at its start (`models.cama.seer_survival.survival_models`), stacked with
|
|
out-of-sample weights; a patient's survival to each horizon is the product of the intervals'.
|
|
|
|
DUPLICATED (issue #9): `encode`, `interval_cohort` and `IntervalSurvival` are CaMa's with the covariates as `FEATURES`
|
|
of this module instead of CaMa's; CaMa's read its own `FEATURES` as a module constant, so they can't be reused without
|
|
changing CaMa. The outcome (`outcome_table`) and the settings (`survival_settings`) are CaMa's, imported.
|
|
"""
|
|
|
|
import json
|
|
|
|
import numpy as np
|
|
import pandas as pd
|
|
from sklearn.base import BaseEstimator, TransformerMixin
|
|
|
|
from models.cama.seer_survival import survival_models as sm
|
|
from models.cama.survival.estimator import EPOCH, INDEX_COLUMN, UNKNOWN, WINDOW_KEYS, _band, survival_settings
|
|
from models.io.contracts import DAYS_PER_YEAR
|
|
from models.steps import indexing
|
|
|
|
FEATURES = ["age_group", "cytology", "hpv"]
|
|
NUMERIC = ["age_years"] # the age before banding
|
|
|
|
|
|
def _latest_cytology(prior: pd.DataFrame, cytology: dict) -> pd.Series:
|
|
"""Per `pac_id`, KPNC's category of her latest cytology sample: the more severe of its squamous and glandular
|
|
results; None when no result falls in a category."""
|
|
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
|
|
results = prior[prior["tipo"].isin(["bethesda", "glandular"]) & prior["valor_codigo"].notna()]
|
|
latest = results[results["fecha"] == results.groupby("pac_id")["fecha"].transform("max")]
|
|
ranks = latest["valor_codigo"].map(severity).groupby(latest["pac_id"]).max()
|
|
names = list(cytology)
|
|
return ranks.map(lambda rank: None if pd.isna(rank) else names[int(rank)])
|
|
|
|
|
|
def member_table(cohort: pd.DataFrame, age_cuts: list, cytology: dict) -> pd.DataFrame:
|
|
"""One row per member of an indexed frame, indexed by `pac_id`: `fecha_indice`, the covariates in `FEATURES` and the
|
|
age in years. Each covariate is the member's most recent observation up to the index (the index day included): her
|
|
age at the index from her `nacimiento`, her latest cytology sample's category (`_latest_cytology`) and her latest HPV
|
|
result; empty where the build has none."""
|
|
frame = cohort.assign(fecha=pd.to_datetime(cohort["fecha"]), fecha_indice=pd.to_datetime(cohort["fecha_indice"]))
|
|
members = frame.groupby("pac_id")["fecha_indice"].first().to_frame()
|
|
birth = frame[frame["tipo"] == "nacimiento"].groupby("pac_id")["fecha"].min().reindex(members.index)
|
|
members["age_years"] = (members["fecha_indice"] - birth).dt.days / DAYS_PER_YEAR
|
|
members["age_group"] = _band(members["age_years"], age_cuts)
|
|
prior = frame[frame["fecha"] <= frame["fecha_indice"]]
|
|
members["cytology"] = _latest_cytology(prior, cytology).reindex(members.index).astype(object)
|
|
hpv = prior[(prior["tipo"] == "vph") & prior["valor_codigo"].notna()].sort_values(["fecha", "fuente_id"])
|
|
members["hpv"] = hpv.groupby("pac_id")["valor_codigo"].last().reindex(members.index)
|
|
members = members.astype({"cytology": object, "hpv": object})
|
|
return members[["fecha_indice", *FEATURES, *NUMERIC]]
|
|
|
|
|
|
def encode(frame: pd.DataFrame, categories: dict | None = None, dummy_columns: list | None = None):
|
|
"""CaMa's `encode` over this module's `FEATURES` (DUPLICATED, issue #9): `(X_dum, X_int, categories, dummy_columns)`.
|
|
With no `categories` they are learned from `frame`; with them, a value the fit never saw takes the unknown
|
|
category."""
|
|
frame = frame[FEATURES].astype(object).where(frame[FEATURES].notna(), UNKNOWN).astype(str)
|
|
if categories is None:
|
|
dummy_columns = list(pd.get_dummies(frame, drop_first=True).columns)
|
|
categories = {name: list(pd.factorize(frame[name])[1]) for name in FEATURES}
|
|
columns = []
|
|
for name in FEATURES:
|
|
codes = pd.Categorical(frame[name], categories=categories[name]).codes
|
|
fallback = categories[name].index(UNKNOWN) if UNKNOWN in categories[name] else 0
|
|
columns.append(np.where(codes < 0, fallback, codes))
|
|
X_dum = pd.get_dummies(frame).reindex(columns=dummy_columns, fill_value=0).to_numpy(dtype=np.float32)
|
|
return X_dum, np.column_stack(columns).astype(int), categories, dummy_columns
|
|
|
|
|
|
def interval_cohort(features: pd.DataFrame, outcomes: pd.DataFrame, settings):
|
|
"""CaMa's `interval_cohort` over this module's `FEATURES` (DUPLICATED, issue #9)."""
|
|
X_dum, X_int, categories, dummy_columns = encode(features)
|
|
cohort = sm.Cohort(outcomes["months"].to_numpy(int), outcomes["event"].to_numpy(bool), X_dum, X_int,
|
|
X_int.max(axis=0) + 1, [0, *settings.horizons], sm.fixed_parent_indices(FEATURES, settings))
|
|
return cohort, categories, dummy_columns
|
|
|
|
|
|
class MemberFeatures(TransformerMixin, BaseEstimator):
|
|
"""A build's long frame to one row per member in `pac_id` order: the covariates in `FEATURES` and `INDEX_COLUMN`,
|
|
the model's index date, empty for the members the scenario's index and rules leave out. Learns nothing."""
|
|
|
|
def __init__(self, index=None, window=None, age_cuts=(35, 45, 55), cytology=None):
|
|
self.index = index
|
|
self.window = window
|
|
self.age_cuts = age_cuts
|
|
self.cytology = cytology
|
|
|
|
def fit(self, X, y=None):
|
|
return self
|
|
|
|
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
|
|
everyone = pd.Index(sorted(X["pac_id"].unique()), name="pac_id")
|
|
indexed = indexing.cohort(X, {"parametros": json.dumps(self.window or {})}, self.index)
|
|
table = member_table(indexed, list(self.age_cuts), self.cytology) \
|
|
if len(indexed) else pd.DataFrame(columns=["fecha_indice", *FEATURES, *NUMERIC])
|
|
table = table.reindex(everyone).rename(columns={"fecha_indice": INDEX_COLUMN})
|
|
return table[[*FEATURES, INDEX_COLUMN]]
|
|
|
|
|
|
def _combinations(X: pd.DataFrame) -> pd.DataFrame:
|
|
"""Each member's combination of the covariates, as `encode` reads them (a missing value is `UNKNOWN`)."""
|
|
return X[FEATURES].astype(object).where(X[FEATURES].notna(), UNKNOWN).astype(str).reset_index(drop=True)
|
|
|
|
|
|
def _frame(combinations: pd.DataFrame) -> pd.DataFrame:
|
|
return combinations.replace(UNKNOWN, None)
|
|
|
|
|
|
class IntervalSurvival(BaseEstimator):
|
|
"""CaMa's `IntervalSurvival` over this module's `FEATURES` (DUPLICATED, issue #9): per interval, LR and HBN stacked;
|
|
the survival to a horizon is the product of the intervals' survival. `fit(X, y)` takes the covariates and `y` with
|
|
`months` and `event`; `predict_proba(X)` gives the mortality (1 minus survival) at each of `horizons_years`. With
|
|
`INDEX_COLUMN` in `X` the first column is the member's model index date (days since 1970-01-01, empty for a member
|
|
without one) and her mortality is empty too.
|
|
|
|
With `interval_level`, two more blocks follow the mortality: its interval's lower and upper ends. The covariates
|
|
are categorical, so every member of a combination gets the same mortality, and so the same interval: `fit` keeps
|
|
one per combination of the training members (`interval_table_`), the percentiles of the mortality of
|
|
`interval_replicas` refits of this same model on bootstrap resamples of them (seeded by `seed`). A combination the
|
|
training never saw has no interval."""
|
|
|
|
def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0), interval_level=None, interval_replicas=100,
|
|
seed=0):
|
|
self.survival = survival
|
|
self.horizons_years = horizons_years
|
|
self.interval_level = interval_level
|
|
self.interval_replicas = interval_replicas
|
|
self.seed = seed
|
|
|
|
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
|
|
s = survival_settings(self.survival)
|
|
if [h / 12 for h in s.horizons] != list(self.horizons_years):
|
|
raise ValueError(f"survival.horizons {list(s.horizons)} months and horizons_years {list(self.horizons_years)} differ")
|
|
cohort, self.categories_, self.dummy_columns_ = interval_cohort(X, y, s)
|
|
everyone = np.arange(len(X))
|
|
if s.combine_active and len(X) >= 2 * s.stack_folds:
|
|
weights = sm.stacking_weights(cohort, s, np.ones(len(X), bool), *sm.out_of_fold(cohort, s, len(X)))
|
|
self.weights_ = weights["w_LR"].to_numpy()
|
|
self.stacking_ = weights.to_dict("records")
|
|
else:
|
|
self.weights_, self.stacking_ = np.full(len(s.horizons), 0.5), []
|
|
self.fitted_ = sm.fit_intervals(cohort, s, everyone, None)
|
|
self.levels_ = cohort.levels
|
|
self.interval_table_ = self._interval_table(X, y) if self.interval_level else {}
|
|
return self
|
|
|
|
def _interval_table(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[tuple, tuple[list, list]]:
|
|
combinations = _combinations(X).drop_duplicates()
|
|
rng = np.random.default_rng(self.seed)
|
|
replicas = []
|
|
for _ in range(int(self.interval_replicas)):
|
|
rows = rng.integers(0, len(X), len(X))
|
|
refit = IntervalSurvival(self.survival, self.horizons_years)
|
|
refit.fit(X.iloc[rows].reset_index(drop=True), y.iloc[rows].reset_index(drop=True))
|
|
replicas.append(1.0 - refit.survival_proba(_frame(combinations)))
|
|
tail = 50 * (1 - self.interval_level)
|
|
low, high = np.nanpercentile(np.stack(replicas), [tail, 100 - tail], axis=0)
|
|
rows = combinations.itertuples(index=False)
|
|
return {tuple(c): (low[i].tolist(), high[i].tolist()) for i, c in enumerate(rows)}
|
|
|
|
def mortality_interval(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
|
|
"""Each member's interval ends at each horizon: her combination's, empty for one the training never saw."""
|
|
empty = ([np.nan] * len(self.horizons_years),) * 2
|
|
ends = [self.interval_table_.get(tuple(c), empty) for c in _combinations(X).itertuples(index=False)]
|
|
return (np.array([e[0] for e in ends], dtype=float).reshape(len(X), -1),
|
|
np.array([e[1] for e in ends], dtype=float).reshape(len(X), -1))
|
|
|
|
def interval_proba(self, X: pd.DataFrame) -> np.ndarray:
|
|
"""Each member's probability of surviving each interval, given she is alive at its start."""
|
|
X_dum, X_int, _, _ = encode(X, self.categories_, self.dummy_columns_)
|
|
P_lr, P_hb, _ = sm.predict_intervals(self.fitted_, X_dum, X_int, self.levels_)
|
|
return self.weights_[None, :] * P_lr + (1 - self.weights_[None, :]) * P_hb
|
|
|
|
def survival_proba(self, X: pd.DataFrame) -> np.ndarray:
|
|
"""Each member's survival to each horizon."""
|
|
return np.cumprod(self.interval_proba(X), axis=1)
|
|
|
|
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
|
|
mortality = 1.0 - self.survival_proba(X)
|
|
if self.interval_level:
|
|
mortality = np.column_stack([mortality, *self.mortality_interval(X)])
|
|
if INDEX_COLUMN not in X.columns:
|
|
return mortality
|
|
dates = pd.to_datetime(X[INDEX_COLUMN])
|
|
member = dates.notna().to_numpy()
|
|
mortality[~member] = np.nan
|
|
return np.column_stack([((dates - EPOCH).dt.days).to_numpy(dtype=float), mortality])
|
|
|
|
|
|
__all__ = ["FEATURES", "INDEX_COLUMN", "IntervalSurvival", "MemberFeatures", "WINDOW_KEYS", "encode", "interval_cohort",
|
|
"member_table"]
|