models train: train a model from the command line

This commit is contained in:
2026-11-04 23:36:46 -06:00
parent 37fb292a4f
commit 0fdab3651c
5 changed files with 130 additions and 26 deletions
+36
View File
@@ -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
+30
View File
@@ -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