155 lines
7.5 KiB
Python
155 lines
7.5 KiB
Python
"""CaCu CIN2+ prototype: the risk of CIN2+ on a biopsy within a window after the index cytology.
|
|
|
|
`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
|
|
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())
|
|
PREDICTORS = ("bethesda", "vph", "vph_16_18")
|
|
MISSING = "(none)"
|
|
DAYS_PER_MONTH = 30.44
|
|
|
|
|
|
def cohort(cohort_path: str) -> pd.DataFrame:
|
|
return read_cohort(cohort_path)
|
|
|
|
|
|
def lineage(cohort_path: str) -> dict:
|
|
return read_metadata(cohort_path)
|
|
|
|
|
|
def cohort_sha256(cohort_path: str) -> str:
|
|
return file_sha256(cohort_path)
|
|
|
|
|
|
def code_sha256() -> str:
|
|
"""The hash of this folder's steps and settings: what says the model itself changed."""
|
|
folder = Path(__file__).parent
|
|
return file_sha256(folder / "model.py", folder / "model.toml")
|
|
|
|
|
|
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:
|
|
"""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) -> 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: Pipeline, test: pd.DataFrame) -> pd.Series:
|
|
"""The probability of `y` for each row of `test`."""
|
|
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_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`
|
|
for every member, whether their outcome is known or not."""
|
|
|
|
def __init__(self, fitted: Pipeline):
|
|
self.fitted = fitted
|
|
|
|
def predict(self, context, model_input, params=None):
|
|
members = predictors(model_input)
|
|
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
|
|
|
|
|
|
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."""
|
|
cohort = cohort_reference(lineage, cohort_sha256)
|
|
armado_id = int(lineage["armado_id"]) if cohort[COHORT_SOURCE_TAG] == "kit" else None
|
|
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
|
|
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,
|
|
"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
|