Sub topic 8
Grid search
This chapter assumes you know basic Python, can train and score a scikit-learn model, and understand cross-validation and the difference between a validation set and a test set.
What grid search does
Grid search is an exhaustive search over a fixed set of hyperparameter values. You list candidate values for each hyperparameter. The search builds every combination, scores each one with cross-validation, and keeps the best.
With 3 values of C and 3 values of gamma, the grid has 9 combinations. With 5-fold cross-validation, that is 45 model fits. The cost is the product of the list lengths times the number of folds.
A worked example
The pipeline scales the features and then fits a support vector classifier. Parameter names use the step__parameter form, so svc__C means the C of the step named svc.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {
"svc__C": [0.1, 1, 10],
"svc__gamma": [0.001, 0.01, 0.1],
}
search = GridSearchCV(pipe, param_grid, cv=5, scoring="accuracy")
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)
print("Test accuracy:", search.score(X_test, y_test))Three points about this code:
- The search sees only
X_train. Cross-validation splits it internally, so the test set stays untouched until the last line. - Because the scaler is inside the pipeline, it is refit on each training fold. This keeps the validation fold from influencing the scaling.
- By default
refit=True. After the search, scikit-learn refits the best combination on all ofX_train.search.scoreandsearch.predictuse that refit model.
Reading the results
best_score_ is the mean cross-validated score of the winning combination. It is optimistic, because you picked it as the maximum of several noisy estimates. Use search.cv_results_ to see every combination, including mean_test_score and std_test_score. If several combinations differ by less than the standard deviation, the data cannot separate them.
If the best value sits on the edge of your grid, such as C=10 when 10 is the largest value, the true optimum may lie outside it. Extend the grid in that direction and run again.
When grid search fits and when it doesn't
| Situation | Grid search? |
|---|---|
| 1 or 2 hyperparameters, few values | Good fit |
| You want a complete, easy-to-plot picture | Good fit |
| 4 or more hyperparameters | Cost grows multiplicatively, so it becomes expensive |
| Some hyperparameters barely matter | Wasteful, since it repeats the same values of the important ones |
Space values on a log scale for hyperparameters like C and gamma. Linear spacing such as [1, 2, 3] wastes the grid when the useful range spans orders of magnitude. The next chapter covers random search, which handles larger spaces better.
Exercise
A grid has 4 values of n_estimators, 3 values of max_depth, and 5 values of min_samples_leaf. You run GridSearchCV with cv=5 and the default refit. How many model fits happen in total, and why is the bestscore an optimistic estimate?
Show answer
There are 4 × 3 × 5 = 60 combinations, so 60 × 5 = 300 cross-validation fits, plus 1 final refit on all training data, for 301. The bestscore is optimistic because it is the maximum over 60 noisy scores. The winner is partly selected for lucky fold splits, so a held-out test set will usually score slightly lower.