Files
models/models/jobs.py
T

89 lines
3.7 KiB
Python

"""Training and scoring of a domain's models, what the Dagster jobs run. A domain's module
`models.<domain>.jobs` binds them to its models (`MODELS`) and its reports: `train(name,
as_of)` registers a new version (MLflow) with its two generated reports; `score(name)` writes
the champion's risk batch."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
import mlflow.pyfunc
import pandas as pd
from joblib.externals.loky import get_reusable_executor
from persistance import gold, registry
class EmptyCohort(ValueError):
"""The site has nobody in a model's cohort (no colposcopies, say): nothing to learn from."""
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted model as MLflow serves it: patient timelines in (gold `<domain>_events` rows
with each patient's index date), one row per patient and horizon out."""
def __init__(self, spec, fitted):
self.spec, self.fitted = spec, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return self.spec.predict(self.fitted, model_input)
@dataclass(frozen=True)
class Jobs:
domain: str
models: dict
technical_validation: Callable[..., dict]
interpretability: Callable[..., dict]
@property
def events(self) -> str:
return f"{self.domain}_events"
def routine(self) -> list[str]:
"""The models a train run takes when none is named: all of them."""
return list(self.models)
def scored(self) -> list[str]:
"""The models a score run takes when none is named: all of them."""
return list(self.models)
def registered(self, name: str) -> str:
return f"{self.domain}.{name}"
def train(self, name: str, as_of: date | None = None) -> int:
"""A new registered version of the model, trained on its cohort's timelines up to
`as_of` (default: today), with its metrics and its two generated reports."""
spec, as_of = self.models[name], as_of or date.today()
if getattr(spec, "reports", False): # trained on its cohort, with its own reports
events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, found = spec.train(events, as_of)
else:
events = gold.timelines(self.events, spec.cohort, as_of)
if events.empty:
raise EmptyCohort(f"{self.registered(name)}: nobody in {spec.cohort}")
fitted, metrics, data = spec.train(events, as_of)
found = {
"technical_validation": self.technical_validation(spec, metrics, data),
"interpretability": self.interpretability(spec, fitted, data),
}
# Bootstraps ran on joblib's worker pool: release it now, or the job's process waits
# for its idle workers to time out (5 minutes) before it can end.
get_reusable_executor().shutdown(wait=True)
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
model = Predictor(spec, fitted)
return registry.register(self.registered(name), model, params, metrics, found)
def score(self, name: str) -> int | None:
"""The champion's risks for today's members of the model's cohort, saved as its risk
batch; None when the model has no champion yet."""
found = registry.champion(self.registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(self.events, self.models[name].cohort))
gold.save_scores(self.registered(name), version, risks)
return version