CaCu CIN2+ prototype: a CIN2+ biopsy within a provisional 12-month window, predicted from the index sample's results

This commit is contained in:
2026-11-06 00:15:12 -06:00
parent f070d9f037
commit 22d1fda0f3
4 changed files with 159 additions and 66 deletions
+68 -25
View File
@@ -1,19 +1,25 @@
"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version.
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
No clinical meaning. `y` is 1 if any Bethesda result isn't `NORMAL`, and `days` runs from the index date to the first
abnormal result, or to the last result when `y` is 0. `days` is only known after the outcome, so the metrics say
nothing about performance.
`y` is 1 when a biopsy graded in `event_grades` falls within `outcome_window_months` of the index date. A member with
no such biopsy whose follow-up to the build's cut-off (`datos_as_of`) is shorter than the window isn't known yet:
it's scored but left out of training and evaluation. The predictors are the index sample's own results (Bethesda
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
nothing after them is used.
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
"""
import tomllib
from datetime import date
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from models.io.lineage import COHORT_SOURCE_TAG, cohort_reference, file_sha256
from models.io.registry import registry
@@ -21,7 +27,9 @@ from models.io.storage import read_cohort, read_metadata
from models.io.tracking import TrainingRun
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
NORMAL = "NORMAL"
PREDICTORS = ("bethesda", "vph", "vph_16_18")
MISSING = "(none)"
DAYS_PER_MONTH = 30.44
def cohort(cohort_path: str) -> pd.DataFrame:
@@ -42,16 +50,44 @@ def code_sha256() -> str:
return file_sha256(folder / "model.py", folder / "model.toml")
def prepare(cohort: pd.DataFrame) -> pd.DataFrame:
"""One row per member with a Bethesda result: `pac_id`, `fecha_indice`, `y`, `days`."""
results = cohort[cohort["tipo"] == "bethesda"].copy()
results["days"] = (pd.to_datetime(results["fecha"]) - pd.to_datetime(results["fecha_indice"])).dt.days
results["abnormal"] = results["valor_codigo"] != NORMAL
members = results.groupby(["pac_id", "fecha_indice"], as_index=False).agg(y=("abnormal", "any"), last=("days", "max"))
first_abnormal = results[results["abnormal"]].groupby("pac_id")["days"].min()
members["days"] = members["pac_id"].map(first_abnormal).fillna(members["last"]).astype(int)
members["y"] = members["y"].astype(int)
return members[["pac_id", "fecha_indice", "y", "days"]]
def cutoff(lineage: dict) -> date:
"""The build's cut-off: no event after it is in the file."""
return date.fromisoformat(lineage["datos_as_of"])
def predictors(cohort: pd.DataFrame) -> pd.DataFrame:
"""One row per member: `pac_id`, `fecha_indice` and the index sample's results, `(none)` where it has none."""
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
sample = cohort[(cohort["tipo"] == "citologia") & (cohort["fecha"] == cohort["fecha_indice"])]
sample = sample.groupby("pac_id")["fuente_id"].first().rename("sample")
results = cohort.merge(sample, left_on="pac_id", right_index=True)
results = results[results["fuente_id"] == results["sample"]]
genotype = results["tipo"] == "vph_genotipo_16_18"
results.loc[genotype, "valor_codigo"] = results.loc[genotype, "valor_numerico"].map({1.0: "POSITIVO", 0.0: "NEGATIVO"})
results["tipo"] = results["tipo"].replace({"vph_genotipo_16_18": "vph_16_18"})
wide = results[results["tipo"].isin(PREDICTORS)].pivot_table(
index="pac_id", columns="tipo", values="valor_codigo", aggfunc="first")
wide = wide.reindex(columns=list(PREDICTORS))
return members.merge(wide, left_on="pac_id", right_index=True, how="left").fillna(
{name: MISSING for name in PREDICTORS})
def outcome(cohort: pd.DataFrame, cutoff: date) -> pd.DataFrame:
"""One row per member: `y`, and `known`, whether the window is complete or the event already happened."""
window = SETTINGS["outcome_window_months"] * DAYS_PER_MONTH
days = (pd.to_datetime(cohort["fecha"]) - pd.to_datetime(cohort["fecha_indice"])).dt.days
event = (cohort["tipo"] == "biopsia") & cohort["valor_codigo"].isin(SETTINGS["event_grades"]) & days.between(0, window)
members = cohort.groupby(["pac_id", "fecha_indice"], as_index=False).size()[["pac_id", "fecha_indice"]]
members["y"] = members["pac_id"].isin(cohort.loc[event, "pac_id"]).astype(int)
follow_up = (pd.Timestamp(cutoff) - pd.to_datetime(members["fecha_indice"])).dt.days
members["known"] = (members["y"] == 1) | (follow_up >= window)
return members[["pac_id", "y", "known"]]
def prepare(predictors: pd.DataFrame, outcome: pd.DataFrame) -> pd.DataFrame:
"""The members whose outcome is known, with their predictors and `y`."""
labelled = predictors.merge(outcome, on="pac_id")
return labelled[labelled["known"]].drop(columns="known").reset_index(drop=True)
def split(prepare: pd.DataFrame) -> dict:
@@ -69,33 +105,38 @@ def test(split: dict) -> pd.DataFrame:
return split["test"]
def fit(train: pd.DataFrame) -> LogisticRegression:
return LogisticRegression().fit(train[["days"]], train["y"])
def fit(train: pd.DataFrame) -> Pipeline:
"""One-hot predictors, an unseen category counted as none of the known ones, and a logistic regression."""
encode = ColumnTransformer([("results", OneHotEncoder(handle_unknown="ignore"), list(PREDICTORS))])
return Pipeline([("encode", encode), ("logistic", LogisticRegression(max_iter=1000))]).fit(
train[list(PREDICTORS)], train["y"])
def predict(fit: LogisticRegression, test: pd.DataFrame) -> pd.Series:
def predict(fit: Pipeline, test: pd.DataFrame) -> pd.Series:
"""The probability of `y` for each row of `test`."""
return pd.Series(fit.predict_proba(test[["days"]])[:, 1], index=test.index, name="probabilidad")
return pd.Series(fit.predict_proba(test[list(PREDICTORS)])[:, 1], index=test.index, name="probabilidad")
def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dict:
"""Aggregates only: no patient data reaches MLflow."""
return {"auc": float(roc_auc_score(test["y"], predict)), "brier": float(brier_score_loss(test["y"], predict)),
"n_train": len(train), "n_test": len(test), "positive_rate_test": float(test["y"].mean())}
"n_train": len(train), "n_test": len(test), "positive_rate_train": float(train["y"].mean()),
"positive_rate_test": float(test["y"].mean()), "mean_probability_test": float(predict.mean())}
class Cin2Logistic(mlflow.pyfunc.PythonModel):
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`."""
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`
for every member, whether their outcome is known or not."""
def __init__(self, fitted: LogisticRegression):
def __init__(self, fitted: Pipeline):
self.fitted = fitted
def predict(self, context, model_input, params=None):
members = prepare(model_input)
members = predictors(model_input)
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str,
def registered_model(fit: Pipeline, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str,
code_sha256: str, environment: str) -> str:
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content,
and which build it is, from the kit or from dbt's rules."""
@@ -105,7 +146,9 @@ def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, coh
cohorte_armado_id=armado_id, cohort=cohort)
run.log_model(Cin2Logistic(fit))
run.finish(metrics=evaluate, hyperparameters={
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256})
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256,
"outcome_window_months": SETTINGS["outcome_window_months"], "event_grades": ",".join(SETTINGS["event_grades"]),
"horizon_years": SETTINGS["outcome_window_months"] / 12})
version = registry.register_run(run)
registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"])
return version
+8 -2
View File
@@ -2,6 +2,12 @@ domain = "cacu"
scenario = "cin2_logistic"
cohort = "cacu/cohorte_vigilancia"
train_fraction = 0.7
# Provisional, to be decided with the domain expert: the window in which a CIN2+ biopsy counts as the outcome. On the
# DEV simulated data (cut-off 2026-12-31, index dates from late 2024) a 24-month window leaves no member with a
# complete window; 12 months leaves 5,231 known members, 162 with the event.
outcome_window_months = 12
event_grades = ["LIEAG", "CIS", "CARCINOMA"]
description = """
Modelo de prueba de la cadena de entrenamiento, sin significado clínico. Los días se conocen solo después del \
desenlace, así que sus métricas no dicen nada sobre su desempeño."""
Prototipo: probabilidad de CIN2+ (biopsia LIEAG, CIS o carcinoma) en los 12 meses siguientes a la citología índice, \
a partir de los resultados de esa muestra (Bethesda, VPH, VPH 16/18). La ventana es provisional y el modelo no tiene \
validación clínica."""