Sub topic 12
Tuning Hyperparameters with a Grid Search
This chapter assumes you have read the earlier chapters of the project. You should know the train/test split, cross-validation with cross_val_score, and the Ridge and HistGradientBoostingRegressor models. It reuses X_train, y_train, X_test and y_test from the split step. Their random_state is 42, which makes results repeatable.
Parameters and hyperparameters
A model has two kinds of numbers that shape its behavior.
- Parameters are learned from data during
fit. Examples are the coefficients of Ridge and the split thresholds inside each boosted tree. - Hyperparameters are set by you before
fit. Examples arelearning_rate,max_leaf_nodesand Ridge'salpha.
The training algorithm cannot choose hyperparameters for you. Its objective is to fit the training data, and a more flexible setting will nearly always fit that data better. You need an outside measurement, and cross-validation provides it. Tuning means trying candidate settings and keeping the one with the best cross-validated score.
What a grid search does
A grid search takes a dictionary that maps each hyperparameter name to a list of values. It builds every combination, scores each one with cross-validation, and picks the best. Scikit-learn implements this as GridSearchCV.
With the grid used in this project, learning_rate has 2 values and max_leaf_nodes has 3. That gives 2 × 3 = 6 combinations. With cv=3, each combination is fitted 3 times, so the search runs 18 fits. By default it then runs one more fit: it refits the best combination on the whole training set.
Running the search
This script runs from top to bottom. It loads the data, splits it and tunes the boosting model.
from sklearn.datasets import fetch_california_housing
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import GridSearchCV, train_test_split
housing = fetch_california_housing(as_frame=True)
df = housing.frame
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
param_grid = {
"learning_rate": [0.05, 0.1],
"max_leaf_nodes": [15, 31, 63],
}
search = GridSearchCV(
HistGradientBoostingRegressor(random_state=42),
param_grid,
cv=3,
scoring="neg_mean_absolute_error",
)
search.fit(X_train, y_train)
print("Best params:", search.best_params_)
print("Best CV MAE:", -search.best_score_)
best_model = search.best_estimator_Several details in this script matter.
search.fit(X_train, y_train)never sees the test set. The cross-validation folds are carved out of the training data.scoring="neg_mean_absolute_error"follows scikit-learn's rule that a higher score is always better. Error metrics are therefore negated.best_score_is a negative number, and you flip the sign to read it as MAE.best_score_is the mean validation score of the winning combination. It is not a test score.best_estimator_is the refitted model. It is a normal fitted estimator, so you can callpredicton it directly.random_state=42on the model keeps runs comparable. Otherwise, differences between candidates could partly come from randomness inside the model.
Reading the full results
The winner is only part of the story. The attribute cv_results_ records the mean and standard deviation of the score for every combination. Loading it into a DataFrame shows how sensitive the model is to each setting.
import pandas as pd
results = pd.DataFrame(search.cv_results_)
results["mean_cv_mae"] = -results["mean_test_score"]
columns = [
"param_learning_rate",
"param_max_leaf_nodes",
"mean_cv_mae",
"std_test_score",
"rank_test_score",
]
print(results[columns].sort_values("rank_test_score").to_string(index=False))Look at two things in this table.
- The gap between the best and worst combination. If all six rows differ by a hundredth of MAE, tuning barely mattered and the default settings were fine.
- The size of
std_test_scorecompared with the gaps between ranks. If the standard deviation is as large as the gap between rank 1 and rank 2, those two settings are effectively tied. Prefer the simpler or faster one.
When the best value sits on the edge
Suppose the winning max_leaf_nodes is 63, the largest value you offered. The true optimum may lie beyond it. Extend the grid in that direction and search again, for example with [63, 127, 255]. If the winner is in the middle of the range, the grid has bracketed the optimum and you can stop. The same applies at the lower end of a range.
A practical workflow has two passes. First run a coarse grid with widely spaced values, such as alpha in [0.01, 1, 100]. Then run a finer grid around the winner.
Tuning a pipeline
When the estimator is a pipeline, hyperparameter names need a prefix. The prefix is the step name, followed by two underscores. make_pipeline names each step after its lowercase class name.
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
ridge = make_pipeline(StandardScaler(), Ridge())
ridge_search = GridSearchCV(
ridge,
{"ridge__alpha": [0.01, 0.1, 1, 10, 100]},
cv=5,
scoring="neg_mean_absolute_error",
)
ridge_search.fit(X_train, y_train)
print("Best alpha:", ridge_search.best_params_)
print("Ridge CV MAE:", -ridge_search.best_score_)Here GridSearchCV clones the whole pipeline for each fold, so the scaler is refitted on each training fold only. Tuning therefore leaks nothing from the validation fold. If you scaled the data before the search, every fold would have seen statistics computed from its own validation rows. This is the leakage problem from the earlier chapter, now happening inside a search.
Run this and compare its best MAE with the boosting model's. The scores come from the same kind of cross-validation, so you can compare them directly. Use the same cv value for both searches if you want a fair comparison.
The cost of a grid
The number of fits grows multiplicatively. Every hyperparameter you add multiplies the total.
| Grid | Combinations | cv | Total fits |
|---|---|---|---|
| 2 × 3 (this project) | 6 | 3 | 18 |
| 4 × 4 | 16 | 5 | 80 |
| 4 × 4 × 5 | 80 | 5 | 400 |
| 5 × 5 × 5 × 5 | 625 | 5 | 3125 |
Three options keep the cost under control.
- Set
n_jobs=-1onGridSearchCV. It runs fits in parallel across your CPU cores. Boosting also uses several threads, so on small machines parallelism may help less than you expect. - Tune only the few hyperparameters that matter most. For boosting,
learning_rateandmax_leaf_nodesare usual first choices. - Switch to
RandomizedSearchCV. It samples a fixed number of combinations from your ranges, set byn_iter, instead of trying them all. It is often a better choice when the grid is large. This project keeps the full grid because it is small and easy to read.
Overfitting the validation scores
Cross-validation scores are estimates with noise. When you compare many combinations, the best one is partly the luckiest. Its best_score_ is therefore slightly optimistic, and the more combinations you try, the larger the effect. Two habits protect you:
- Keep grids modest, so you do not hunt through hundreds of nearly identical models.
- Judge the final model on the test set, which was never involved in any choice. The test score is lower than
best_score_in many projects. A small gap is normal. A large gap is a warning.
Common mistakes
- Reading
best_score_as an MAE. It is negated. - Forgetting the step prefix with pipelines, which raises an error such as an invalid parameter name. Call
ridge.get_params().keys()to list valid names. - Calling
search.fiton the full dataset. The test rows then take part in cross-validation, which leaks them into the choices. - Comparing searches that used different
cvvalues or different scoring metrics. - Treating a tiny score difference as meaningful without checking
std_test_score.
After tuning, the next step is to run best_model.predict(X_test) once and report the final metrics.
Exercise
A grid search has paramgrid = {"learningrate": [0.05, 0.1, 0.2], "maxleafnodes": [15, 31, 63, 127]} and cv=5. How many model fits does GridSearchCV run with the default refit? After it finishes, bestscore is -0.31. What does that number mean?
Show answer
There are 3 × 4 = 12 combinations, each fitted 5 times, so 60 fits, plus 1 refit of the best combination on the whole training set, for 61 in total. The value -0.31 means the best combination had a mean cross-validated MAE of 0.31, which is about $31,000 because the target is in units of $100,000. It is a validation estimate from the training data, not a test score.
Exercise
You tune makepipeline(StandardScaler(), Ridge()) and pass {"alpha": [0.1, 1, 10]} to GridSearchCV. It raises an error about an invalid parameter. What is the fix, and why is it better to tune the whole pipeline than to scale Xtrain first?
Show answer
Use the step prefix: {"ridge_alpha": [0.1, 1, 10]}. Tuning the whole pipeline refits the scaler on each training fold only, so the validation fold does not influence the scaling statistics. Scaling Xtrain once before the search would let every validation fold affect the scaler, which is data leakage and makes the CV scores optimistic.
Exercise
The best maxleafnodes in your grid [15, 31, 63] is 63. What should you do next, and why?
Show answer
Extend the grid upward, for example [63, 127, 255], and search again. A winner at the edge of the grid suggests the optimum may lie outside the range you tried. If the new winner is in the interior of the range, you have bracketed the optimum.