The classifier's routines join the fitting steps: analytic_method, class_balance, output_confidence and routines

They depend only on the fitted pipeline and the split, so every scenario that lists models.steps.model_fitting
records them; sampling and missing_data stay in cin2_logistic, which owns windowed_outcomes and index_sample_results.
Moved as written in the merge (git blame -C follows them to 1b45bc6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
2026-11-19 20:45:44 -06:00
parent 6fbf573999
commit dce29670a4
3 changed files with 49 additions and 44 deletions
+3 -39
View File
@@ -6,8 +6,9 @@ it's scored but left out of training and evaluation. The predictors are the inde
category, HPV, HPV 16/18), matched by the sample's source row, so the score is valid once those results are reported;
nothing after them is used.
The split, the classifier, the fit and the metrics are `models.steps.model_fitting`'s, listed with this module in
`model.toml`. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
The split, the classifier, the fit, the metrics and the classifier's routines (ML-01a) are
`models.steps.model_fitting`'s, listed with this module in `model.toml`; `sampling` and `missing_data`, the routines
that depend on this scenario's members and predictors, are here. `fitted_model` puts `IndexSampleResults` in front of the fitted pipeline, so the registered model is one
scikit-learn `Pipeline` that takes a build's long frame. Settings arrive as config, the cohort and its lineage through
loaders, and registering is the driver's saver (`models.dags.training`).
"""
@@ -17,7 +18,6 @@ from datetime import date
import pandas as pd
import pandera.pandas as pandera
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import brier_score_loss
from sklearn.pipeline import Pipeline
from models.annotations import checked_frame
@@ -117,39 +117,3 @@ def missing_data(index_sample_results: pd.DataFrame, train_set: pd.DataFrame, te
return {"method": f"un predictor sin resultado en la muestra índice es la categoría {MISSING!r}; nadie se excluye",
"members": missing(index_sample_results), "train": missing(train_set), "test": missing(test_set)}
def analytic_method(fitted_pipeline: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
classifier = fitted_pipeline.named_steps["classify"]
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
return {"method": "regresión logística sobre los predictores codificados one-hot",
"estimator": type(classifier).__name__, "settings": classifier.get_params(),
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, features), map(float, classifier.coef_[0])))}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline) -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = fitted_pipeline.named_steps["classify"].class_weight
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
"train": {str(k): int(v) for k, v in train_set["y"].value_counts().sort_index().items()},
"test": {str(k): int(v) for k, v in test_set["y"].value_counts().sort_index().items()}}
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, calibration_bins: int = 10) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
bins = pd.qcut(test_probabilities, q=min(calibration_bins, test_probabilities.nunique()), duplicates="drop")
table = pd.DataFrame({"p": test_probabilities, "y": test_set["y"]}).groupby(bins, observed=True).agg(
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
"brier": float(brier_score_loss(test_set["y"], test_probabilities)),
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
+40
View File
@@ -5,6 +5,10 @@ the outcome) and the driver passes both modules to `with_modules`, with `predict
`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 routines' records (ML-01a) a classifier leaves are here too: `analytic_method`, `class_balance` and
`output_confidence`, and `routines`, which gathers them with the scenario's own `sampling` and `missing_data` under the
kinds the registry checks before promoting.
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.
"""
@@ -85,3 +89,39 @@ def metrics(auc: float, brier_score: float, train_set: pd.DataFrame, test_set: p
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}
def analytic_method(fitted_pipeline: Pipeline) -> dict:
"""METODO_ANALITICO: the fitted model, its settings and its coefficients."""
classifier = fitted_pipeline.named_steps["classify"]
features = fitted_pipeline.named_steps["encode"].get_feature_names_out()
return {"method": "regresión logística sobre los predictores codificados one-hot",
"estimator": type(classifier).__name__, "settings": classifier.get_params(),
"intercept": float(classifier.intercept_[0]),
"coefficients": dict(zip(map(str, features), map(float, classifier.coef_[0])))}
def class_balance(train_set: pd.DataFrame, test_set: pd.DataFrame, fitted_pipeline: Pipeline) -> dict:
"""BALANCE_CLASES: how many of each class there were, and whether they were reweighted."""
weight = fitted_pipeline.named_steps["classify"].class_weight
return {"method": "ninguno: las clases se usan en su proporción observada" if weight is None else f"pesos {weight}",
"train": {str(k): int(v) for k, v in train_set["y"].value_counts().sort_index().items()},
"test": {str(k): int(v) for k, v in test_set["y"].value_counts().sort_index().items()}}
def output_confidence(test_set: pd.DataFrame, test_probabilities: pd.Series, calibration_bins: int = 10) -> dict:
"""CONFIANZA_SALIDA: on the test members, the predicted probability against the observed rate, by tenths."""
bins = pd.qcut(test_probabilities, q=min(calibration_bins, test_probabilities.nunique()), duplicates="drop")
table = pd.DataFrame({"p": test_probabilities, "y": test_set["y"]}).groupby(bins, observed=True).agg(
n=("y", "size"), mean_probability=("p", "mean"), observed_rate=("y", "mean"))
return {"method": "calibración en la prueba: probabilidad media contra frecuencia observada, por cuantiles",
"brier": float(brier_score_loss(test_set["y"], test_probabilities)),
"bins": [{"range": str(interval), "n": int(row.n), "mean_probability": float(row.mean_probability),
"observed_rate": float(row.observed_rate)} for interval, row in table.iterrows()]}
def routines(sampling: dict, missing_data: dict, analytic_method: dict, class_balance: dict,
output_confidence: dict) -> dict:
"""Each routine's record, by the kind it's stored under (ML-01a)."""
return {"MUESTREO": sampling, "DATOS_FALTANTES": missing_data, "METODO_ANALITICO": analytic_method,
"BALANCE_CLASES": class_balance, "CONFIANZA_SALIDA": output_confidence}
+6 -5
View File
@@ -50,13 +50,14 @@ def test_the_oldest_members_train_and_the_newest_test(labelled):
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."""
def test_the_driver_needs_only_the_members_the_predictors_the_fraction_and_the_scenarios_routines(labelled):
"""Pins down the dataflow's external inputs: the three required ones, and `sampling` and `missing_data`, the two
routines (ML-01a) only a scenario can write; `target_column`, `split_order`, `max_iter` and `calibration_bins` 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"}
assert required == {"labelled_members", "predictor_columns", "train_fraction", "sampling", "missing_data"}
def _has_default(variable) -> bool: