Files
models/models/dags/estimation.py
T
edgar 78a4748592 Estimates: each risk's interval when the model gives one; a member it can't place has no rows
A run with `risk_interval_level` has a model that gives, after the risk at each horizon, its interval's lower and
upper ends; the estimate keeps them as `ic_bajo` and `ic_alto`, the contract checks that they hold the risk, and the
batch stores them. `scored_frame` is the one place that reads the run and calls the model, for the command and the
WebApi's cycle. A member whose risk is NaN (a combination the model never saw) is left out instead of stopping the
whole batch.
2026-11-22 07:38:17 -06:00

92 lines
5.5 KiB
Python

"""Estimating with any scenario's registered version: score a source's build and write the estimate, once.
Estimation runs the registered pyfunc, outside Hamilton, so a version estimates the same whatever the repository holds
now. The model takes the build's long frame and gives, through `predict_proba`, one row per member in `pac_id` order;
its last columns are the probabilities at the version's horizons (`horizons_years`, recorded with its run). For a
classifier that's the positive class at its one horizon. The output has one row per member and horizon
(`ESTIMATE_FRAME`); its metadata names the version, the outcome (`model.toml`'s `outcome`) and the source's reference.
"""
import json
from pathlib import Path
import mlflow.pyfunc
import numpy as np
import pandas as pd
import pyarrow as pa
from models.dags.training import Scenario
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import CohortSource, read_metadata, write_once
# The config key, logged with the run, of a model whose risks come with their interval (`estimate_frame`).
INTERVAL_PARAM = "risk_interval_level"
def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -> bool:
"""Whether the output file already holds this version's scores of this build."""
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, **cohort})
def estimate_frame(cohort: pd.DataFrame, probabilities: np.ndarray, horizons: list[float],
intervals: bool = False) -> pd.DataFrame:
"""One row per member (in `pac_id` order, as the model gives them) and horizon. A model that decides its own index
date (`models.steps.indexing`) gives it as one more first column, in days since 1970-01-01, with the members it
leaves out empty: their rows are dropped and the rest are dated by it, not by the cohort's index. A member without
a risk (NaN: one the model can't place) has no rows. With `intervals`
the model gives three blocks of one column per horizon, the risk and its interval's lower and upper ends
(`ic_bajo`, `ic_alto`)."""
members = cohort[["pac_id", "fecha_indice"]].drop_duplicates().sort_values("pac_id", kind="stable")
width = len(horizons) * (3 if intervals else 1)
if probabilities.ndim != 2 or len(probabilities) != len(members) or probabilities.shape[1] not in (width, width + 1):
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members and {len(horizons)} horizons"
+ (" with intervals" if intervals else ""))
risks, dates = probabilities[:, -width:], members["fecha_indice"].to_numpy()
if probabilities.shape[1] == width + 1:
decided = ~np.isnan(probabilities[:, 0])
members, risks = members[decided], risks[decided]
dates = pd.to_datetime(probabilities[decided, 0], unit="D").date
scored = ~np.isnan(risks[:, :len(horizons)]).any(axis=1) # a member the model can't place (a combination unseen in training)
members, risks, dates = members[scored], risks[scored], dates[scored]
blocks = np.split(risks, 3 if intervals else 1, axis=1)
frame = pd.DataFrame({"pac_id": np.repeat(members["pac_id"].to_numpy(), len(horizons)).astype(int),
"fecha_indice": np.repeat(dates, len(horizons)),
"horizonte_anios": np.tile(np.asarray(horizons, dtype=float), len(members)),
"probabilidad": blocks[0].ravel().astype(float)})
if intervals:
frame["ic_bajo"], frame["ic_alto"] = blocks[1].ravel().astype(float), blocks[2].ravel().astype(float)
return frame
def scored_frame(resolved: ResolvedVersion, cohort_frame: pd.DataFrame) -> pd.DataFrame:
"""The version's estimate of a build's long frame: its model's output at the run's horizons, with the interval
when the run has `INTERVAL_PARAM`."""
params = registry.client.get_run(resolved.run_id).data.params
intervals = params.get(INTERVAL_PARAM) not in (None, "", "None", "null")
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
return estimate_frame(cohort_frame, probabilities, json.loads(params["horizons_years"]), intervals)
def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
version: str | None = None) -> tuple[ResolvedVersion, bool]:
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
`modelo_sha` is copied when the version has it, and isn't checked."""
output_path = Path(output_path)
resolved = registry.resolve(scenario.domain, scenario.scenario, version)
cohort = source.reference()
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
cohort_frame = source.frame()
risks = scored_frame(resolved, cohort_frame)
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
provenance = {"modelo_nombre": registered_name(scenario.domain, scenario.scenario),
"modelo_version": resolved.version, "mlflow_run_id": resolved.run_id,
"desenlace": scenario.outcome, **cohort}
if resolved.modelo_sha:
provenance["modelo_sha"] = resolved.modelo_sha
table = pa.Table.from_pandas(risks, preserve_index=False)
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
return resolved, True