CaCu training and scoring jobs on gold, MLflow versions with their reports

This commit is contained in:
Roberto Treviño
2026-11-25 01:16:45 -06:00
parent bea3e4cd2d
commit b6857dab2a
4 changed files with 273 additions and 6 deletions
+54
View File
@@ -0,0 +1,54 @@
"""Training and scoring of the CaCu models: what the Dagster jobs run."""
from datetime import date
import mlflow.pyfunc
import pandas as pd
from models.cacu import reports
from models.cacu.specs import MODELS
from persistance import gold, registry
EVENTS = "cacu_events"
def registered(name: str) -> str:
return f"cacu.{name}"
class Predictor(mlflow.pyfunc.PythonModel):
"""A fitted CaCu model as MLflow serves it: patient timelines in (gold `cacu_events`
rows with each patient's index date), one row per patient and horizon out."""
def __init__(self, name: str, fitted):
self.name, self.fitted = name, fitted
def predict(self, context, model_input: pd.DataFrame, params=None) -> pd.DataFrame:
return MODELS[self.name].predict(self.fitted, model_input)
def train(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 = MODELS[name], as_of or date.today()
events = gold.timelines(EVENTS, spec.cohort, as_of)
args = (as_of,) if spec.method == "logistic regression" else ()
fitted, metrics, data = spec.train(events, *args)
found = {
"technical_validation": reports.technical_validation(spec, metrics, data),
"interpretability": reports.interpretability(spec, fitted, data),
}
params = {"cohort": spec.cohort, "method": spec.method, "as_of": as_of.isoformat()}
return registry.register(registered(name), Predictor(name, fitted), params, metrics, found)
def score(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(registered(name))
if found is None:
return None
version, model = found
risks = model.predict(gold.timelines(EVENTS, MODELS[name].cohort))
gold.save_scores(registered(name), version, risks)
return version
+167
View File
@@ -0,0 +1,167 @@
"""The two reports training writes for each model version (the third, the clinical
validation, is a document the clinical team adds). Both are data the governance page draws.
- technical validation: how the version was trained and tested, and its held-out metrics;
- interpretability: what drives its predictions. For the mixture, observed against
predicted risk per combination of its features: the Turnbull estimate (the
nonparametric cumulative risk under interval censoring) with a bootstrap band, the
model's curve with its delta-method band, and expected over observed at each horizon.
For the logistic regression, its coefficients and calibration by risk decile.
"""
import numpy as np
import pandas as pd
from scipy.stats import norm
from sklearn.metrics import brier_score_loss
from models.cacu.pim import Mixture
from models.cacu.specs import Logistic, Pim
GRID_STEP = 0.1 # years between points of a curve
BOOTSTRAP = 200
SEED = 20261122
Z = norm.ppf(0.975)
def technical_validation(spec: Pim | Logistic, metrics: dict, data: dict) -> dict:
members = data.get("coded", data.get("labelled"))
return {
"model": spec.name,
"method": spec.method,
"cohort": spec.cohort,
"split": "temporal: the earliest 70% of index dates train, the latest 30% test",
"members": len(members),
"index_dates": [str(members["index_date"].min()), str(members["index_date"].max())],
"metrics": metrics,
}
def turnbull(c, l, r, iters: int = 5000, tol: float = 1e-10):
"""Turnbull's EM: support points and cumulative risk at each. A prevalent case's event
is at 0; a patient free at the index has hers in (l, r]; an unknown one in [0, r]."""
finite = r[np.isfinite(r)]
support = np.unique(np.concatenate([[0.0], finite[finite > 0], [np.inf]]))
low, high = np.where(c == 0, l, -np.inf), np.where(c == 1, 0.0, r)
inside = (support[None, :] > low[:, None]) & (support[None, :] <= high[:, None])
patterns, counts = np.unique(inside, axis=0, return_counts=True)
p = np.full(len(support), 1 / len(support))
for _ in range(iters):
weighted = patterns * p
new = (counts[:, None] * weighted / weighted.sum(1, keepdims=True)).sum(0) / counts.sum()
done = np.max(np.abs(new - p)) < tol
p = new
if done:
break
return support, np.cumsum(p)
def _at(support, cumulative, t) -> np.ndarray:
i = np.searchsorted(support, np.asarray(t, dtype=float), side="right") - 1
return np.where(i < 0, 0.0, cumulative[np.maximum(i, 0)])
def _label(feature: str, value) -> str:
if value is None or (isinstance(value, float) and np.isnan(value)):
return "NA"
if feature == "hpv_positive":
return "positive" if float(value) == 1.0 else "negative"
return str(value)
def _band(curve, variance) -> tuple[list, list]:
relative = np.where(curve > 0, np.sqrt(variance) / np.maximum(curve, 1e-300), 0.0)
return (np.clip(curve * np.exp(-Z * relative), 0, 1).tolist(),
np.clip(curve * np.exp(Z * relative), 0, 1).tolist()) # fmt: skip
def _mixture_curve(mixture: Mixture, row: pd.DataFrame, years) -> tuple | None:
key = tuple(row[list(mixture.strata)].iloc[0]) if mixture.strata else ()
if key not in mixture.fits_ or not mixture._placed(row, mixture.seen_[key]).all():
return None
prevalence, incidence = mixture._design(row, mixture.seen_[key])
point, variance = mixture.fits_[key].risk_with_variance(prevalence, incidence, years)
return point[0], variance[0]
def interpretability(spec: Pim | Logistic, model, data: dict) -> dict:
if isinstance(spec, Logistic):
return _logistic(model, data["test"])
coded = data["coded"]
full = Mixture(spec.horizons, spec.incidence_features, spec.strata,
model.levels).fit(coded[spec.features], coded[["c", "l", "r"]]) # fmt: skip
members = coded.reset_index(drop=True)
labels = pd.DataFrame({f: members[f].map(lambda v, f=f: _label(f, v)) for f in spec.features})
horizons = np.asarray(spec.horizons, dtype=float)
grid = np.round(np.arange(0, horizons.max() + GRID_STEP / 2, GRID_STEP), 6)
rng = np.random.default_rng(SEED)
groups = []
for _, combination in labels.drop_duplicates().iterrows():
mask = (labels == combination).all(axis=1).to_numpy()
group = members[mask]
c, l, r = (group[k].to_numpy(dtype=float) for k in ("c", "l", "r"))
support, cumulative = turnbull(c, l, r)
boot_grid, boot_h = [], []
for _ in range(BOOTSTRAP):
pick = rng.integers(0, len(group), len(group))
s, cum = turnbull(c[pick], l[pick], r[pick])
boot_grid.append(_at(s, cum, grid))
boot_h.append(_at(s, cum, horizons))
observed, var_observed = _at(support, cumulative, horizons), np.var(boot_h, axis=0, ddof=1)
entry = {
"combination": combination.to_dict(),
"n": int(mask.sum()),
"prevalent": int((c == 1).sum()),
"incident": int(((c != 1) & np.isfinite(r)).sum()),
"observed": {"years": grid.tolist(), "risk": _at(support, cumulative, grid).tolist(),
"low": np.percentile(boot_grid, 2.5, axis=0).tolist(),
"high": np.percentile(boot_grid, 97.5, axis=0).tolist()},
"predicted": None,
"expected_over_observed": [],
} # fmt: skip
probe = group.iloc[[0]][spec.features]
at_grid, at_h = _mixture_curve(full, probe, grid), _mixture_curve(full, probe, horizons)
if at_grid is not None:
low, high = _band(*at_grid)
entry["predicted"] = {"years": grid.tolist(), "risk": at_grid[0].tolist(),
"low": low, "high": high} # fmt: skip
for k, h in enumerate(horizons):
e = None if at_h is None else float(at_h[0][k])
ratio = {"years": float(h), "expected": e, "observed": float(observed[k]),
"ratio": None, "low": None, "high": None} # fmt: skip
if e and observed[k] > 0 and np.isfinite(var_observed[k]):
se = np.sqrt(at_h[1][k] / e**2 + var_observed[k] / observed[k] ** 2)
value = e / observed[k]
ratio |= {"ratio": value, "low": value * np.exp(-Z * se),
"high": value * np.exp(Z * se)} # fmt: skip
entry["expected_over_observed"].append(ratio)
groups.append(entry)
groups.sort(key=lambda g: (-g["n"], list(g["combination"].values())))
return {"model": spec.name, "kind": "subgroups", "bootstrap": BOOTSTRAP, "seed": SEED,
"groups": groups} # fmt: skip
def _logistic(model, test: pd.DataFrame, bins: int = 10) -> dict:
classifier, encoder = model.named_steps["classify"], model.named_steps["encode"]
names = encoder.get_feature_names_out()
p = test["p"]
deciles = pd.qcut(p, q=min(bins, p.nunique()), duplicates="drop")
table = test.groupby(deciles, observed=True).agg(n=("y", "size"), predicted=("p", "mean"),
observed=("y", "mean")) # fmt: skip
return {
"model": "logistic regression",
"kind": "coefficients",
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, names), map(float, classifier.coef_[0]), strict=True)),
"calibration": {
"brier": float(brier_score_loss(test["y"], p)),
"bins": [
{
"range": str(k),
"n": int(v.n),
"predicted": float(v.predicted),
"observed": float(v.observed),
}
for k, v in table.iterrows()
],
}, # fmt: skip
}
+46 -2
View File
@@ -1,9 +1,13 @@
"""Dagster code location: every heavy step of the platform is a job defined here."""
from datetime import date
import dagster as dg
from models import graph
from persistance import config_log
from models.cacu import jobs as cacu
from models.cacu.specs import MODELS as CACU_MODELS
from persistance import config_log, silver
WRITES = {"writes": "platform"} # dagster.yaml lets one run with this tag at a time (SQLite)
@@ -27,4 +31,44 @@ def ingest():
run_pipeline()
defs = dg.Definitions(jobs=[ingest])
class Training(dg.Config):
models: list[str] = list(CACU_MODELS)
as_of: str | None = None # the date the data are taken up to (default: today)
@dg.op
def train_models(context: dg.OpExecutionContext, config: Training) -> dict:
"""A new registered version of each model (MLflow), with its reports."""
as_of = date.fromisoformat(config.as_of) if config.as_of else None
found = {}
for name in config.models:
found[name] = cacu.train(name, as_of)
context.log.info(f"{name}: version {found[name]}")
return found
@dg.job
def train_cacu():
train_models()
class Scoring(dg.Config):
models: list[str] = list(CACU_MODELS)
@dg.op
def score_models(context: dg.OpExecutionContext, config: Scoring) -> dict:
"""Each model's champion scores its cohort; then gold's risk tables are rebuilt."""
found = {name: cacu.score(name) for name in config.models}
for name, version in found.items():
context.log.info(f"{name}: " + (f"version {version}" if version else "no champion"))
silver.build(["cacu_risk+"])
return found
@dg.job(tags=WRITES)
def score_cacu():
score_models()
defs = dg.Definitions(jobs=[ingest, train_cacu, score_cacu])
+6 -4
View File
@@ -257,12 +257,14 @@ def run_link(p: str, node: Link):
torn = set(spread[(spread > 1).any(axis=1)].index) if facts else set()
held = json.dumps(["records of this person disagree on birth date or sex"])
columns = {f: {"data_type": "text", "nullable": True} for f in (HELD, *fields)}
nodes.write(p, node.id, [
linked = [
{RECORD: r.unique_id, "person_id": r.cluster_id,
HELD: held if r.cluster_id in torn else None,
**{f: getattr(r, f) for f in fields}}
for r in persons.itertuples()
], columns) # fmt: skip
] # fmt: skip
nodes.write(p, node.id, linked, columns)
nodes.stage("identity", p, node.id, linked, silver.columns("identity")) # silver.person
# One row per person, so random pairs are different people and Splink's u is honest.
ids = [f for f in IDENTIFIERS if f in fields]
@@ -376,5 +378,5 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
RUNNERS[node.kind](pipeline_id, node)
log(f"{node.id} ({node.kind}) done")
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
silver.build(entities)
log(f"silver: {', '.join(entities)}")
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
log(f"silver and gold, from {', '.join(entities)}")