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.
This commit is contained in:
+35
-13
@@ -21,28 +21,52 @@ 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]) -> pd.DataFrame:
|
||||
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."""
|
||||
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")
|
||||
if probabilities.ndim != 2 or len(probabilities) != len(members):
|
||||
raise ValueError(f"the model gave {probabilities.shape} for {len(members)} members")
|
||||
risks, dates = probabilities[:, -len(horizons):], members["fecha_indice"].to_numpy()
|
||||
if probabilities.shape[1] == len(horizons) + 1:
|
||||
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
|
||||
return 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": risks.ravel().astype(float)})
|
||||
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,
|
||||
@@ -55,9 +79,7 @@ def estimate(scenario: Scenario, source: CohortSource, output_path: str | Path,
|
||||
if already_estimated(output_path, resolved.version, cohort):
|
||||
return resolved, False
|
||||
cohort_frame = source.frame()
|
||||
horizons = json.loads(registry.client.get_run(resolved.run_id).data.params["horizons_years"])
|
||||
probabilities = np.asarray(mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame))
|
||||
risks = estimate_frame(cohort_frame, probabilities, horizons)
|
||||
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,
|
||||
|
||||
@@ -48,7 +48,12 @@ ESTIMATE_FRAME = pandera.DataFrameSchema(
|
||||
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
|
||||
"fecha_indice": pandera.Column(nullable=False),
|
||||
"horizonte_anios": pandera.Column(float, pandera.Check.ge(0)),
|
||||
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
|
||||
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1)),
|
||||
# the risk's interval, from a model that gives one (NaN where it can't)
|
||||
"ic_bajo": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False),
|
||||
"ic_alto": pandera.Column(float, pandera.Check.in_range(0, 1), nullable=True, required=False)},
|
||||
checks=pandera.Check(lambda f: ~(f["ic_bajo"] > f["probabilidad"]) & ~(f["ic_alto"] < f["probabilidad"])
|
||||
if "ic_bajo" in f else pd.Series(True, index=f.index), error="ic_bajo <= probabilidad <= ic_alto"),
|
||||
strict=True, ordered=True, unique=["pac_id", "horizonte_anios"], name="estimate")
|
||||
|
||||
POPULATION, INDEX, EXCLUSION, VARIABLES = "population", "index", "exclusion", "variables"
|
||||
|
||||
+13
-5
@@ -1,15 +1,23 @@
|
||||
"""From an estimate's rows to the risks a batch stores: `(pac_id, fecha_indice, horizonte_anios, probabilidad, ic_bajo,
|
||||
ic_alto)`; `fecha_indice` is the model's index date for the member, which its horizons count from."""
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
|
||||
|
||||
|
||||
def risk_rows(estimate: pd.DataFrame) -> list[tuple]:
|
||||
"""One risk per member and horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a member scored
|
||||
twice at one horizon or a probability outside 0..1 stops the batch."""
|
||||
"""One risk per member and horizon, with its interval when the estimate has one, once the rows satisfy
|
||||
`ESTIMATE_FRAME`: a member scored twice at one horizon or a probability outside 0..1 stops the batch."""
|
||||
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
|
||||
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), None, None)
|
||||
for pac_id, fecha, horizon, probability in zip(estimate["pac_id"], estimate["fecha_indice"],
|
||||
estimate["horizonte_anios"], estimate["probabilidad"])]
|
||||
missing = pd.Series(np.nan, index=estimate.index)
|
||||
low, high = estimate.get("ic_bajo", missing), estimate.get("ic_alto", missing)
|
||||
|
||||
def value(v):
|
||||
return None if pd.isna(v) else float(v)
|
||||
|
||||
return [(int(pac_id), pd.Timestamp(fecha).date(), float(horizon), float(probability), value(lo), value(hi))
|
||||
for pac_id, fecha, horizon, probability, lo, hi in zip(estimate["pac_id"], estimate["fecha_indice"],
|
||||
estimate["horizonte_anios"],
|
||||
estimate["probabilidad"], low, high)]
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""What this module covers: `models.dags.estimation.estimate_frame`, from a model's output to the estimate's rows.
|
||||
|
||||
Fixtures: none; a two-member cohort frame built in each test.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from models.dags.estimation import estimate_frame
|
||||
|
||||
COHORT = pd.DataFrame({"pac_id": [1, 2], "fecha_indice": [date(2025, 1, 1), date(2025, 2, 1)]})
|
||||
|
||||
|
||||
def test_a_member_the_model_cannot_place_has_no_rows():
|
||||
"""Pins down: a member whose risk is NaN (a combination unseen in training) is left out and the rest keep their
|
||||
rows, so one such member doesn't stop the whole batch. Fails if the NaN reaches the estimate's contract."""
|
||||
found = estimate_frame(COHORT, np.array([[0.1, 0.2], [np.nan, np.nan]]), [0.0, 1.0])
|
||||
|
||||
assert found["pac_id"].tolist() == [1, 1] and found["probabilidad"].tolist() == [0.1, 0.2]
|
||||
|
||||
|
||||
def test_with_intervals_the_unplaced_member_is_left_out_too():
|
||||
"""Pins down: with intervals, the risk block decides who is scored and each kept row has its two ends. Fails if
|
||||
the blocks are read in another order or a NaN end drops a member that has a risk."""
|
||||
output = np.array([[0.1, 0.05, 0.2], [np.nan, np.nan, np.nan]])
|
||||
found = estimate_frame(COHORT, output, [1.0], intervals=True)
|
||||
|
||||
assert found[["pac_id", "probabilidad", "ic_bajo", "ic_alto"]].values.tolist() == [[1, 0.1, 0.05, 0.2]]
|
||||
@@ -75,11 +75,19 @@ def test_each_row_becomes_one_risk_at_its_horizon():
|
||||
(2, d2, 3.0, 0.23, None, None)]
|
||||
|
||||
|
||||
def test_a_risk_keeps_the_interval_the_model_gave():
|
||||
"""Pins down: an estimate with `ic_bajo` and `ic_alto` stores them with each risk, and NaN (a member the model
|
||||
couldn't bound) is stored as no interval. Fails if `risk_rows` drops the interval or stores NaN."""
|
||||
frame = _estimate((1, 2)).assign(ic_bajo=[0.05, float("nan")], ic_alto=[0.2, float("nan")])
|
||||
assert [row[4:] for row in risk_rows(frame)] == [(0.05, 0.2), (None, None)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),
|
||||
_estimate().rename(columns={"probabilidad": "p"})])
|
||||
_estimate().rename(columns={"probabilidad": "p"}),
|
||||
_estimate().assign(ic_bajo=[0.2, 0.1, 0.3], ic_alto=[0.3, 0.3, 0.4])])
|
||||
def test_a_malformed_estimate_stops_the_batch(frame):
|
||||
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, or other columns stop the batch
|
||||
before anything is written. Fails if any of them reaches the database."""
|
||||
"""Pins down: a member scored twice at one horizon, a probability outside 0..1, other columns, or an interval that
|
||||
doesn't hold its risk stop the batch before anything is written. Fails if any of them reaches the database."""
|
||||
with pytest.raises(ValueError):
|
||||
risk_rows(frame)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user