Sub topic 12
Tuning without fooling yourself
This chapter assumes you can fit scikit-learn estimators, build a Pipeline, and run cross_val_score. It also assumes you have read the earlier chapters on validation, leakage, and gradient-boosted trees. Here the question is how to adjust hyperparameters and still report an honest score.
Why tuning can mislead you
A hyperparameter is a setting you choose before training, such as a learning rate or the maximum number of leaves per tree. The model does not learn it from the data. You pick it by trying values and keeping the one that scores best.
That selection step is the problem. Suppose you try 50 settings and report the best cross-validation score. Each score has noise, and the maximum of 50 noisy numbers is biased upward. The reported number is partly skill and partly luck. The more settings you try, and the smaller your data, the larger this optimism becomes.
The fix is to keep two jobs apart:
- Selection: choosing the best setting, using data the search is allowed to see.
- Estimation: judging how well the whole procedure works, using data the search never saw.
What to tune first
Not every setting matters equally. Spend your budget on the few that change model behavior the most.
| Model | Settings that usually matter | Settings you can often leave alone |
|---|---|---|
| Logistic regression | `C` (inverse regularization strength), penalty type | Solver, tolerance |
| Random forest | `max_features`, `min_samples_leaf`, `max_depth` | `n_estimators` (more is rarely worse, only slower) |
| Gradient boosting | `learning_rate`, `max_leaf_nodes`, `l2_regularization`, number of iterations | `max_bins` |
For boosting, the learning rate and the number of iterations trade off against each other. A lower learning rate needs more iterations. Early stopping handles the iteration count for you: HistGradientBoostingClassifier can hold out part of the training data and stop when the score stops improving. Set a low learning rate, allow many iterations, and let early stopping pick the count. Then you only tune the learning rate and the tree size.
Search strategies
Grid search tries every combination from lists you provide. It is simple and reproducible, but the cost grows multiplicatively. Three settings with five values each is 125 fits per fold.
Random search draws combinations from distributions. It works well when only a few settings matter, because each trial tests a new value of every setting. A grid wastes trials repeating the same value of an important setting while varying an unimportant one. For scale-like settings such as learning rates, sample on a log scale, for example loguniform(0.01, 0.3).
Successive halving (HalvingRandomSearchCV) starts many candidates on a small amount of data and keeps only the best ones for larger amounts. It is cheaper when fits are slow, but early rounds use small samples, so noisy candidates can be dropped by mistake. It is still experimental in scikit-learn and needs an extra import.
Bayesian optimization libraries such as Optuna choose the next trial based on earlier results. They help when each fit is expensive. For most tabular problems with a modest budget, random search is a good default.
The nested cross-validation pattern
Nested cross-validation puts a search inside each fold of an outer loop:
- The outer loop splits the data into training and test parts.
- On each outer training part, the inner loop runs the search with its own cross-validation and picks the best setting.
- The search refits on the whole outer training part with that setting.
- The outer test part scores the refitted model. The search never saw it.
The average of the outer scores estimates how well the whole procedure performs: "tune with this search, then fit." It does not estimate the performance of one specific setting.
The code below runs this pattern. The RandomizedSearchCV object is itself an estimator, so passing it to cross_val_score gives you the nesting. It continues from the earlier examples, which define X, y, preprocess, and cv.
from scipy.stats import loguniform
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
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_scores = cross_val_score(search, X, y, cv=cv, scoring="roc_auc")
print(outer_scores.mean().round(3), outer_scores.std().round(3))Three details matter here:
- The parameter names use the pipeline step name, a double underscore, then the parameter.
make_pipelinelowercases the class name to make the step name. - The preprocessing is inside the pipeline, so the imputer, scaler, and encoder are refitted on each inner training part. Preprocessing outside the pipeline would leak statistics from the validation rows into the search.
- The inner and outer splitters have different seeds. Using the same splits for both is not wrong, but different seeds make the two loops less correlated.
Cost
Nested cross-validation is expensive. This example fits 5 outer folds × 3 inner folds × 10 candidates = 150 inner fits, plus 5 refits. If that is too slow, reduce n_iter, use fewer outer folds, or pass n_jobs=-1 to run fits in parallel.
Two uses of the outer score
Nested cross-validation answers "how good is this procedure?" It does not produce the final model. To get one, run the search once on all your training data and keep best_estimator_.
final_search = search.fit(X, y)
print(final_search.best_params_)
print(round(final_search.best_score_, 3))The best_score_ from this fit is the optimistic number described earlier. Do not report it as your expected performance. Report the nested score instead. If you also have a final held-out test set, score the fitted search on it once, at the very end.
Common ways tuning goes wrong
- Peeking at the test set. Every time you look at the test score and then change something, the test set becomes part of tuning. Use it once.
- Tuning only the favorite model. If you spend hours tuning gradient boosting and use defaults for the linear model, a win for boosting may reflect effort, not model quality. Give each candidate a comparable budget.
- Treating small gaps as real. If two settings differ by less than the standard deviation across folds, you cannot tell them apart. Prefer the simpler or faster one.
- Search ranges that are too narrow. If the best value sits at the edge of your range, extend the range and search again.
- Preprocessing outside the pipeline. Fitting an imputer or encoder on the full dataset before the search leaks information into every fold.
- Ignoring variance in the final choice. Look at
search.cv_results_and check the spread (std_test_score), not only the mean.
You can inspect the search results as a table:
import pandas as pd
results = pd.DataFrame(final_search.cv_results_)
columns = ["mean_test_score", "std_test_score", "rank_test_score"]
print(results.sort_values("rank_test_score")[columns].head())If the top five candidates are within one standard deviation of each other, the search found a plateau. Any of them is a reasonable choice, and the difference is not worth chasing.
Exercise
You run RandomizedSearchCV with 40 candidates on a 5-fold split and report the bestscore as your expected performance on new data. A colleague says the number is too high. Why is the colleague right, and what would you change?
Show answer
bestscore is the maximum over 40 noisy cross-validation scores, so it is biased upward, and the same folds both selected the winner and scored it. To get an honest estimate, wrap the search in an outer cross-validation (nested cross-validation) and report the outer scores, or score the final fitted search once on a held-out test set that tuning never touched.
Exercise
A search over maxleafnodes in [15, 31, 63] returns 63 as the best value for every run. What should you do next?
Show answer
The best value is at the edge of the range, so the true optimum may be larger. Extend the range (for example add 127 and 255), rerun the search, and check whether the score keeps improving or levels off. Also check the standard deviation across folds to see if the gain is larger than the noise.