Sub topic 12
Tuning without fooling yourself
This chapter assumes you can build a scikit-learn pipeline, run cross_val_score, and know why preprocessing must be fitted inside each fold. Those topics come from the earlier chapters on validation and pipelines.
Why tuning inflates scores
A hyperparameter is a setting you choose before training, such as a tree's max_leaf_nodes or a boosting learning_rate. Tuning means trying many settings and keeping the best one.
The problem is selection bias. If you try 50 settings and report the best cross-validation score, that number is the maximum of 50 noisy estimates. Part of it is luck. The more settings you try, the more optimistic the reported score becomes, and the effect is largest on small datasets.
Search strategies
Grid search tries every combination in a fixed grid. The cost grows multiplicatively with each parameter you add. Random search samples settings from distributions, and it usually finds a good region faster. This is because only a few hyperparameters tend to matter, and random sampling tries many distinct values of each one.
- Sample continuous parameters such as
learning_rateon a log scale, for example withloguniform. - Use a list for discrete choices such as
max_leaf_nodes. - Set
random_stateso the search can be repeated.
Nested cross-validation
Nested cross-validation separates choosing a setting from judging the result. The outer loop splits the data into train and test folds. Inside each outer training fold, an inner loop runs the search and picks a setting. The outer test fold is never seen by the search, so its score estimates how well the whole procedure (search plus final fit) performs on new data.
In scikit-learn, pass the search object itself to cross_val_score. This runs the whole search again inside every outer fold.
import numpy as np
import pandas as pd
from scipy.stats import loguniform
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, cross_val_score
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"]),
])
search = RandomizedSearchCV(
make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
param_distributions={
"histgradientboostingclassifier__learning_rate": loguniform(0.01, 0.3),
"histgradientboostingclassifier__max_leaf_nodes": [15, 31, 63],
},
n_iter=10,
cv=StratifiedKFold(n_splits=3, shuffle=True, random_state=1),
scoring="roc_auc",
random_state=0,
)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
outer_scores = cross_val_score(search, X, y, cv=outer_cv, scoring="roc_auc")
print(outer_scores.mean().round(3), outer_scores.std().round(3))The parameter names use the pattern <step name>__<parameter>, where make_pipeline lowercases the class name to form the step name. A misspelled key raises an error when the search is fitted.
Common errors
- Reporting
best_score_as the final estimate. That value comes from the same folds that chose the winner, so it is optimistic. Use the nested score instead. - Tuning on the final test set. After you look at a test score and change something, that data has become validation data.
- Tuning outside the pipeline. If the search sees data that was already scaled or imputed on all rows, information leaks across folds.
- Tuning only the finalist. Giving one model a large search and the others defaults makes the comparison unfair. Give each candidate a similar budget.
Reading the result
Compare the outer mean with the spread across outer folds. If the gap between two models is smaller than the standard deviation, treat them as tied and decide on cost, speed, or interpretability. Nested cross-validation multiplies the work, here 5 × 3 × 10 model fits plus refits, so keep n_iter modest for large data.
Exercise
A colleague tunes a model with GridSearchCV on 5 folds, then reports best_score_ as expected performance on new data. Why is this too optimistic, and what change fixes it?
Show answer
best_score_ is the highest of many cross-validation scores, and the same folds were used to pick the winner. The selection favors settings that were lucky on those folds. Wrap the search in an outer cross-validation, for example cross_val_score(search, X, y, cv=outer_cv), or score the tuned model once on a test set that the search never touched.