Value checks with pandera on cohort files, read and written, and on estimates, written and stored

This commit is contained in:
2026-11-06 00:44:58 -06:00
parent 71e77f0c7e
commit 5d65730b98
7 changed files with 127 additions and 17 deletions
+2 -3
View File
@@ -6,7 +6,7 @@ import mlflow.pyfunc
import pyarrow as pa
from models.cacu.cin2_logistic.model import SETTINGS
from models.io.contracts import ESTIMATE_COLUMNS
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
from models.io.lineage import COHORT_FILE_TAG, cohort_reference, file_sha256, matches
from models.io.registry import ResolvedVersion, registered_name, registry
from models.io.storage import read_cohort, read_metadata, write_once
@@ -29,8 +29,7 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No
if already_estimated(output_path, resolved.version, cohort):
return resolved, False
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
if tuple(risks.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
check_frame(ESTIMATE_FRAME, risks, EstimateError, f"version {resolved.version}'s output")
window = SETTINGS["outcome_window_months"]
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
"mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
+37 -1
View File
@@ -4,6 +4,7 @@
every row.
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
- The values both must hold (`COHORT_FRAME`, `ESTIMATE_FRAME`, checked with `check_frame`).
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
@@ -15,6 +16,7 @@ from datetime import date
from typing import NamedTuple, Protocol, runtime_checkable
import pandas as pd
import pandera.pandas as pandera
import pyarrow as pa
COHORT_SCHEMA = pa.schema([
@@ -26,11 +28,45 @@ COHORT_SCHEMA = pa.schema([
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
# The values the columns must hold, checked on the frames read from and written to these files (pandera). The arrow
# schema says which columns and types; these say what a valid row and a valid file are.
COHORT_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0)),
"fecha_indice": pandera.Column(nullable=False),
"fecha": pandera.Column(nullable=False),
"clase": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"tipo": pandera.Column(str, pandera.Check.str_length(min_value=1)),
"fuente_tabla": pandera.Column(str, nullable=False),
"fuente_id": pandera.Column(str, nullable=False)},
checks=pandera.Check(lambda frame: frame.groupby("pac_id")["fecha_indice"].nunique().le(1).all(),
error="a member has more than one index date"),
name="cohort build")
ESTIMATE_FRAME = pandera.DataFrameSchema(
{"pac_id": pandera.Column(int, pandera.Check.gt(0), unique=True),
"fecha_indice": pandera.Column(nullable=False),
"probabilidad": pandera.Column(float, pandera.Check.in_range(0, 1))},
strict=True, ordered=True, name="estimate")
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
class CohortFileError(ValueError):
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s."""
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s, or its rows break
`COHORT_FRAME`."""
class EstimateError(ValueError):
"""An estimate's rows break `ESTIMATE_FRAME`: other columns, a member scored twice, a probability outside 0..1."""
def check_frame(schema: pandera.DataFrameSchema, frame: pd.DataFrame, error: type[ValueError], where: str) -> pd.DataFrame:
"""`frame` if it satisfies `schema`, else `error` naming every failed check (up to ten)."""
try:
return schema.validate(frame, lazy=True)
except pandera.errors.SchemaErrors as failed:
cases = failed.failure_cases[["column", "check", "failure_case"]].head(10).to_dict("records")
raise error(f"{where} isn't a valid {schema.name}: {cases}") from None
class CohortDefinitionError(ValueError):
+3 -3
View File
@@ -19,8 +19,8 @@ import pyarrow as pa
import pyarrow.parquet as pq
from sqlalchemy.engine import make_url
from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
CohortQueries, ExclusionRule)
from models.io.contracts import (COHORT_FRAME, COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError,
CohortFileError, CohortQueries, ExclusionRule, check_frame)
def cohorts_root(database_url: str) -> Path:
@@ -108,7 +108,7 @@ def read_cohort(path: str | Path) -> pd.DataFrame:
schema = pq.read_schema(path)
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
return pd.read_parquet(path)
return check_frame(COHORT_FRAME, pd.read_parquet(path), CohortFileError, str(path))
def write_once(table: pa.Table, path: Path) -> None:
+3 -1
View File
@@ -5,7 +5,7 @@ from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.contracts import COHORT_FRAME, COHORT_SCHEMA as SCHEMA, CohortFileError, check_frame
from models.io.lineage import table_sha256
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
@@ -36,5 +36,7 @@ def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
"""The file's table, once its rows satisfy `COHORT_FRAME`: a build that would fail to read is never written."""
check_frame(COHORT_FRAME, cohort_events, CohortFileError, f"build {lineage.get('build') or lineage.get('armado_id')}")
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
+4 -8
View File
@@ -2,16 +2,12 @@
import pandas as pd
from models.io.contracts import ESTIMATE_COLUMNS
from models.io.contracts import ESTIMATE_FRAME, EstimateError, check_frame
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
"""One risk per member at the model's horizon, without an interval; a member scored twice stops the batch."""
if tuple(estimate.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}")
if estimate["pac_id"].duplicated().any():
raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}")
if not estimate["probabilidad"].between(0, 1).all():
raise ValueError("a probability outside 0..1")
"""One risk per member at the model's horizon, without an interval, once the rows satisfy `ESTIMATE_FRAME`: a
member scored twice or a probability outside 0..1 stops the batch."""
check_frame(ESTIMATE_FRAME, estimate, EstimateError, "the estimate")
return [(int(pac_id), float(horizon_years), float(probability), None, None)
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]