Files
WebApi/webapi/orchestration/estimators.py

82 lines
3.7 KiB
Python

"""Live estimators for `Context.estimators`: the cycle's `estimate` step scores each cohort with the model version
its domain has in production.
`estimate` hands an estimator the cohort build's wide frame (`estimar(columnas, filas)`, `procedencia()`,
`desenlace`): one column per the cohort's own variables. A registered model's predictors are a different, larger
set, read from the build's exported file (the same export `python -m models cohorts export` writes), so an
estimator here ignores the wide frame and rebuilds the model's own input: the cycle's latest build for membership,
the domain's timeline for the events, then the production version in MLflow to score it. `estimar`'s arguments go
unused by design.
"""
from dataclasses import dataclass
from importlib import import_module
from typing import Any
@dataclass(frozen=True)
class Provenance:
modelo_nombre: str
modelo_version: str
mlflow_run_id: str
modelo_sha: str | None
def como_dict(self) -> dict[str, str]:
return {key: value for key, value in self.__dict__.items() if value}
class Cin2LogisticEstimator:
"""Scores CaCu's surveillance cohort with the `cacu-cin2_logistic` version in production (or `version`, to
test a candidate). Offered by `live_estimators` only once that version exists, so `procedencia` always has
something to report when `estimate` calls it."""
def __init__(self, domain: str = "cacu", version: str | None = None):
self.domain = domain
self.version = version
self.desenlace = "cin2_mas"
self._provenance: Provenance | None = None
def estimar(self, columnas: list[str], filas: list[tuple]) -> list[tuple]:
import mlflow.pyfunc
from persistance.settings import settings
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.registry import registered_name, registry
from models.io.storage import cohorts_root, read_cohort
from models.pipelines.export_cohort import export_kit_build
from models.steps.risks import risk_rows
repos = import_module(f"persistance.{self.domain}")
url = SETTINGS["cohort"]
build_id = repos.cohort_repository.latest_build(url)
resolved = registry.resolve(self.domain, SETTINGS["scenario"], self.version)
root = cohorts_root(getattr(settings, f"{self.domain}_database_url"))
path, _ = export_kit_build(repos.cohort_repository, repos.timeline_repository, root, self.domain, url, build_id)
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(path))
window = SETTINGS["outcome_window_months"]
self.desenlace = f"cin2_{window}m"
self._provenance = Provenance(
modelo_nombre=registered_name(self.domain, SETTINGS["scenario"]), modelo_version=resolved.version,
mlflow_run_id=resolved.run_id, modelo_sha=resolved.modelo_sha)
return [tuple(row) for row in risk_rows(risks, window / 12)]
def procedencia(self) -> Provenance:
if self._provenance is None:
raise RuntimeError("estimar() runs before procedencia()")
return self._provenance
def live_estimators(domain: str) -> dict[str, Any]:
"""The estimators of a domain's cohorts whose model has a version in production, by cohort url. Empty where
none is in production yet, the same as no estimator being configured: `estimate` then does nothing."""
if domain != "cacu":
return {}
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.registry import registry
try:
registry.resolve(domain, SETTINGS["scenario"])
except LookupError:
return {}
return {SETTINGS["cohort"]: Cin2LogisticEstimator(domain)}