cin2_pim with PIMixture's I-spline baseline, frequency weights, HPV strata and KPNC's cytology categories

The incidence baseline is chosen in model.toml (Weibull or I-splines of order 4 with knots at quantiles, equal to
PIMixture's Ispline); identical rows are fitted once with their count as weight; one mixture per stratum, a member of
an unseen stratum or level gets NaN. The index cytology goes into KPNC's six categories, glandular results included and
the most severe winning; an optional history feature is read from the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-20 12:06:05 -06:00
parent 01e4406838
commit 3e72063e3f
7 changed files with 367 additions and 68 deletions
+1 -1
View File
@@ -33,7 +33,7 @@ WebApi.
| `dags/training.py`, `dags/estimation.py` | Training and estimating any scenario: `Scenario` reads `model.toml` (its `modules`, the graph's nodes, and `[config]`); the driver is `with_modules(*modules)` with the config, a source's loaders and the saver; `find_trained` (same source reference, `models` version, config and environment) before anything runs; a failing node's inputs are kept out of the log. Estimation runs the registered model's `predict_proba` on the source's frame and writes one row per member and horizon. `python -m models train\|estimate\|run … [--read db\|file]`: a kit build is read from the database by default. |
| `steps/model_fitting.py` | The classifier steps scenarios share: the temporal split, the classifier chosen by config, the fit and its metrics. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within one year (`horizons_years`, provisional) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. `model.toml` (names, `modules`: its `model.py` and `steps/model_fitting.py`, and `[config]`) and `model.py` (the dataflow to `labelled_members`, and `fitted_model`: a scikit-learn `Pipeline` that takes the long frame). Its routines' records (ML-01a: `sampling`, `missing_data`, `analytic_method`, `class_balance`, `output_confidence`) are nodes too, and the saver writes them; `train.py` only delegates to `dags/training.py`. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--read db|file] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]`, by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull incidence, `likelihood.py`), fitted to each member's code and interval; the clinical settings (windows, known-negative results) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/cin2_pim/` | CaCu's CIN2+ prevalence–incidence prototype: the cumulative risk at the index visit and at 1, 3 and 5 years. `PrevalenceIncidenceMixture`, a scikit-learn estimator (logistic prevalence, Weibull or I-spline incidence, `likelihood.py`), one mixture per HPV stratum, fitted to each member's code and interval; the clinical settings (windows, known-negative results, KPNC's cytology categories, the incidence family) in `model.toml`. No correction of verification bias, no clinical validation. Same commands as `cin2_logistic`. |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios. Cada escenario lleva sus cuadernos en `<escenario>/notebooks/`, fuera del paquete instalado. |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
+3 -2
View File
@@ -9,8 +9,9 @@ VPH+/NILM como desconocido).
## Modelo
- $\pi(x) = \operatorname{expit}(x^\top\theta)$: probabilidad de NIC2+ en la visita índice (prevalencia, logística).
- $S(t \mid z) = \exp\{-(t/\lambda)^k e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (Weibull, riesgos
proporcionales).
- $S(t \mid z) = \exp\{-\Lambda_0(t)\, e^{z^\top\beta}\}$: supervivencia libre de NIC2+ incidente (riesgos
proporcionales), con $\Lambda_0$ Weibull, $(t/\lambda)^k$, o los I-splines de PIMixture, $\sum_j e^{\gamma_j} I_j(t)$
(`incidence` en `model.toml`). Una mezcla por estrato de VPH, con la citología índice en las categorías de KPNC.
- Riesgo acumulado: $CR(t) = \pi + (1-\pi)\,[1 - S(t)]$.
El tiempo se cuenta en años desde la visita índice $T_0$.
+110 -28
View File
@@ -8,11 +8,21 @@ Each row has a code `c` and an interval `(l, r]` in years since the index visit:
- `c = -999`: unknown at the index visit (no colposcopy). Contributes `pi + (1 - pi) * (S(l) - S(r))`, usually
with `l = 0`.
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-(t / scale) ** shape * exp(Z @ beta))` the Weibull
survival of the incidence (proportional hazards in `Z`).
`pi = expit(X @ theta)` is the prevalence and `S(t) = exp(-H0(t) * exp(Z @ beta))` the survival of the incidence
(proportional hazards in `Z`). The baseline cumulative hazard `H0` is a family:
- `Weibull`: `H0(t) = (t / scale) ** shape`, the default;
- `ISpline`: PIMixture's weakly-parametric `H0(t) = sum_j exp(gamma_j) I_j(t)`, with `I_j` the I-spline basis on knots
at quantiles of the observed times. Each `I_j` rises from 0 to 1, so `H0` is flat after the last knot.
Each row may carry a frequency weight `w` (identical rows collapsed into one); the standard errors (`-H^-1`) are those
of frequency weights, not of sampling weights.
"""
from dataclasses import dataclass
import numpy as np
from scipy.interpolate import BSpline
from scipy.optimize import minimize
from scipy.special import expit
@@ -38,6 +48,71 @@ def weibull_survival(t, log_scale, log_shape, beta, Z):
return survival
def ispline_basis(t, order: int, knots) -> np.ndarray:
"""(len(t) x (len(knots) + order - 2)) I-spline basis: `I_j(t) = sum_{m >= j} B_m(t)`, the B-splines of degree
`order` on `knots` with repeated boundaries. Equals PIMixture's `Ispline(t, order, knots)`, transposed."""
t, knots = np.asarray(t, dtype=float), np.asarray(knots, dtype=float)
full = np.r_[np.repeat(knots[0], order + 1), knots[1:-1], np.repeat(knots[-1], order + 1)]
inside = np.clip(np.nan_to_num(t, posinf=knots[-1]), knots[0], knots[-1])
bsplines = BSpline.design_matrix(inside, full, order, extrapolate=False).toarray()
basis = np.cumsum(bsplines[:, ::-1], axis=1)[:, ::-1][:, 1:]
basis[t >= knots[-1]] = 1.0
basis[t <= knots[0]] = 0.0
return basis
def quantile_knots(l, r, n_knots: int) -> tuple[float, ...]:
"""PIMixture's knots: quantiles of the unique observed times, the `l` (zeros included) and the finite `r`."""
l, r = np.asarray(l, dtype=float), np.asarray(r, dtype=float)
times = np.unique(np.r_[l, r[np.isfinite(r)]])
return tuple(float(k) for k in np.quantile(times, np.linspace(0, 1, n_knots)))
@dataclass(frozen=True)
class Weibull:
"""`H0(t) = (t / scale) ** shape`; params `[log_scale, log_shape]`."""
n_params = 2
def cumulative_hazard(self, t, params):
with np.errstate(over="ignore", invalid="ignore"):
return (np.asarray(t, dtype=float) / np.exp(params[0])) ** np.exp(params[1])
def start(self, c, l, r):
return np.array([_starting_log_scale(c, l, r), 0.0])
@dataclass(frozen=True)
class ISpline:
"""`H0(t) = sum_j exp(gamma_j) I_j(t)`; params `gamma`, one per basis function."""
knots: tuple[float, ...]
order: int = 3
@property
def n_params(self):
return len(self.knots) + self.order - 2
def cumulative_hazard(self, t, params):
return ispline_basis(t, self.order, self.knots) @ np.exp(params)
def start(self, c, l, r):
"""The exponential start's `H0` at the last knot, shared equally among the basis functions."""
rate = np.exp(-_starting_log_scale(c, l, r))
return np.full(self.n_params, np.log(max(rate * self.knots[-1], 1e-6) / self.n_params))
WEIBULL = Weibull()
def survival(t, baseline_params, beta, Z, baseline=WEIBULL):
"""S(t) for any baseline family. S(0) = 1 and S(inf) = 0."""
t = np.asarray(t, dtype=float)
with np.errstate(over="ignore", invalid="ignore"):
cumulative = baseline.cumulative_hazard(t, baseline_params) * np.exp(Z @ beta)
found = np.exp(-cumulative)
found = np.where(t <= 0, 1.0, found)
return np.where(np.isinf(t), 0.0, found)
def split_params(params, n_x, n_z):
"""params = [theta (n_x), beta (n_z), log_scale, log_shape]."""
theta = params[:n_x]
@@ -47,24 +122,25 @@ def split_params(params, n_x, n_z):
return theta, beta, log_scale, log_shape
def neg_loglik(params, c, l, r, X, Z):
theta, beta, log_scale, log_shape = split_params(params, X.shape[1], Z.shape[1])
def neg_loglik(params, c, l, r, X, Z, baseline=WEIBULL, w=None):
n_x, n_z = X.shape[1], Z.shape[1]
theta, beta, rest = params[:n_x], params[n_x:n_x + n_z], params[n_x + n_z:]
w = np.ones(len(c)) if w is None else np.asarray(w, dtype=float)
pi = prevalence(theta, X)
interval = weibull_survival(l, log_scale, log_shape, beta, Z) - weibull_survival(r, log_scale, log_shape, beta, Z)
interval = survival(l, rest, beta, Z, baseline) - survival(r, rest, beta, Z, baseline)
interval = np.maximum(interval, TINY)
total = 0.0
row = np.zeros(len(c))
prevalent = c == 1
total += np.sum(np.log(pi[prevalent] + TINY))
row[prevalent] = np.log(pi[prevalent] + TINY)
not_prevalent = c == 0
total += np.sum(np.log(1 - pi[not_prevalent] + TINY))
total += np.sum(np.log(interval[not_prevalent]))
row[not_prevalent] = np.log(1 - pi[not_prevalent] + TINY) + np.log(interval[not_prevalent])
unknown = c == UNKNOWN
total += np.sum(np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY))
row[unknown] = np.log(pi[unknown] + (1 - pi[unknown]) * interval[unknown] + TINY)
return -total
return -np.sum(w * row)
def numerical_hessian(f, x, step=1e-4):
@@ -109,25 +185,26 @@ def _starting_theta(c, X, ridge=1e-3):
return minimize(loss, np.zeros(X.shape[1]), method="BFGS").x
def fit(c, l, r, X, Z):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors."""
def fit(c, l, r, X, Z, baseline=WEIBULL, w=None):
"""Maximum likelihood with scipy. Returns a dict with the estimates and their Wald standard errors; with the
Weibull also `log_scale` and `log_shape`."""
c, l, r = np.asarray(c), np.asarray(l, dtype=float), np.asarray(r, dtype=float)
X, Z = np.asarray(X, dtype=float), np.asarray(Z, dtype=float)
n_x, n_z = X.shape[1], Z.shape[1]
# Two starts, the better optimum kept: the likelihood of a rare outcome has poor local optima (all the risk put in
# the prevalence and none in the incidence, or the other way round).
log_scale = _starting_log_scale(c, l, r)
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), log_scale, 0.0],
np.r_[np.zeros(n_x), np.zeros(n_z), log_scale, 0.0]]
results = [minimize(neg_loglik, s, args=(c, l, r, X, Z), method="BFGS") for s in starts]
start = baseline.start(c, l, r)
starts = [np.r_[_starting_theta(c, X), np.zeros(n_z), start], np.r_[np.zeros(n_x), np.zeros(n_z), start]]
args = (c, l, r, X, Z, baseline, w)
results = [minimize(neg_loglik, s, args=args, method="BFGS") for s in starts]
result = min(results, key=lambda res: res.fun if np.isfinite(res.fun) else np.inf)
theta, beta, log_scale, log_shape = split_params(result.x, n_x, n_z)
theta, beta, rest = result.x[:n_x], result.x[n_x:n_x + n_z], result.x[n_x + n_z:]
# BFGS's own hess_inv is a rough approximation: the standard errors come from a finite-difference Hessian.
# A coefficient that ran off to the boundary (e.g. a group with no prevalent case: logit → −inf) has a flat
# likelihood, a zero row in the Hessian, and makes the whole matrix singular. It gets no standard error (NaN) and
# the others are computed without it.
hessian = numerical_hessian(lambda p: neg_loglik(p, c, l, r, X, Z), result.x)
hessian = numerical_hessian(lambda p: neg_loglik(p, *args), result.x)
free = np.abs(result.x) < BOUNDARY
standard_errors = np.full(len(result.x), np.nan)
covariance = np.full((len(result.x), len(result.x)), np.nan)
@@ -137,11 +214,11 @@ def fit(c, l, r, X, Z):
standard_errors[free] = np.sqrt(np.where(variances > 0, variances, np.nan))
except np.linalg.LinAlgError:
pass
return {
found = {
"theta": theta,
"beta": beta,
"log_scale": log_scale,
"log_shape": log_shape,
"baseline": baseline,
"baseline_params": rest,
"params": result.x,
"se": standard_errors,
"covariance": covariance,
@@ -152,14 +229,19 @@ def fit(c, l, r, X, Z):
"converged": bool(np.max(np.abs(result.jac[free]), initial=0.0) < 1e-3),
"message": result.message,
}
if isinstance(baseline, Weibull):
found["log_scale"], found["log_shape"] = float(rest[0]), float(rest[1])
return found
def cumulative_risk(fitted, X, Z, years):
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence."""
"""CR(t) = pi + (1 - pi) * (1 - S(t)), one column per horizon. Column t = 0 is the prevalence. A `fitted` without
`baseline` (built by hand) is a Weibull with `log_scale` and `log_shape`."""
pi = prevalence(fitted["theta"], X)
columns = []
for t in years:
survival = weibull_survival(np.full(len(X), float(t)), fitted["log_scale"], fitted["log_shape"],
fitted["beta"], Z)
columns.append(pi + (1 - pi) * (1 - survival))
baseline = fitted.get("baseline", WEIBULL)
rest = fitted.get("baseline_params")
if rest is None:
rest = np.array([fitted["log_scale"], fitted["log_shape"]])
columns = [pi + (1 - pi) * (1 - survival(np.full(len(X), float(t)), rest, fitted["beta"], Z, baseline))
for t in years]
return np.column_stack(columns)
+153 -33
View File
@@ -15,7 +15,8 @@ Follow-up without a test isn't counted: a member is free only as far as her last
`PrevalenceIncidenceMixture` is a scikit-learn estimator: `fit(X, y)` with the members' features and their `c`, `l`,
`r`; `predict_proba(X)` gives the cumulative risk at each horizon, CR(t) = π + (1 − π)(1 − S(t)), with the prevalence
π logistic in every feature and the incidence S(t) Weibull with proportional hazards in `incidence_features`.
π logistic in every feature (KPNC's cytology categories as indicators) and the incidence S(t) with proportional
hazards in `incidence_features` over a Weibull or I-spline baseline (`incidence`), one mixture per stratum (`strata`).
`fitted_model` puts `IndexResults` in front of it, so the registered model is one `Pipeline` that takes a build's long
frame. Settings arrive as config (`model.toml`), the cohort through a loader, and registering is the
driver's saver (`models.dags.training`).
@@ -34,7 +35,17 @@ from models.cacu.cin2_pim import likelihood
from models.io.contracts import DAYS_PER_YEAR
from models.steps import model_fitting
FEATURES = ["abnormal_cytology", "hpv_positive"]
FEATURES = ["cytology", "hpv_positive"]
def _features(history: dict) -> list[str]:
"""The model's features: the index results', and the history's one if the scenario has a history."""
return FEATURES + ([history["feature"]] if history else [])
def _levels(cytology: dict, history: dict) -> dict:
"""The levels of each categorical feature, the reference first."""
return {"cytology": list(cytology), **({history["feature"]: list(history["levels"])} if history else {})}
INTERVAL_CODED = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"c": pandera.Column(int, pandera.Check.isin([1, 0, likelihood.UNKNOWN])),
@@ -48,15 +59,50 @@ def _days(cohort: pd.DataFrame) -> pd.Series:
return (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
def index_results(cohort: pd.DataFrame, index_sample_days: int) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first Bethesda and HPV results within `index_sample_days` of the
index date, and the features taken from them."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "vph"])]
def _most_severe(codes: pd.Series, cytology: dict) -> pd.Series:
"""Per `pac_id` (the index of `codes`), the most severe of `cytology`'s categories among the codes; None if none."""
severity = {code: rank for rank, values in enumerate(cytology.values()) for code in values}
ranks = codes.map(severity).groupby(level=0).max()
names = list(cytology)
return pd.Series([None if np.isnan(rank) else names[int(rank)] for rank in ranks], index=ranks.index,
dtype=object)
def _history(cohort: pd.DataFrame, members: pd.DataFrame, cytology: dict, history: dict) -> pd.Series:
"""The history feature: the grade of the results in the `lookback_days` up to the member's first `event` (KPNC's
referral before the colposcopy). `high` if a category of `high`; else `low` if one of `low`, or of
`low_if_hpv_positive` with a positive HPV; else None (no referral result, or one that wouldn't refer)."""
event = cohort[cohort["tipo"] == history["event"]].groupby("pac_id")["fecha"].min()
timed = cohort.assign(event=cohort["pac_id"].map(event))
before = (pd.to_datetime(timed["event"]) - pd.to_datetime(timed["fecha"])).dt.days
near = timed[before.between(0, history["lookback_days"])]
results = near[near["tipo"].isin(["bethesda", "glandular"])].set_index("pac_id")["valor_codigo"]
worst = pd.Series(_most_severe(results, cytology).reindex(members["pac_id"]).to_numpy(), index=members.index)
hpv = near[(near["tipo"] == "vph") & (near["valor_codigo"] == "POSITIVO")]["pac_id"].unique()
positive = members["pac_id"].isin(hpv).to_numpy()
grade = np.where(worst.isin(history["high"]), "high",
np.where(worst.isin(history["low"]) | (worst.isin(history["low_if_hpv_positive"]) & positive),
"low", None))
return pd.Series(grade, index=members.index, dtype=object)
def index_results(cohort: pd.DataFrame, index_sample_days: int, cytology: dict, history: dict | None = None) -> pd.DataFrame:
"""One row per member, in `pac_id` order: the first squamous (Bethesda), glandular and HPV results within
`index_sample_days` of the index date, and the features taken from them. `cytology` maps KPNC's categories, from
least to most severe, to the codes of either result; with both results the more severe category wins, and a
member with neither, or with codes in no category, gets None. With a `history`, its feature too (`_history`)."""
near = cohort[_days(cohort).between(0, index_sample_days) & cohort["tipo"].isin(["bethesda", "glandular", "vph"])]
wide = near.sort_values("fecha").pivot_table(index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
members = cohort.groupby("pac_id", as_index=False)["fecha_indice"].first()
members = members.merge(wide.reindex(columns=["bethesda", "vph"]), left_on="pac_id", right_index=True, how="left")
members["abnormal_cytology"] = (members["bethesda"].notna() & (members["bethesda"] != "NORMAL")).astype(float)
members = members.merge(wide.reindex(columns=["bethesda", "glandular", "vph"]), left_on="pac_id", right_index=True,
how="left")
codes = members.set_index("pac_id")[["bethesda", "glandular"]].stack()
found = _most_severe(codes, cytology).reindex(members["pac_id"]).tolist()
members["cytology"] = pd.Series([v if isinstance(v, str) else None for v in found], index=members.index,
dtype=object)
members["hpv_positive"] = (members["vph"] == "POSITIVO").astype(float)
if history:
members[history["feature"]] = _history(cohort, members, cytology, history)
return members
@@ -81,7 +127,7 @@ def _negative_days(cohort: pd.DataFrame, days: pd.Series, event_grades: list[str
@checked_frame(INTERVAL_CODED)
def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], prevalent_window_months: int,
index_sample_days: int, known_negative: dict) -> pd.DataFrame:
index_sample_days: int, known_negative: dict, cytology: dict, history: dict) -> pd.DataFrame:
"""Each member's features with `c`, `l` and `r` (see the module's docstring)."""
days = _days(cohort)
window = prevalent_window_months * DAYS_PER_YEAR / 12
@@ -91,7 +137,7 @@ def interval_coded_members(cohort: pd.DataFrame, event_grades: list[str], preval
before_event = ~(negatives["days"] >= negatives["pac_id"].map(first_event))
last_negative = negatives[before_event].groupby("pac_id")["days"].max()
coded = index_results(cohort, index_sample_days)
coded = index_results(cohort, index_sample_days, cytology, history)
event_days, free_until = coded["pac_id"].map(first_event), coded["pac_id"].map(last_negative)
prevalent = event_days <= window
found_free = free_until.notna() & ~prevalent
@@ -110,37 +156,107 @@ def train_test_split(interval_coded_members: pd.DataFrame, train_fraction: float
class PrevalenceIncidenceMixture(BaseEstimator):
"""Logistic prevalence and Weibull incidence fitted by maximum likelihood (`likelihood.fit`)."""
"""Logistic prevalence and proportional-hazards incidence fitted by maximum likelihood (`likelihood.fit`).
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",)):
`incidence` picks the baseline: `{"family": "weibull"}` or `{"family": "ispline", "knots": k, "order": o}`, with
`k` knots at quantiles of each stratum's observed times (PIMixture's weakly-parametric model). With `strata`, one
mixture per combination of their values, as in Cheung et al. 2020 (stratified by HPV, cytology as covariate): the
strata leave both designs and a member of a stratum not seen in training gets NaN. A feature listed in `levels`
is categorical: one indicator per level but the first (the reference), keeping in each stratum only the levels
seen in its training; a member of a level not seen there, or of none, gets NaN and is left out of the fit.
Identical rows are collapsed into frequency weights, which `sample_weight` multiplies.
"""
def __init__(self, horizons_years=(0.0, 1.0, 3.0, 5.0), incidence_features=("hpv_positive",), strata=(),
incidence=None, levels=None):
self.horizons_years = horizons_years
self.incidence_features = incidence_features
self.strata = strata
self.incidence = incidence
self.levels = levels
def _design(self, X: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), X.to_numpy(dtype=float)])
return prevalence, X[list(self.incidence_features)].to_numpy(dtype=float)
def _baseline(self, y: pd.DataFrame):
settings = dict(self.incidence or {"family": "weibull"})
family = settings.pop("family")
if family == "weibull":
return likelihood.WEIBULL
if family == "ispline":
return likelihood.ISpline(likelihood.quantile_knots(y["l"], y["r"], settings["knots"]),
settings.get("order", 3))
raise ValueError(f"unknown incidence family {family!r}")
def fit(self, X: pd.DataFrame, y: pd.DataFrame):
prevalence, incidence = self._design(X)
found = likelihood.fit(y["c"], y["l"], y["r"], prevalence, incidence)
self.theta_, self.beta_ = found["theta"], found["beta"]
self.log_scale_, self.log_shape_ = float(found["log_scale"]), float(found["log_shape"])
self.standard_errors_, self.neg_loglik_, self.converged_ = found["se"], found["neg_loglik"], found["converged"]
def _seen(self, X: pd.DataFrame) -> dict:
"""Each categorical feature's levels present in `X`, in `levels`' order."""
return {f: [v for v in values if (X[f] == v).any()] for f, values in (self.levels or {}).items()
if f in X.columns and f not in self.strata}
def _placed(self, X: pd.DataFrame, seen: dict) -> np.ndarray:
"""Rows whose categorical features take a level in `seen`."""
return np.all([X[f].isin(values).to_numpy() for f, values in seen.items()], axis=0) if seen \
else np.ones(len(X), dtype=bool)
def _columns(self, X: pd.DataFrame, features, seen: dict) -> np.ndarray:
columns = []
for f in features:
if f in self.strata:
continue
if f in seen:
columns += [(X[f] == v).to_numpy(dtype=float) for v in seen[f][1:]]
else:
columns.append(X[f].to_numpy(dtype=float))
return np.column_stack(columns) if columns else np.zeros((len(X), 0))
def _design(self, X: pd.DataFrame, seen: dict) -> tuple[np.ndarray, np.ndarray]:
prevalence = np.column_stack([np.ones(len(X)), self._columns(X, X.columns, seen)])
return prevalence, self._columns(X, self.incidence_features, seen)
def _groups(self, X: pd.DataFrame):
if not self.strata:
return [((), np.arange(len(X)))]
return [(key if isinstance(key, tuple) else (key,), rows)
for key, rows in X.groupby(list(self.strata), sort=True).indices.items()]
def fit(self, X: pd.DataFrame, y: pd.DataFrame, sample_weight=None):
rows = pd.concat([X.reset_index(drop=True), y[["c", "l", "r"]].reset_index(drop=True)], axis=1)
rows["w"] = 1.0 if sample_weight is None else np.asarray(sample_weight, dtype=float)
self.fits_, self.seen_ = {}, {}
for key, index in self._groups(X):
group = rows.iloc[index]
seen = self._seen(group)
group = group[self._placed(group, seen)].groupby([*X.columns, "c", "l", "r"], as_index=False)["w"].sum()
prevalence, incidence = self._design(group[X.columns], seen)
self.seen_[key] = seen
self.fits_[key] = likelihood.fit(group["c"].to_numpy(), group["l"].to_numpy(), group["r"].to_numpy(),
prevalence, incidence, self._baseline(group), group["w"].to_numpy())
self.neg_loglik_ = float(sum(f["neg_loglik"] for f in self.fits_.values()))
self.converged_ = all(f["converged"] for f in self.fits_.values())
return self
def predict_proba(self, X: pd.DataFrame) -> np.ndarray:
"""One column per horizon: CR(t). The column of t = 0 is the prevalence."""
prevalence, incidence = self._design(X)
fitted = {"theta": self.theta_, "beta": self.beta_, "log_scale": self.log_scale_, "log_shape": self.log_shape_}
return likelihood.cumulative_risk(fitted, prevalence, incidence, self.horizons_years)
risks = np.full((len(X), len(self.horizons_years)), np.nan)
for key, index in self._groups(X):
if key not in self.fits_:
continue
members = X.iloc[index]
placed = self._placed(members, self.seen_[key])
prevalence, incidence = self._design(members[placed], self.seen_[key])
risks[index[placed]] = likelihood.cumulative_risk(self.fits_[key], prevalence, incidence,
self.horizons_years)
return risks
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float]) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years).fit(train_set[FEATURES], train_set[["c", "l", "r"]])
def fitted_mixture(train_set: pd.DataFrame, horizons_years: list[float], incidence: dict,
incidence_features: list[str], strata: list[str], cytology: dict,
history: dict) -> PrevalenceIncidenceMixture:
return PrevalenceIncidenceMixture(horizons_years, tuple(incidence_features), tuple(strata), incidence,
_levels(cytology, history)).fit(train_set[_features(history)],
train_set[["c", "l", "r"]])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[FEATURES])
def test_cumulative_risks(fitted_mixture: PrevalenceIncidenceMixture, test_set: pd.DataFrame,
history: dict) -> np.ndarray:
return fitted_mixture.predict_proba(test_set[_features(history)])
def _status_at(members: pd.DataFrame, horizon: float) -> np.ndarray:
@@ -158,7 +274,7 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
"converged": float(fitted_mixture.converged_)}
for column, horizon in enumerate(horizons_years):
status = _status_at(test_set, horizon)
known = ~np.isnan(status)
known = ~np.isnan(status) & ~np.isnan(test_cumulative_risks[:, column]) # NaN: a stratum unseen in training
y, p = status[known], test_cumulative_risks[known, column]
tag = f"{horizon:g}y"
found[f"n_known_{tag}"] = int(known.sum())
@@ -174,16 +290,20 @@ def metrics(fitted_mixture: PrevalenceIncidenceMixture, train_set: pd.DataFrame,
class IndexResults(TransformerMixin, BaseEstimator):
"""A build's long frame to the features of each member, in `pac_id` order. Learns nothing."""
def __init__(self, index_sample_days: int = 30):
def __init__(self, index_sample_days: int = 30, cytology=None, history=None):
self.index_sample_days = index_sample_days
self.cytology = cytology
self.history = history
def fit(self, X, y=None):
return self
def transform(self, X: pd.DataFrame) -> pd.DataFrame:
return index_results(X, self.index_sample_days)[FEATURES]
return index_results(X, self.index_sample_days, self.cytology, self.history)[_features(self.history)]
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int) -> Pipeline:
def fitted_model(fitted_mixture: PrevalenceIncidenceMixture, index_sample_days: int, cytology: dict,
history: dict) -> Pipeline:
"""What's registered: the fitted mixture behind `IndexResults`."""
return Pipeline([("index_results", IndexResults(index_sample_days)), ("mixture", fitted_mixture)])
return Pipeline([("index_results", IndexResults(index_sample_days, cytology, history)),
("mixture", fitted_mixture)])
+23 -1
View File
@@ -8,7 +8,8 @@ requirements = ["scikit-learn", "numpy", "pandas", "scipy", "cloudpickle"]
modules = ["models.cacu.cin2_pim.model"]
description = """
Prototipo: riesgo acumulado de CIN2+ (biopsia LIEAG, CIS o carcinoma) en la visita índice y a 1, 3 y 5 años, con un \
modelo de mezcla prevalencia (logística) e incidencia (Weibull) a partir de la citología y el VPH índice. Sin \
modelo de mezcla prevalencia (logística) e incidencia (I-splines de PIMixture) estratificado por el VPH índice, con la \
citología índice en las categorías de KPNC como covariable (Cheung et al. 2020). Sin \
corrección del sesgo de verificación ni validación clínica."""
# The dataflow's config (`with_config`); each key is an input of the nodes that name it.
@@ -23,3 +24,24 @@ index_sample_days = 30
# The results that make a visit free of CIN2+ without a biopsy: every key with one of its values (KPNC: HPV-negative
# with NILM or ASC-US; Cheung et al. 2020, doi:10.1097/LGT.0000000000000528).
known_negative = { bethesda = ["NORMAL", "ASC-US"], vph = ["NEGATIVO"] }
# The incidence's baseline cumulative hazard: { family = "weibull" }, or PIMixture's weakly-parametric
# { family = "ispline", knots = k, order = o }, with k knots at quantiles of each stratum's observed times. The
# finite times are whole years 1-5, so a basis of more than 5 functions (knots + order - 2) isn't identifiable. KPNC
# table 1 is exactly order 4 with 3 knots (bayes-pim, chapter 6).
incidence = { family = "ispline", knots = 3, order = 4 }
# One mixture per value of these features; the other features enter the prevalence, and those listed here the
# incidence. KPNC: stratified by HPV, cytology as covariate (Cheung et al. 2020).
strata = ["hpv_positive"]
incidence_features = ["cytology"]
# A feature of the member's history before the index (e.g. the referral before a colposcopy); none in surveillance.
history = {}
# KPNC's index cytology categories, from least to most severe, and the codes of each from the squamous (Bethesda) and
# the glandular result; the first is the reference. With both results the more severe category wins. Adenocarcinoma
# has no KPNC row: it goes with the high-grade and malignant results.
[config.cytology]
NILM = ["NORMAL"]
ASC-US = ["ASC-US"]
LSIL = ["LIEBG"]
ASC-H = ["ASC-H"]
AGC = ["AGC"]
"HSIL+" = ["LIEAG", "CIS", "ADENOCARCINOMA"]
+40 -3
View File
@@ -48,7 +48,8 @@ def _member(pac_id, index, bethesda, vph, biopsies=(), visits=()):
def _coded(rows):
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
coded = model.interval_coded_members(frame, CONFIG["event_grades"], CONFIG["prevalent_window_months"],
CONFIG["index_sample_days"], CONFIG["known_negative"])
CONFIG["index_sample_days"], CONFIG["known_negative"], CONFIG["cytology"],
CONFIG["history"])
return tuple(coded.iloc[0][["c", "l", "r"]])
@@ -154,8 +155,9 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
or a module added to the driver rewires a parameter."""
required, optional = training.external_inputs(training.dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"cohort", "event_grades", "horizons_years", "index_sample_days",
"known_negative", "prevalent_window_months", "train_fraction"}
assert required == {"cohort", "cytology", "event_grades", "history", "horizons_years", "incidence",
"incidence_features", "index_sample_days", "known_negative", "prevalent_window_months", "strata",
"train_fraction"}
assert optional == set()
@@ -194,3 +196,38 @@ def test_training_and_estimating_score_every_member_at_every_horizon(cohort_file
inside = mlflow.pyfunc.load_model(uri).predict(pd.read_parquet(cohort_file))
assert outside.shape == (300, len(CONFIG["horizons_years"]))
np.testing.assert_allclose(outside.to_numpy(), inside)
def test_each_stratum_gets_its_own_mixture_and_an_unseen_one_gets_no_risk(cohort_frame):
"""Pins down the stratification of the TOML: one fit per HPV value, each predicting only its own members, and NaN
(not another stratum's risk) for a value absent from training. Fails if the strata are pooled or mixed up."""
members = training.dataflow(*SCENARIO.modules, config=CONFIG).execute(
["interval_coded_members"], inputs={"cohort": cohort_frame})["interval_coded_members"]
only_negative = members[members["hpv_positive"] == 0]
mixture = model.PrevalenceIncidenceMixture(CONFIG["horizons_years"], ("cytology",), ("hpv_positive",),
CONFIG["incidence"], {"cytology": list(CONFIG["cytology"])}).fit(
only_negative[model.FEATURES], only_negative[["c", "l", "r"]])
risks = mixture.predict_proba(members[model.FEATURES])
assert list(mixture.fits_) == [(0,)]
assert np.isnan(risks[members["hpv_positive"].to_numpy() == 1]).all()
assert not np.isnan(risks[members["hpv_positive"].to_numpy() == 0]).any()
def test_the_index_cytology_takes_kpncs_categories_not_a_binary():
"""Pins down the cytology of the TOML: each squamous or glandular code goes to its KPNC category (LIEBG is LSIL;
CIS and adenocarcinoma are HSIL+), with both results the more severe wins (AGC over ASC-US, HSIL+ over AGC), and a
member without a cytology gets none rather than the reference. Fails if the categories collapse back to
normal/abnormal, the glandular result is ignored, or a missing cytology is read as NILM."""
rows = [*_member(1, INDEX, "LIEBG", "POSITIVO"), *_member(2, INDEX, "CIS", "NEGATIVO"),
*_member(3, INDEX, "NORMAL", "NEGATIVO"), *_member(4, INDEX, "ASC-US", "POSITIVO"),
*_member(5, INDEX, "LIEAG", "POSITIVO"), *_member(6, INDEX, "NORMAL", "POSITIVO")]
glandular = [(4, "AGC"), (5, "AGC"), (6, "ADENOCARCINOMA")]
rows += [_row(pac_id, INDEX, 7, "glandular", code) for pac_id, code in glandular]
frame = pd.DataFrame(rows, columns=COHORT_SCHEMA.names)
frame = frame[~((frame["pac_id"] == 3) & (frame["tipo"] == "bethesda"))]
found = model.index_results(frame, CONFIG["index_sample_days"], CONFIG["cytology"])
assert found["cytology"].tolist() == ["LSIL", "HSIL+", None, "AGC", "HSIL+", "HSIL+"]
+37
View File
@@ -80,3 +80,40 @@ def test_fit_finds_a_rare_incidence():
assert fitted["converged"] and fitted["neg_loglik"] <= truth + 1e-6
np.testing.assert_allclose(fitted["beta"], beta, atol=0.4)
assert np.all(np.isfinite(fitted["se"]))
def test_the_ispline_basis_rises_from_0_to_1_and_has_knots_plus_order_minus_2_functions():
"""Pins down PIMixture's basis: H0(0) = 0, flat at 1 from the last knot on, each function non-decreasing, and the
count PIMixture's `Ispline` gives. Fails if the basis stops starting at 0 (the bug that gave events at t = 1 zero
probability) or the count drifts from PIMixture's."""
knots = (0.0, 2.0, 5.0)
t = np.linspace(0, 8, 81)
basis = L.ispline_basis(np.r_[t, np.inf], 3, knots)
assert basis.shape == (82, len(knots) + 3 - 2)
assert (basis[0] == 0).all() and (basis[:-1][t >= 5] == 1).all() and (basis[-1] == 1).all()
assert (np.diff(basis[:-1], axis=0) >= -1e-12).all()
def test_the_ispline_mixture_recovers_a_weibull_cumulative_risk():
"""Pins down that the weakly-parametric baseline fits data it wasn't generated from: the I-spline's cumulative
risk at 1 to 5 years is close to the Weibull truth. Fails if the I-spline's start or parameterization breaks."""
c, l, r, X, Z, theta, beta, scale, shape = simulate()
baseline = L.ISpline(L.quantile_knots(l, r, 3), order=3)
fitted = L.fit(c, l, r, X, Z, baseline)
years = [1.0, 3.0, 5.0]
truth = L.cumulative_risk({"theta": theta, "beta": beta, "log_scale": np.log(scale), "log_shape": np.log(shape)},
X[:2], Z[:2], years)
assert fitted["converged"]
np.testing.assert_allclose(L.cumulative_risk(fitted, X[:2], Z[:2], years), truth, atol=0.02)
def test_a_frequency_weight_is_the_same_as_repeating_the_row():
"""Pins down the weights: a row with weight 2 contributes as two identical rows, so collapsing duplicates
doesn't change the fit. Fails if the weights stop multiplying each row's log-likelihood."""
c, l, r, X, Z, *_ = simulate(n=300)
params = np.r_[-3.0, 1.5, 0.7, np.log(8.0), np.log(1.3)]
twice = L.neg_loglik(params, *(np.r_[a, a] for a in (c, l, r)), np.r_[X, X], np.r_[Z, Z])
assert L.neg_loglik(params, c, l, r, X, Z, w=np.full(len(c), 2.0)) == pytest.approx(twice)