Sub topic 15
A repeatable selection workflow
This chapter ties the earlier ones together into a procedure you can run on any new table. It assumes you know scikit-learn pipelines, cross-validation, and the model families covered so far: baselines, linear models, random forests, gradient boosting, and neural networks. The goal is a process that gives the same answer when someone else repeats it, and that leaves a record of why you chose what you chose.
Why a workflow at all
Without a fixed procedure, model selection drifts. You try a model you like, tune it for an hour, and compare it with an untuned alternative. You then pick the winner on a metric you chose after seeing the results. Each step is defensible alone. Together they produce an optimistic score and a choice you cannot reproduce.
A workflow fixes the decisions that must not depend on results. These are the metric, the folds, and the preprocessing. It then lets the candidate models vary.
The steps
1. Frame the problem and pick the metric
Write down the target, the prediction moment, and the cost of each error type. Choose one primary metric, such as ROC AUC for ranking or log loss for calibrated probabilities. Add at most a few secondary metrics. Do this before you look at any model score. If you change the metric afterwards, you are selecting for the metric as well as the model.
2. Fix the validation scheme
Pick the splitter that matches how the model will be used. Use StratifiedKFold for ordinary classification and GroupKFold when rows from one entity must stay together. Use TimeSeriesSplit when the future must not leak into the past. Set the random seed and reuse the same splitter object for every candidate. Hold out a final test set, if you have enough data, and do not touch it until step 7.
3. Build the pipeline and the baseline
Put all preprocessing inside a pipeline so that imputers, scalers, and encoders are fitted inside each training fold. Score a dummy model first. Every later number is judged against it.
4. Score candidates on identical folds
Run the baseline and a short list of models through the same splitter and metric. A reasonable short list is logistic or ridge regression, a random forest, and a gradient-boosted model. Add a neural network only if you have a reason, such as a large dataset or a need for shared representations. Record the fold mean, the fold standard deviation, and the timings.
5. Tune only the finalists
Tuning every candidate wastes time and increases the chance of a lucky result. Tune the top one or two, and use nested cross-validation so the reported score covers the whole tuning procedure. If tuning gains less than the fold noise, keep the defaults.
6. Apply practical constraints
Check latency, memory, interpretability requirements, and how much maintenance each model needs. Models whose scores fall within noise of each other are interchangeable on accuracy, so these constraints decide between them.
7. Record the decision and refit
Refit the chosen pipeline on all training data. Score it once on the held-out test set. Save the code, the library versions, the seeds, and the results table.
A reusable comparison harness
The code below turns steps 3, 4, and 6 into functions. It uses the same synthetic table as earlier chapters. The evaluate function returns one table with scores and timings. The pick_simplest function applies the one-standard-error rule. Among models whose mean score is within one standard error of the best, it takes the simplest one, using an order you supply.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
N_SPLITS = 5
cv = StratifiedKFold(n_splits=N_SPLITS, shuffle=True, random_state=0)
candidates = {
"baseline": make_pipeline(preprocess, DummyClassifier(strategy="prior")),
"logreg": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
"random_forest": make_pipeline(preprocess, RandomForestClassifier(n_estimators=200, random_state=0)),
"hist_gb": make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
}
def evaluate(candidates, X, y, cv, scoring="roc_auc"):
rows = []
for name, model in candidates.items():
res = cross_validate(model, X, y, cv=cv, scoring=scoring)
rows.append({
"model": name,
"mean": res["test_score"].mean(),
"std": res["test_score"].std(),
"fit_s": res["fit_time"].mean(),
"predict_s": res["score_time"].mean(),
})
return pd.DataFrame(rows).set_index("model").sort_values("mean", ascending=False)
def pick_simplest(results, order, n_splits):
best_name = results["mean"].idxmax()
threshold = results.loc[best_name, "mean"] - results.loc[best_name, "std"] / np.sqrt(n_splits)
for name in order:
if name in results.index and results.loc[name, "mean"] >= threshold:
return name
return best_name
results = evaluate(candidates, X, y, cv)
print(results.round(3))
print("choice:", pick_simplest(results, ["logreg", "random_forest", "hist_gb"], N_SPLITS))On this data the target is an XOR of an age threshold and a city indicator. A linear model cannot represent that interaction well, so the tree models should score clearly higher than logreg. In that case the simplicity rule does not choose the linear model, because its mean falls outside the tolerance. The rule only applies when the scores are close.
The fold standard deviation divided by the square root of the number of folds is a rough yardstick. Cross-validation folds share training rows, so their scores are correlated and the true uncertainty is larger. Treat the threshold as a tie-breaking convention.
What to record
Keep a short decision record next to the code. A table like this is enough:
| Item | Example entry |
|---|---|
| Metric and reason | ROC AUC, because the model ranks customers for outreach |
| Validation | 5-fold stratified, seed 0, held-out test set untouched |
| Baseline score | 0.500 |
| Candidates and scores | Mean and standard deviation per model, same folds |
| Tuning | Which models, which search space, nested score |
| Constraints | Latency budget, interpretability need, who maintains it |
| Final choice | Model name, library versions, refit date |
This record lets you re-run the comparison when data changes. It also lets a reviewer see which decisions were made before the results and which were made after.
Common failure modes
- Changing the splitter between candidates. Scores then reflect different data splits as well as different models.
- Reading the test set more than once. Each look turns the test set into another validation set.
- Preprocessing outside the pipeline. Fitting a scaler or imputer on all rows leaks fold statistics into training.
- Ignoring the baseline. A score of 0.92 means little until you know the baseline scores 0.90.
- Treating a small gap as a win. If two models differ by less than the fold standard deviation, you have no evidence that one is better.
- Stopping at one run. Repeat the comparison with a different fold seed when scores are close. If the ranking flips, the models are tied.
When to rerun the workflow
Rerun it when the data distribution changes, when the metric or business goal changes, or when a new library version changes defaults. Between those events, monitor the chosen model on live data. A drop in live performance is a reason to return to step 1, since the problem may no longer match your original framing.
Exercise
In the harness above, hist_gb has the best mean ROC AUC of 0.90 with a fold standard deviation of 0.02 over 5 folds. random_forest has a mean of 0.89, and logreg has a mean of 0.80. The order passed to pick_simplest is logreg, randomforest, histgb. Which model is chosen, and why?
Show answer
The threshold is 0.90 - 0.02 / sqrt(5), which is about 0.891. logreg at 0.80 falls below it. random_forest at 0.89 is also just below it, so it is rejected. hist_gb is the first model in the order that passes, so it is chosen. If the random forest had scored 0.895, it would have been chosen as the simpler model within tolerance.
Exercise
A colleague scores logistic regression with the default splitter and a random forest with a different seeded splitter. They report that the forest wins by 0.01 AUC. List two problems with this comparison and the fix for each.
Show answer
First, the models were scored on different folds, so the 0.01 gap may come from the splits. Fix this by creating one splitter object and passing it to both models. Second, a 0.01 gap may be within fold noise and no baseline is reported. Fix this by recording the mean and standard deviation for each model plus a dummy baseline, and by repeating with another seed before claiming a win.