dce29670a4
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
128 lines
7.2 KiB
Python
128 lines
7.2 KiB
Python
"""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 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.
|
|
"""
|
|
|
|
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}
|
|
|
|
|
|
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}
|