CaCu models: no risk without HPV, hidden models untrained, inputs kept per prediction, attrition and variance diagnostics, rebuild job, opt-in Firth development evaluation

This commit is contained in:
Roberto Treviño
2026-12-05 19:42:07 -06:00
parent 69f5c20e2f
commit 20651b8d17
16 changed files with 802 additions and 68 deletions
+21 -1
View File
@@ -5,6 +5,9 @@ gives the current model's predictions.
Fixed on purpose, so left out of the comparison:
- cin2_logistic's index date: the current estimator reads P(no outcome) as a date
(1970-01-01 for everyone); the rewrite returns the index sample's date.
- A patient without an HPV result at the index is not evaluated; the current models read it
as negative, so a result that is not positive stands in for it here.
- An interval whose covariance can't be estimated is unknown, not the current platform's.
"""
import json
@@ -14,6 +17,8 @@ import numpy as np
import pandas as pd
import pytest
from core import cacu
from models.cacu.features import days, prepared
from models.cacu.specs import MODELS
REFERENCE = Path(__file__).parents[2] / "tests" / "fixtures" / "reference" / "cacu"
@@ -55,11 +60,23 @@ def timelines(cohort: str) -> pd.DataFrame:
return found
def assumed_hpv(events: pd.DataFrame) -> pd.DataFrame:
"""A not-positive HPV result (nor a negative one) at the index of whoever has none."""
near = days(prepared(events)).between(0, cacu.INDEX_SAMPLE_DAYS)
tested = events.loc[(events["type"] == "hpv") & near.to_numpy(), "person_id"]
index = events.groupby("person_id", as_index=False).first()
missing = index[~index["person_id"].isin(tested)]
assumed = missing.assign(date=missing["index_date"], type="hpv", value_code="assumed")
return pd.concat([events, assumed[events.columns]], ignore_index=True)
@pytest.mark.parametrize("name", ["cin2_pim", "cancer_pim", "cin2_pim_post_treatment",
"cin2_logistic"]) # fmt: skip
def test_predictions_match_the_current_models(name):
spec = MODELS[name]
events = timelines(COHORTS[spec.cohort])
if spec.method != "logistic regression":
events = assumed_hpv(events)
args = (REFERENCE_CUTOFF,) if spec.method == "logistic regression" else ()
model, metrics, _ = spec.train(events, *args)
reference = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
@@ -78,7 +95,9 @@ def test_predictions_match_the_current_models(name):
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
np.testing.assert_allclose(both[ours], both[theirs], rtol=RTOL, atol=0)
kept = both[ours].notna() | (ours == "probability") # estimable intervals
np.testing.assert_allclose(both.loc[kept, ours], both.loc[kept, theirs], rtol=RTOL,
atol=0) # fmt: skip
if spec.method != "logistic regression":
assert (pd.to_datetime(both["index_date"]) == pd.to_datetime(both["fecha_indice"])).all()
@@ -105,6 +124,7 @@ def test_survival_matches_the_current_model_with_its_index_fixed():
"stack_w_lr_36m", "stack_w_lr_60m"): # fmt: skip
assert metrics[name] == pytest.approx(current["metrics"][name], rel=RTOL), name
found = spec.predict(model, events)
assert all(set(json.loads(v)) == set(spec.features) for v in found["input_values"])
reference = pd.read_parquet(REFERENCE / "ref" / "survival.parquet")
both = found.merge(reference, left_on=["person_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip