CaCu's dummy model in its own folder

This commit is contained in:
2026-11-04 21:38:37 -06:00
parent 1f6e2df051
commit 37fb292a4f
9 changed files with 218 additions and 8 deletions
+96
View File
@@ -0,0 +1,96 @@
"""CaCu's dummy model: it tests the chain from a cohort build's file to a registered version.
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.
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
"""
import hashlib
import tomllib
from pathlib import Path
import mlflow.pyfunc
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from models.io.cohorts import cohort_lineage, read_cohort
from models.io.registry import registered_name
from models.io.training import TrainingRun
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
NORMAL = "NORMAL"
def cohort(cohort_path: str) -> pd.DataFrame:
return read_cohort(cohort_path)
def lineage(cohort_path: str) -> dict:
return cohort_lineage(cohort_path)
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 split(prepare: pd.DataFrame) -> dict:
"""The oldest index dates train and the newest test."""
ordered = prepare.sort_values(["fecha_indice", "pac_id"], kind="stable")
cut = int(len(ordered) * SETTINGS["train_fraction"])
return {"train": ordered.iloc[:cut], "test": ordered.iloc[cut:]}
def train(split: dict) -> pd.DataFrame:
return split["train"]
def test(split: dict) -> pd.DataFrame:
return split["test"]
def fit(train: pd.DataFrame) -> LogisticRegression:
return LogisticRegression().fit(train[["days"]], train["y"])
def predict(fit: LogisticRegression, 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")
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())}
class Cin2Logistic(mlflow.pyfunc.PythonModel):
"""The registered artifact: takes a build's long frame and returns each member's probability."""
def __init__(self, fitted: LogisticRegression):
self.fitted = fitted
def predict(self, context, model_input, params=None):
return predict(self.fitted, prepare(model_input))
def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, environment: str) -> str:
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content."""
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
cohorte_armado_id=int(lineage["armado_id"]))
run.log_model(Cin2Logistic(fit))
version = run.finish(metrics=evaluate, hyperparameters={
"cohort_file": str(cohort_path), "cohort_sha256": hashlib.sha256(Path(cohort_path).read_bytes()).hexdigest()})
name = registered_name(SETTINGS["domain"], SETTINGS["scenario"])
run.client.update_model_version(name, version, description=SETTINGS["description"])
return version
+7
View File
@@ -0,0 +1,7 @@
domain = "cacu"
scenario = "cin2_logistic"
cohort = "cacu/cohorte_vigilancia"
train_fraction = 0.7
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."""
+12
View File
@@ -0,0 +1,12 @@
"""The model's Hamilton driver."""
from hamilton import driver
from models.cacu.cin2_logistic import model
def train(cohort_path: str, environment: str = "DEV") -> str:
"""Trains on a build's file and returns the registered version."""
dr = driver.Builder().with_modules(model).build()
inputs = {"cohort_path": str(cohort_path), "environment": environment}
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
+6
View File
@@ -22,6 +22,12 @@ class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `SCHEMA`'s."""
def cohort_lineage(path: str | Path) -> dict[str, str]:
"""The lineage in the file's metadata, without reading any rows."""
metadata = pq.read_metadata(path).metadata
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
def read_cohort(path: str | Path) -> pd.DataFrame:
"""The build's rows, after checking the file's schema without reading them."""
schema = pq.read_schema(path)