|
|
|
@@ -0,0 +1,187 @@
|
|
|
|
|
"""Prueba de concepto: un modelo de riesgo de CIN2+ con MLflow, de `toy-model/riesgo_juguete.py`.
|
|
|
|
|
|
|
|
|
|
Entrena una logística sobre el marco de `cacu/cohorte_vigilancia`, la registra en MLflow
|
|
|
|
|
(`MLFLOW_TRACKING_URI`; en el despliegue, `http://<host>:9705`) y la sirve a la arista `estimar` con
|
|
|
|
|
`EstimadorMlflow`, que cumple `EstimadorDeRiesgo`. Lo corre Orquestacion:
|
|
|
|
|
|
|
|
|
|
uv run python -m orquestacion modelos entrenar [--horizonte 1] [--armado 3]
|
|
|
|
|
uv run python -m orquestacion ciclo cacu --desde 2025 --hasta 2025 --solo estimar --modelo cacu_cin2_mas --version 1
|
|
|
|
|
|
|
|
|
|
Sin pacientes en MLflow (ADR-MD-008): ni filas ni `input_example`. `ModeloCin2Mas` se serializa por
|
|
|
|
|
referencia a este módulo: cargarlo pide `models` instalado.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import hashlib
|
|
|
|
|
import tempfile
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
|
|
import mlflow
|
|
|
|
|
import numpy as np
|
|
|
|
|
import pandas as pd
|
|
|
|
|
from mlflow.models import ModelSignature
|
|
|
|
|
from mlflow.types import ColSpec, Schema
|
|
|
|
|
from sklearn.linear_model import LogisticRegression
|
|
|
|
|
from sklearn.metrics import brier_score_loss, roc_auc_score
|
|
|
|
|
|
|
|
|
|
from indicadores_kit.cacu.tablas import COHORTES
|
|
|
|
|
from indicadores_kit.oro.cohortes.armado import leer_marco, linaje, ultimo_armado
|
|
|
|
|
from indicadores_kit.oro.cohortes.definicion import leer_definicion, ruta_de_cohorte
|
|
|
|
|
|
|
|
|
|
from models.riesgo import Procedencia, Riesgo
|
|
|
|
|
|
|
|
|
|
EXPERIMENTO = "cacu-cin2"
|
|
|
|
|
NOMBRE_MODELO = "cacu_cin2_mas"
|
|
|
|
|
COHORTE_URL = "cacu/cohorte_vigilancia"
|
|
|
|
|
DESENLACE = "cin2_mas"
|
|
|
|
|
COVARIABLES = ["pap_0", "hpv_0"]
|
|
|
|
|
SIN_ESTADO = -999
|
|
|
|
|
HORIZONTE = 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 1 · descargar ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def descargar(repositorio, armado_id=None):
|
|
|
|
|
"""El marco del armado (el último si no se dice) y su linaje `kit.*`, en una sesión de `repositorio`. Solo lee."""
|
|
|
|
|
d = leer_definicion(ruta_de_cohorte("cacu", "cohorte_vigilancia"))
|
|
|
|
|
|
|
|
|
|
def leer(sesion):
|
|
|
|
|
aid = armado_id if armado_id is not None else ultimo_armado(sesion, d.url, cohortes=COHORTES)
|
|
|
|
|
if aid is None:
|
|
|
|
|
raise LookupError(f"No hay armados de {d.url}: corre antes la arista `cohortes`.")
|
|
|
|
|
columnas, filas = leer_marco(sesion, aid, d, cohortes=COHORTES)
|
|
|
|
|
return pd.DataFrame(filas, columns=columnas), linaje(sesion, aid, d, cohortes=COHORTES)
|
|
|
|
|
|
|
|
|
|
return repositorio.leer(leer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 2 · preparar ----------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def a_nulos(df):
|
|
|
|
|
"""`-999` es nulo, en números y en códigos."""
|
|
|
|
|
return df.replace({SIN_ESTADO: np.nan, float(SIN_ESTADO): np.nan, str(SIN_ESTADO): np.nan})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def preparar(marco, horizonte=HORIZONTE):
|
|
|
|
|
"""El marco con la etiqueta `y` a `horizonte` años, sin las filas no etiquetables.
|
|
|
|
|
|
|
|
|
|
Provisional (MD-Q6): y = 1 si `c == 1` o `r <= h`; y = 0 si `c == 0` y `l >= h`; lo demás se excluye.
|
|
|
|
|
"""
|
|
|
|
|
df = a_nulos(marco)
|
|
|
|
|
df["fecha_indice"] = pd.to_datetime(df["fecha_indice"])
|
|
|
|
|
positivo = (df["c"] == 1) | (df["r"] <= horizonte)
|
|
|
|
|
negativo = (df["c"] == 0) & (df["l"] >= horizonte) & ~positivo
|
|
|
|
|
df["y"] = np.where(positivo, 1, np.where(negativo, 0, -1))
|
|
|
|
|
return df[df["y"] >= 0].sort_values(["fecha_indice", "pac_id"]).reset_index(drop=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 3 · entrenar y evaluar ------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def dividir(df, fraccion=0.7):
|
|
|
|
|
"""Partición temporal: las fechas índice más antiguas entrenan. Nunca al azar."""
|
|
|
|
|
corte = df["fecha_indice"].iloc[int(len(df) * fraccion)]
|
|
|
|
|
return df[df["fecha_indice"] < corte], df[df["fecha_indice"] >= corte], corte
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ModeloCin2Mas(mlflow.pyfunc.PythonModel):
|
|
|
|
|
"""El pyfunc: indicadoras de las covariables y una logística. Recibe el marco, devuelve P(CIN2+) por fila.
|
|
|
|
|
|
|
|
|
|
Un nulo o un nivel que no se vio al ajustar da ceros en sus indicadoras.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def __init__(self, horizonte=HORIZONTE, C=1.0):
|
|
|
|
|
self.horizonte, self.C = float(horizonte), C
|
|
|
|
|
self.niveles, self.logistica = {}, None
|
|
|
|
|
|
|
|
|
|
def indicadoras(self, df):
|
|
|
|
|
df = a_nulos(df)
|
|
|
|
|
return pd.DataFrame(
|
|
|
|
|
{f"{c}={n}": (df[c].astype("string") == n).fillna(False).astype(float).to_numpy()
|
|
|
|
|
for c in COVARIABLES for n in self.niveles[c]},
|
|
|
|
|
index=df.index,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def ajustar(self, df):
|
|
|
|
|
self.niveles = {c: sorted(a_nulos(df)[c].dropna().astype(str).unique()) for c in COVARIABLES}
|
|
|
|
|
self.logistica = LogisticRegression(C=self.C, max_iter=1000).fit(self.indicadoras(df), df["y"])
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
def predict(self, context, model_input, params=None):
|
|
|
|
|
return self.logistica.predict_proba(self.indicadoras(model_input))[:, 1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def evaluar(modelo, entrena, prueba):
|
|
|
|
|
p = modelo.predict(None, prueba)
|
|
|
|
|
return {
|
|
|
|
|
"brier": brier_score_loss(prueba["y"], p, labels=[0, 1]),
|
|
|
|
|
"auc": roc_auc_score(prueba["y"], p) if prueba["y"].nunique() == 2 else float("nan"),
|
|
|
|
|
"n_entrenamiento": len(entrena), "n_prueba": len(prueba),
|
|
|
|
|
"positivos_entrenamiento": int(entrena["y"].sum()), "positivos_prueba": int(prueba["y"].sum()),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 4 · registrar ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
def sha_del_artefacto(model_uri):
|
|
|
|
|
"""sha256 de `python_model.pkl` (preprocesamiento + logística); el `MLmodel` lleva ids y fechas."""
|
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
|
|
|
ruta = Path(mlflow.artifacts.download_artifacts(model_uri, dst_path=tmp)) / "python_model.pkl"
|
|
|
|
|
return hashlib.sha256(ruta.read_bytes()).hexdigest()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def registrar(modelo, metricas, parametros, linaje):
|
|
|
|
|
"""Una corrida con el linaje, los parámetros, las métricas y el pyfunc registrado. Sin pacientes."""
|
|
|
|
|
firma = ModelSignature(inputs=Schema([ColSpec("string", c, required=False) for c in COVARIABLES]))
|
|
|
|
|
mlflow.set_experiment(EXPERIMENTO)
|
|
|
|
|
with mlflow.start_run() as corrida:
|
|
|
|
|
mlflow.set_tags({**linaje, "desenlace": DESENLACE})
|
|
|
|
|
mlflow.log_params(parametros)
|
|
|
|
|
mlflow.log_metrics(metricas)
|
|
|
|
|
info = mlflow.pyfunc.log_model(name="modelo", python_model=modelo, signature=firma,
|
|
|
|
|
registered_model_name=NOMBRE_MODELO)
|
|
|
|
|
mlflow.set_tag("modelo_sha", sha_del_artefacto(info.model_uri))
|
|
|
|
|
return corrida.info.run_id, str(info.registered_model_version)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def entrenar(repositorio, horizonte=HORIZONTE, armado_id=None):
|
|
|
|
|
"""Pasos 1-4. Devuelve (`run_id`, versión registrada, métricas)."""
|
|
|
|
|
marco, linaje = descargar(repositorio, armado_id)
|
|
|
|
|
df = preparar(marco, horizonte)
|
|
|
|
|
entrena, prueba, corte = dividir(df)
|
|
|
|
|
if entrena["y"].nunique() < 2:
|
|
|
|
|
raise ValueError(f"La partición de entrenamiento tiene una sola clase ({len(entrena)} etiquetados).")
|
|
|
|
|
modelo = ModeloCin2Mas(horizonte).ajustar(entrena)
|
|
|
|
|
metricas = evaluar(modelo, entrena, prueba)
|
|
|
|
|
# El corte es la fecha índice de una paciente: a MLflow va solo su mes.
|
|
|
|
|
parametros = {"horizonte_anios": horizonte, "C": modelo.C, "corte_temporal_mes": corte.strftime("%Y-%m"),
|
|
|
|
|
"covariables": ",".join(COVARIABLES), "etiqueta": "provisional MD-Q6"}
|
|
|
|
|
run_id, version = registrar(modelo, metricas, parametros, linaje)
|
|
|
|
|
return run_id, version, metricas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 6b · el estimador de la arista `estimar` -------------------------------------------------
|
|
|
|
|
|
|
|
|
|
class EstimadorMlflow:
|
|
|
|
|
"""Cumple `EstimadorDeRiesgo` con una versión registrada de `NOMBRE_MODELO`."""
|
|
|
|
|
|
|
|
|
|
cohorte_url = COHORTE_URL
|
|
|
|
|
desenlace = DESENLACE
|
|
|
|
|
|
|
|
|
|
def __init__(self, version):
|
|
|
|
|
cliente = mlflow.MlflowClient()
|
|
|
|
|
mv = cliente.get_model_version(NOMBRE_MODELO, str(version))
|
|
|
|
|
uri = f"models:/{NOMBRE_MODELO}/{mv.version}"
|
|
|
|
|
sha = sha_del_artefacto(uri)
|
|
|
|
|
if sha != cliente.get_run(mv.run_id).data.tags.get("modelo_sha"):
|
|
|
|
|
raise ValueError(f"El artefacto de {uri} no es el que se registró.")
|
|
|
|
|
self.pyfunc = mlflow.pyfunc.load_model(uri)
|
|
|
|
|
self.horizonte = self.pyfunc.unwrap_python_model().horizonte
|
|
|
|
|
self._procedencia = Procedencia(NOMBRE_MODELO, str(mv.version), mv.run_id, sha)
|
|
|
|
|
|
|
|
|
|
def procedencia(self):
|
|
|
|
|
return self._procedencia
|
|
|
|
|
|
|
|
|
|
def estimar(self, columnas, filas):
|
|
|
|
|
marco = pd.DataFrame(filas, columns=columnas)
|
|
|
|
|
entrada = a_nulos(marco)[COVARIABLES].astype(object)
|
|
|
|
|
p = self.pyfunc.predict(entrada.where(entrada.notna(), None))
|
|
|
|
|
return [Riesgo(int(pac), self.horizonte, round(float(q), 6)) for pac, q in zip(marco["pac_id"], p)]
|