|
|
|
@@ -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
|