Fitting steps every scenario shares: a temporal split, the classifier chosen by config, the fit and its metrics
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
"""Fitting a classifier on labelled members and measuring it: the steps every scenario shares.
|
||||
|
||||
A scenario's own module produces `labelled_members` (one row per member whose outcome is known, its predictors and
|
||||
the outcome) and the driver passes both modules to `with_modules`, with `predictor_columns`, `train_fraction` and the
|
||||
`classifier` config. Each node is named after what it produces. No node reads, writes or logs: registering the result
|
||||
is a saver's job.
|
||||
|
||||
The classifier is chosen by config: `@config.when(classifier=...)` picks one `prefit_classifier`, so another
|
||||
classifier is one more function here and no change to any scenario.
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
from hamilton.function_modifiers import config, extract_fields
|
||||
from sklearn.base import ClassifierMixin, clone
|
||||
from sklearn.compose import ColumnTransformer
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
from sklearn.pipeline import Pipeline
|
||||
from sklearn.preprocessing import OneHotEncoder
|
||||
|
||||
SPLIT_ORDER = ("fecha_indice", "pac_id")
|
||||
PROBABILITY = "probabilidad"
|
||||
|
||||
|
||||
@extract_fields({"train_set": pd.DataFrame, "test_set": pd.DataFrame})
|
||||
def train_test_split(labelled_members: pd.DataFrame, train_fraction: float, target_column: str = "y",
|
||||
split_order: tuple = SPLIT_ORDER) -> dict:
|
||||
"""The oldest members by `split_order` train and the newest test: a model is judged on cases later than the ones
|
||||
it learned from, never on a shuffled mix."""
|
||||
if target_column not in labelled_members.columns:
|
||||
raise ValueError(f"labelled_members has no {target_column!r} column")
|
||||
ordered = labelled_members.sort_values(list(split_order), kind="stable")
|
||||
cut = int(len(ordered) * train_fraction)
|
||||
return {"train_set": ordered.iloc[:cut], "test_set": ordered.iloc[cut:]}
|
||||
|
||||
|
||||
def encoder(predictor_columns: list[str]) -> ColumnTransformer:
|
||||
"""One-hot predictors; a category not seen in training counts as none of the known ones."""
|
||||
return ColumnTransformer([("predictors", OneHotEncoder(handle_unknown="ignore"), list(predictor_columns))])
|
||||
|
||||
|
||||
@config.when(classifier="logistic")
|
||||
def prefit_classifier__logistic(max_iter: int = 1000) -> ClassifierMixin:
|
||||
"""An unfitted logistic regression."""
|
||||
return LogisticRegression(max_iter=max_iter)
|
||||
|
||||
|
||||
def fitted_pipeline(encoder: ColumnTransformer, prefit_classifier: ClassifierMixin, train_set: pd.DataFrame,
|
||||
predictor_columns: list[str], target_column: str = "y") -> Pipeline:
|
||||
"""The encoder and the classifier fitted on `train_set`. Fits copies, so the prefit nodes stay unfitted."""
|
||||
pipeline = Pipeline([("encode", clone(encoder)), ("classify", clone(prefit_classifier))])
|
||||
return pipeline.fit(train_set[list(predictor_columns)], train_set[target_column])
|
||||
|
||||
|
||||
def test_probabilities(fitted_pipeline: Pipeline, test_set: pd.DataFrame, predictor_columns: list[str]) -> pd.Series:
|
||||
"""The probability of the outcome for each row of `test_set`."""
|
||||
return pd.Series(fitted_pipeline.predict_proba(test_set[list(predictor_columns)])[:, 1], index=test_set.index,
|
||||
name=PROBABILITY)
|
||||
|
||||
|
||||
def auc(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
|
||||
"""Area under the ROC curve on `test_set`; undefined (an error) when the test set has a single class."""
|
||||
return float(roc_auc_score(test_set[target_column], test_probabilities))
|
||||
|
||||
|
||||
def brier_score(test_set: pd.DataFrame, test_probabilities: pd.Series, target_column: str = "y") -> float:
|
||||
return float(brier_score_loss(test_set[target_column], test_probabilities))
|
||||
|
||||
|
||||
def positive_rate_train(train_set: pd.DataFrame, target_column: str = "y") -> float:
|
||||
return float(train_set[target_column].mean())
|
||||
|
||||
|
||||
def positive_rate_test(test_set: pd.DataFrame, target_column: str = "y") -> float:
|
||||
return float(test_set[target_column].mean())
|
||||
|
||||
|
||||
def mean_probability_test(test_probabilities: pd.Series) -> float:
|
||||
return float(test_probabilities.mean())
|
||||
|
||||
|
||||
def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: pd.DataFrame,
|
||||
positive_rate_train: float, positive_rate_test: float, mean_probability_test: float) -> dict:
|
||||
"""What a training run records: aggregates only, no patient data. The keys are the names MLflow keeps."""
|
||||
return {"auc": auc, "brier": brier_score, "n_train": len(train_set), "n_test": len(test_set),
|
||||
"positive_rate_train": positive_rate_train, "positive_rate_test": positive_rate_test,
|
||||
"mean_probability_test": mean_probability_test}
|
||||
@@ -0,0 +1,119 @@
|
||||
"""What this module covers: `models.steps.model_fitting` run by a Hamilton driver built from that module alone, the
|
||||
way a scenario's driver uses it: the temporal split, the classifier chosen by config, the fit and the metrics.
|
||||
|
||||
Fixtures: `labelled`, forty members with index dates one day apart, one categorical predictor (`resultado`: `A` is
|
||||
always positive, `B` never) and `y`; `_driver` builds the driver with `classifier = "logistic"` unless told
|
||||
otherwise, and `_run` executes nodes with the three required inputs.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||
|
||||
from models.steps import model_fitting
|
||||
|
||||
PREDICTORS = ["resultado"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def labelled() -> pd.DataFrame:
|
||||
"""Forty members, `pac_id` 1..40, index dates from 2025-01-01 one day apart in reverse `pac_id` order (so the
|
||||
oldest is member 40). Members whose `pac_id` is divisible by 4 have `resultado` `A` and `y` 1, the rest `B`
|
||||
and `y` 0."""
|
||||
rows = [{"pac_id": n, "fecha_indice": date(2025, 1, 1) + timedelta(days=40 - n),
|
||||
"resultado": "A" if n % 4 == 0 else "B", "y": int(n % 4 == 0)} for n in range(1, 41)]
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _driver(config: dict | None = None):
|
||||
return driver.Builder().with_modules(model_fitting).with_config(
|
||||
{"classifier": "logistic"} if config is None else config).build()
|
||||
|
||||
|
||||
def _run(nodes: list[str], labelled: pd.DataFrame, config: dict | None = None, **inputs) -> dict:
|
||||
required = {"labelled_members": labelled, "predictor_columns": PREDICTORS, "train_fraction": 0.75}
|
||||
return _driver(config).execute(nodes, inputs={**required, **inputs})
|
||||
|
||||
|
||||
def test_the_oldest_members_train_and_the_newest_test(labelled):
|
||||
"""Pins down the temporal split: with 0.75, the 30 oldest index dates train and the 10 newest test, and every
|
||||
member is in exactly one of them. Fails if the split shuffles, ignores the index date or loses rows."""
|
||||
result = _run(["train_set", "test_set"], labelled)
|
||||
train, test = result["train_set"], result["test_set"]
|
||||
assert len(train) == 30 and len(test) == 10
|
||||
assert train["fecha_indice"].max() < test["fecha_indice"].min()
|
||||
assert sorted(train["pac_id"].tolist() + test["pac_id"].tolist()) == list(range(1, 41))
|
||||
|
||||
|
||||
def test_the_driver_needs_only_the_members_the_predictors_and_the_fraction(labelled):
|
||||
"""Pins down the dataflow's external inputs: the three required ones; `target_column`, `split_order` and
|
||||
`max_iter` have defaults. Fails if a node reads a setting from a global or the disk instead of taking it as an
|
||||
input, or if a new input appears without a default."""
|
||||
required = {v.name for v in _driver().list_available_variables()
|
||||
if v.is_external_input and v.originating_functions and not _has_default(v)}
|
||||
assert required == {"labelled_members", "predictor_columns", "train_fraction"}
|
||||
|
||||
|
||||
def _has_default(variable) -> bool:
|
||||
for function in variable.originating_functions:
|
||||
parameter = inspect.signature(function).parameters.get(variable.name)
|
||||
if parameter is not None and parameter.default is inspect.Parameter.empty:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def test_the_classifier_is_chosen_by_config(labelled):
|
||||
"""Pins down `@config.when`: with `classifier = "logistic"` the prefit node is an unfitted logistic regression,
|
||||
and without a known classifier there's no `prefit_classifier` to fit with. Fails if the classifier is built
|
||||
inside `fitted_pipeline` again or the config key changes."""
|
||||
prefit = _run(["prefit_classifier"], labelled)["prefit_classifier"]
|
||||
assert type(prefit).__name__ == "LogisticRegression" and not hasattr(prefit, "coef_")
|
||||
with pytest.raises(ValueError):
|
||||
_run(["fitted_pipeline"], labelled, config={"classifier": "unknown"})
|
||||
|
||||
|
||||
def test_fitting_leaves_the_prefit_nodes_unfitted(labelled):
|
||||
"""Pins down that `fitted_pipeline` fits copies: the `encoder` and `prefit_classifier` values the driver computed
|
||||
stay unfitted. Fails if the fit mutates them, which would leak one run's fit into anything else that reads them."""
|
||||
result = _run(["encoder", "prefit_classifier", "fitted_pipeline"], labelled)
|
||||
assert not hasattr(result["prefit_classifier"], "coef_")
|
||||
assert not hasattr(result["encoder"], "transformers_")
|
||||
assert hasattr(result["fitted_pipeline"].named_steps["classify"], "coef_")
|
||||
|
||||
|
||||
def test_metrics_are_sklearn_s_on_the_test_set_under_the_names_mlflow_keeps(labelled):
|
||||
"""Pins down `metrics`: AUC and Brier computed on the test set's `y` and probabilities, the sizes and rates, with
|
||||
the keys training runs have always recorded. Fails if a metric is computed on the wrong set or a key is renamed
|
||||
(a renamed key splits a model's history in MLflow)."""
|
||||
result = _run(["metrics", "test_set", "test_probabilities"], labelled)
|
||||
test, probabilities, metrics = result["test_set"], result["test_probabilities"], result["metrics"]
|
||||
assert set(metrics) == {"auc", "brier", "n_train", "n_test", "positive_rate_train", "positive_rate_test",
|
||||
"mean_probability_test"}
|
||||
assert metrics["auc"] == pytest.approx(roc_auc_score(test["y"], probabilities))
|
||||
assert metrics["brier"] == pytest.approx(brier_score_loss(test["y"], probabilities))
|
||||
assert (metrics["n_train"], metrics["n_test"]) == (30, 10)
|
||||
assert metrics["positive_rate_test"] == pytest.approx(test["y"].mean())
|
||||
assert probabilities.name == "probabilidad" and probabilities.index.equals(test.index)
|
||||
|
||||
|
||||
def test_an_unseen_category_scores_as_none_of_the_known_ones(labelled):
|
||||
"""Pins down the encoder's `handle_unknown="ignore"`: a test member with a category training never saw still
|
||||
gets a probability, between the two known categories'. Fails if the encoder raises on unknown categories."""
|
||||
pipeline = _run(["fitted_pipeline"], labelled)["fitted_pipeline"]
|
||||
a, b, c = pipeline.predict_proba(pd.DataFrame({"resultado": ["A", "B", "C"]}))[:, 1]
|
||||
assert b < c < a
|
||||
|
||||
|
||||
def test_no_node_reads_writes_or_logs():
|
||||
"""Pins down that the module imports nothing that does I/O (MLflow, the registry, storage, tracking). Fails if a
|
||||
node starts logging or registering again instead of leaving that to a saver."""
|
||||
tree = ast.parse(inspect.getsource(model_fitting))
|
||||
imported = {alias.name for node in ast.walk(tree) if isinstance(node, ast.Import) for alias in node.names}
|
||||
imported |= {node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom)}
|
||||
assert not {name for name in imported if name.split(".")[0] in {"mlflow", "persistance"}
|
||||
or name.startswith("models.io")}
|
||||
Reference in New Issue
Block a user