Sub topic 12
Tuning Hyperparameters with a Grid Search
This chapter assumes you have a train/test split (X_train, X_test, y_train, y_test), know how cross_val_score works, and have a gradient boosting score from cross-validation to compare against. The test set stays untouched here.
Parameters and hyperparameters
A model learns its parameters from data. In a linear model these are the coefficients. A hyperparameter is a setting you choose before training, such as how fast the model learns or how complex each tree may be. The model cannot learn these from the data on its own, so you try several values and compare the results.
For HistGradientBoostingRegressor, two common hyperparameters are:
learning_rate: how much each new tree corrects the errors of the earlier trees. Smaller values learn more slowly and are often more stable.max_leaf_nodes: the maximum number of leaves per tree. More leaves let the model capture finer patterns, but raise the risk of overfitting.
How a grid search works
A grid search tries every combination of the values you list. Each combination is scored with cross-validation, and the best one wins. GridSearchCV then refits that best combination on the full training set.
With 2 learning rates and 3 leaf limits there are 6 combinations. With cv=3, scikit-learn fits 18 models, plus one final refit.
Running the search
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import HistGradientBoostingRegressor
df = fetch_california_housing(as_frame=True).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_The scoring name starts with neg_ because scikit-learn always treats a higher score as better. Error is lower-is-better, so the library negates it. Flip the sign when you print it, as the last lines do with best_score_.
Reading the results
search.cv_results_ holds the score of every combination. Load it into a DataFrame to see how sensitive the model is to each setting:
import pandas as pd
results = pd.DataFrame(search.cv_results_)
cols = ["param_learning_rate", "param_max_leaf_nodes", "mean_test_score"]
print(results[cols].sort_values("mean_test_score", ascending=False))If the best value sits at the edge of your grid, such as max_leaf_nodes=63, the true optimum may lie beyond it. Extend the grid in that direction and search again.
Common errors
- Tuning on the test set. If you pick settings by looking at test scores, the test score no longer estimates performance on new data. The search above sees only
X_train. - Grids that grow too fast. The number of fits is the product of the value counts, times
cv. Three parameters with five values each andcv=5means 625 fits. - Over-trusting small gaps. Two combinations that differ by a tiny amount in
mean_test_scoreare effectively tied. Prefer the simpler one. - Forgetting preprocessing. If your model needs a scaler, tune the whole pipeline so scaling is refit inside each fold. Parameter names then use the step prefix, such as
ridge__alpha.
Exercise
A grid has learning_rate with 3 values and max_leaf_nodes with 4 values, and you use cv=5. How many models does GridSearchCV fit during the search, not counting the final refit?
Show answer
There are 3 × 4 = 12 combinations, and each is fitted once per fold, so 12 × 5 = 60 fits.
Exercise
Your best learning_rate is 0.1, the largest value in the grid. What should you do, and why not check the test set?
Show answer
Extend the grid with larger values, such as 0.2, and rerun the search, because the best value may lie beyond the edge. Do not check the test set, because using it to choose settings makes the final test score an overly optimistic estimate.