Sub topic 5
Tuning with cross-validated grid search
This chapter assumes you know how k-fold cross-validation works, what a hyperparameter is, and how to fit and score a scikit-learn estimator. Here you will see how GridSearchCV combines a grid of candidate settings with cross-validation to pick the best one.
The idea
A hyperparameter is a setting you choose before training, such as the regularization strength C of a support vector machine. To pick a value, you try several candidates and compare them. Cross-validation gives each candidate a fair score on data it was not trained on.
A grid search does this for every combination in a grid:
- List the values to try for each hyperparameter.
- Form every combination (the Cartesian product).
- For each combination, run k-fold cross-validation and average the fold scores.
- Choose the combination with the highest mean score.
- Refit a model with that combination on all the data you passed in.
A worked example
The code below tunes an SVM on the breast cancer dataset. The scaler sits inside a pipeline, so it is refit on the training part of every fold. Pipeline step names become prefixes in the grid: svc__C means the C parameter of the step named svc.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold
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)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(pipe, param_grid, cv=cv)
search.fit(X, y)
# This is the score of the best candidate on the same folds used to pick it.
print("best_score_ (optimistic):", search.best_score_)
print("best_params_:", search.best_params_)The grid has 3 values of C and 3 of gamma, so 9 candidates. With 5 folds, that is 45 fits, plus one final refit on all the data.
What the search stores
After fit, several attributes are available:
| Attribute | Meaning |
|---|---|
| `best_params_` | The winning hyperparameter combination |
| `best_score_` | Mean cross-validated score of the winner |
| `best_estimator_` | The pipeline refit on all data with `best_params_` |
| `cv_results_` | Per-candidate mean scores, standard deviations, and ranks |
Calling search.predict(X_new) or search.score(X_new, y_new) uses best_estimator_. So the search object can be used like any other estimator.
Common mistakes
- Tuning outside the pipeline. If you scale the whole dataset first and then search, the scaler has seen the validation folds. Put preprocessing in the pipeline.
- Wrong parameter names. A grid key such as
Cfails on a pipeline. Usestepname__param. Callpipe.get_params().keys()to list valid names. - Grids at the edge. If the best value sits at the border of your grid, the true optimum may lie outside it. Extend the grid in that direction.
- Reading
best_score_as a final result. This is the trap the next chapter explains.
Why `best_score_` is only a tuning number
Each candidate's mean score contains some luck from how the folds happened to fall. Taking the maximum over nine candidates tends to pick up some of that luck. The reported score is therefore biased upward. The effect grows with the number of candidates and shrinks with more data.
Exercise
A grid has 4 values for C, 5 values for gamma, and you use cv=3. How many model fits does GridSearchCV perform with the default refit=True?
Show answer
There are 4 × 5 = 20 candidates. With 3 folds that is 60 fits, plus 1 refit of the best candidate on all the data, so 61 fits in total.
Exercise
You wrote param_grid = {"C": [0.1, 1, 10]} for make_pipeline(StandardScaler(), SVC()) and got an error about an invalid parameter. What is the fix?
Show answer
Prefix the parameter with the pipeline step name: {"svc__C": [0.1, 1, 10]}. The step name is the lowercase class name that make_pipeline generates.