models train: train a model from the command line
This commit is contained in:
@@ -20,7 +20,7 @@ WebApi.
|
||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||
| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select <dominio>_linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. |
|
||||
| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. |
|
||||
| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. |
|
||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||
|
||||
@@ -14,12 +14,48 @@ def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||
return 2
|
||||
|
||||
|
||||
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||
"""Finds the model's folder from its name and trains it on the build's file."""
|
||||
if args.environment == "prod" and args.armado is None:
|
||||
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from models.io.cohorts import cohorts_root, find_cohort_file
|
||||
|
||||
package = f"models.{args.domain}.{args.scenario}"
|
||||
try:
|
||||
model, trainer = import_module(f"{package}.model"), import_module(f"{package}.train")
|
||||
except ModuleNotFoundError as error:
|
||||
if not (error.name or "").startswith(package):
|
||||
raise
|
||||
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
|
||||
return 1
|
||||
try:
|
||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||
path = find_cohort_file(root, model.SETTINGS["cohort"], args.armado)
|
||||
except (FileNotFoundError, ValueError) as error:
|
||||
print(f"{error}: export it with scripts/export_cohort.py", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
|
||||
return 0
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
||||
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
||||
|
||||
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
||||
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
||||
|
||||
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
|
||||
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||
train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||
train.set_defaults(run=lambda args: _train(train, args))
|
||||
return parser
|
||||
|
||||
|
||||
|
||||
@@ -4,11 +4,13 @@ Long format: one row per member and event, with the member's index date on every
|
||||
frame and computes its own outcome and predictors from it; it never reads the database.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from sqlalchemy.engine import make_url
|
||||
|
||||
SCHEMA = pa.schema([
|
||||
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
|
||||
@@ -22,6 +24,34 @@ class CohortFileError(ValueError):
|
||||
"""The file isn't a cohort build: its columns or types aren't `SCHEMA`'s."""
|
||||
|
||||
|
||||
def cohorts_root(database_url: str) -> Path:
|
||||
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
||||
if configured := os.environ.get("COHORTS_DIR"):
|
||||
return Path(configured)
|
||||
url = make_url(database_url)
|
||||
if url.get_backend_name() != "sqlite" or not url.database:
|
||||
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
||||
return Path(url.database.removeprefix("file:")).parent / "cohorts"
|
||||
|
||||
|
||||
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
||||
domain, cohort = url.split("/", 1)
|
||||
return root / domain / cohort / f"{armado_id}.parquet"
|
||||
|
||||
|
||||
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
||||
"""The file of that build, or of the cohort's latest build that has a file."""
|
||||
if armado_id is None:
|
||||
builds = [int(file.stem) for file in cohort_path(root, url, 0).parent.glob("*.parquet") if file.stem.isdigit()]
|
||||
if not builds:
|
||||
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
||||
armado_id = max(builds)
|
||||
path = cohort_path(root, url, armado_id)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
||||
return path
|
||||
|
||||
|
||||
def cohort_lineage(path: str | Path) -> dict[str, str]:
|
||||
"""The lineage in the file's metadata, without reading any rows."""
|
||||
metadata = pq.read_metadata(path).metadata
|
||||
|
||||
@@ -13,7 +13,6 @@ repository, so it needs neither dbt nor write access. In a read-only folder, wit
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Callable, Iterable
|
||||
@@ -28,10 +27,9 @@ from persistance.aristas.oro import CohortBuild, CohortMember
|
||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
||||
from persistance.settings import settings
|
||||
from sqlalchemy import column, select, table
|
||||
from sqlalchemy.engine import make_url
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from models.io.cohorts import SCHEMA, cohort_lineage
|
||||
from models.io.cohorts import SCHEMA, cohort_lineage, cohort_path, cohorts_root
|
||||
|
||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||
|
||||
@@ -40,21 +38,6 @@ class TimelineViewError(RuntimeError):
|
||||
"""dbt's timeline view can't be read."""
|
||||
|
||||
|
||||
def cohorts_root(database_url: str) -> Path:
|
||||
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
||||
if configured := os.environ.get("COHORTS_DIR"):
|
||||
return Path(configured)
|
||||
url = make_url(database_url)
|
||||
if url.get_backend_name() != "sqlite" or not url.database:
|
||||
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
||||
return Path(url.database.removeprefix("file:")).parent / "cohorts"
|
||||
|
||||
|
||||
def cohort_file(build: CohortBuild, root: Path) -> Path:
|
||||
domain, cohort = build.url.split("/", 1)
|
||||
return root / domain / cohort / f"{build.armado_id}.parquet"
|
||||
|
||||
|
||||
def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]:
|
||||
"""Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`."""
|
||||
name = f"{domain}_linea_de_tiempo"
|
||||
@@ -107,7 +90,7 @@ def write_once(table: pa.Table, path: Path) -> None:
|
||||
|
||||
def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]:
|
||||
"""The build's file: reused if it's already there and belongs to the build, written once if not."""
|
||||
path = cohort_file(build, root)
|
||||
path = cohort_path(root, build.url, build.armado_id)
|
||||
if path.exists():
|
||||
lineage = cohort_lineage(path)
|
||||
if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
|
||||
split, and that training on a build's file registers a version with its lineage.
|
||||
split, that training on a build's file registers a version with its lineage, and the `models train` command over it.
|
||||
|
||||
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
||||
build's Parquet file with its lineage; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
|
||||
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
|
||||
SQLite-backed MLflow.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
@@ -13,6 +14,7 @@ import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import pytest
|
||||
|
||||
from models.__main__ import main
|
||||
from models.cacu.cin2_logistic import model
|
||||
from models.cacu.cin2_logistic.train import train
|
||||
from models.io.cohorts import SCHEMA
|
||||
@@ -38,13 +40,27 @@ def cohort_frame():
|
||||
return pd.DataFrame(rows, columns=SCHEMA.names)
|
||||
|
||||
|
||||
def _write(frame, path, armado_id):
|
||||
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
pq.write_table(table.replace_schema_metadata({"armado_id": str(armado_id), "url": "cacu/cohorte_vigilancia"}), path)
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_file(cohort_frame, tmp_path):
|
||||
"""The frame as build 7's file."""
|
||||
table = pa.Table.from_pandas(cohort_frame, schema=SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "7.parquet"
|
||||
pq.write_table(table.replace_schema_metadata({"armado_id": "7", "url": "cacu/cohorte_vigilancia"}), path)
|
||||
return path
|
||||
return _write(cohort_frame, tmp_path / "7.parquet", 7)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exported(cohort_frame, tmp_path, monkeypatch):
|
||||
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
|
||||
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
|
||||
_write(cohort_frame, folder / "7.parquet", 7)
|
||||
_write(cohort_frame, folder / "12.parquet", 12)
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
return folder
|
||||
|
||||
|
||||
def test_prepare_computes_y_and_days_from_bethesda_only(cohort_frame):
|
||||
@@ -91,3 +107,42 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
|
||||
|
||||
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
||||
assert len(probabilities) == 20 and probabilities.between(0, 1).all()
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
||||
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
|
||||
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
|
||||
assert "version 1" in capsys.readouterr().out
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV"
|
||||
|
||||
|
||||
def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking):
|
||||
"""Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option
|
||||
is ignored."""
|
||||
assert main(["train", "cacu", "cin2_logistic", "--armado", "7", "--environment", "prod"]) == 0
|
||||
|
||||
stored = registry.get("cacu", "cin2_logistic", "1")
|
||||
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
|
||||
|
||||
|
||||
def test_prod_without_a_build_is_refused(capsys):
|
||||
"""Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls
|
||||
back to the latest file."""
|
||||
with pytest.raises(SystemExit) as stopped:
|
||||
main(["train", "cacu", "cin2_logistic", "--environment", "prod"])
|
||||
|
||||
assert stopped.value.code == 2 and "--armado" in capsys.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("arguments, message", [
|
||||
(["cacu", "ninguno"], "no such model: cacu/ninguno"),
|
||||
(["cacu", "cin2_logistic", "--armado", "99"], "export it"),
|
||||
])
|
||||
def test_what_is_missing_is_named(exported, arguments, message, capsys):
|
||||
"""Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no
|
||||
version. Fails if the command lets the import error through, or trains on another file."""
|
||||
assert main(["train", *arguments]) == 1
|
||||
assert message in capsys.readouterr().err
|
||||
|
||||
Reference in New Issue
Block a user