diff --git a/models/cacu/survival/estimator.py b/models/cacu/survival/estimator.py index 4468266..d028a39 100644 --- a/models/cacu/survival/estimator.py +++ b/models/cacu/survival/estimator.py @@ -105,16 +105,35 @@ class MemberFeatures(TransformerMixin, BaseEstimator): 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.""" + without one) and her mortality is empty too. - def __init__(self, survival=None, horizons_years=(1.0, 3.0, 5.0)): + 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) @@ -130,8 +149,30 @@ class IntervalSurvival(BaseEstimator): 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_) @@ -144,6 +185,8 @@ class IntervalSurvival(BaseEstimator): 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]) diff --git a/models/cacu/survival/model.py b/models/cacu/survival/model.py index 1ec213e..03c1acb 100644 --- a/models/cacu/survival/model.py +++ b/models/cacu/survival/model.py @@ -75,9 +75,12 @@ def train_test_split(labelled_members: pd.DataFrame, train_fraction: float) -> d 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 fitted_survival(train_set: pd.DataFrame, survival: dict, horizons_years: list[float], + risk_interval_level: float | None = None, risk_interval_replicas: int = 100) -> IntervalSurvival: + """The interval survival fitted on the training members, with each combination's bootstrap interval at + `risk_interval_level` when there is one (`models.dags.estimation` reads the same key from the run).""" + return IntervalSurvival(survival, tuple(horizons_years), risk_interval_level, risk_interval_replicas).fit( + train_set[FEATURES], train_set[["months", "event"]]) def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataFrame) -> np.ndarray: @@ -87,7 +90,7 @@ def test_interval_survival(fitted_survival: IntervalSurvival, test_set: pd.DataF def train_mortality(fitted_survival: IntervalSurvival, train_set: pd.DataFrame) -> np.ndarray: """The training members' mortality at each horizon (apparent performance).""" - return fitted_survival.predict_proba(train_set[FEATURES]) + return 1.0 - fitted_survival.survival_proba(train_set[FEATURES]) def metrics(train_set: pd.DataFrame, test_set: pd.DataFrame, test_interval_survival: np.ndarray, diff --git a/models/cacu/survival/model.toml b/models/cacu/survival/model.toml index 10270d1..7dd689d 100644 --- a/models/cacu/survival/model.toml +++ b/models/cacu/survival/model.toml @@ -29,6 +29,10 @@ complement = "supervivencia" train_fraction = 0.7 # The model's horizons, in years; `survival.horizons` are the same in months. horizons_years = [1.0, 3.0, 5.0] +# The level of each risk's interval: per combination of the covariates, the percentiles of `risk_interval_replicas` +# refits on bootstrap resamples of the training members. None gives no interval. +risk_interval_level = 0.95 +risk_interval_replicas = 100 # The age at the index in bands, in years. The cytology and HPV are the most recent up to the index, at any distance. age_cuts = [35, 45, 55] diff --git a/tests/cacu/test_cacu_survival.py b/tests/cacu/test_cacu_survival.py index 8ce3868..93572b3 100644 --- a/tests/cacu/test_cacu_survival.py +++ b/tests/cacu/test_cacu_survival.py @@ -37,7 +37,7 @@ CONFIG = SCENARIO.config WINDOW = {"recruitment_start": "2018-01-01", "recruitment_end": "2027-01-01", "cutoff": CUTOFF.isoformat()} LINEAGE = {"url": "cacu/cohorte_total", "datos_as_of": CUTOFF.isoformat(), "parametros": json.dumps(WINDOW)} N = 240 -QUICK = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}} +QUICK = {**CONFIG, "survival": {**CONFIG["survival"], "n_boot": 20, "ks_max_seconds": 5}, "risk_interval_replicas": 20} def _row(pac_id, when, tipo, valor=None, source="t", source_id=None, first=None): @@ -130,7 +130,7 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort(): assert required == {"source_cohort", "cohort_lineage", "age_cuts", "cytology", "etiquetas", "horizons_years", "index", "survival", "train_fraction"} # `index` is required: the registered model re-indexes a build with it. - assert optional == {"calibration_bins", "report_panels"} + assert optional == {"calibration_bins", "report_panels", "risk_interval_level", "risk_interval_replicas"} def _primer_carcinoma(frame: pd.DataFrame) -> pd.Series: @@ -219,8 +219,9 @@ def test_the_dataflow_reaches_its_metrics_routines_and_population_record_without def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_models_index(cohort_file, mlflow_tracking, tmp_path): """Pins down: training on a build's file registers a version with its population record; estimating with it writes - one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with the members the - scenario leaves out absent. Fails if the version cannot score a build or the estimate keeps the cohort's index.""" + one row per scored member and horizon, dated by the model's index (the carcinoma biopsy), with its combination's + bootstrap interval holding it, and with the members the scenario leaves out absent. Fails if the version cannot + score a build, the estimate keeps the cohort's index, or the risks lose their interval.""" version = train(dataclasses.replace(SCENARIO, config=QUICK), CohortFile(cohort_file)) output = tmp_path / "estimate.parquet" @@ -234,6 +235,8 @@ def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_mode inicio = date.fromisoformat(WINDOW["recruitment_start"]) antes = set(_primer_carcinoma(read_cohort(cohort_file))[lambda d: d < inicio].index) assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} + assert risks[["ic_bajo", "ic_alto"]].notna().all().all() + assert ((risks["ic_bajo"] <= risks["probabilidad"]) & (risks["probabilidad"] <= risks["ic_alto"])).mean() > 0.9 assert set(risks["pac_id"]) == (set(range(1, N + 1)) | {241}) - antes frame = read_cohort(cohort_file) diagnosis = frame[(frame["tipo"] == "biopsia") & (frame["valor_codigo"] == "CARCINOMA") & (frame["pac_id"] == 1)]