Sub topic 8
Grid search
Grid search is the simplest systematic way to pick hyperparameters. You list candidate values for each hyperparameter, train and score a model for every combination, and keep the best one. This chapter assumes you know basic Python, can fit and score a scikit-learn model, and have met cross-validation and train/test splits in earlier chapters.
How grid search works
You supply a set of values per hyperparameter. The grid is the Cartesian product of those sets. Each cell of the grid is one candidate setting. For each candidate, cross-validation gives an average score on the training data. The candidate with the best average wins.
The test set stays out of the loop until the last step. If you use test scores to choose among candidates, the test score stops being an honest estimate of how the model will do on new data.
A complete example
The example below tunes an RBF support vector classifier. C controls how strongly the model is penalized for training errors. gamma controls how far the influence of a single training point reaches.
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))Several details here matter.
- Pipeline prefixes.
make_pipelinenames each step after its lowercase class name. The grid keysvc__Cmeans "theCparameter of the step namedsvc". A misspelled key raises an error whenfitis called. - Scaling inside the pipeline. The scaler is refit on the training part of each fold, so statistics from the validation fold never leak into training.
stratify=y. It keeps the class proportions the same in both splits.search.score. After fitting, it uses the refit best model and the scorer you configured.
What `fit` actually does
This grid has 3 × 3 = 9 candidates. With 5 folds, that is 45 model fits during the search. By default, GridSearchCV then refits the best candidate on the whole training set, which is fit number 46. That refit model is available as search.best_estimator_, and search.predict uses it.
The refit step is why best_score_ and the test score differ. best_score_ is the mean cross-validation score of the winner, measured on folds that each used 80% of the training data. It is also biased upward, because it is the maximum over nine noisy estimates. Treat it as an optimistic number. The test score is the honest one.
The cost of a grid
Grid size multiplies across hyperparameters. The number of fits is the product of the value counts times the number of folds.
| Hyperparameters | Values each | Candidates | Fits with 5-fold CV |
|---|---|---|---|
| 2 | 5 | 25 | 125 |
| 4 | 5 | 625 | 3,125 |
| 6 | 5 | 15,625 | 78,125 |
Two consequences follow:
- Grid search is practical for roughly two to four hyperparameters. Past that, random search (next chapter) covers the space more cheaply.
- A grid spends effort unevenly. If only one of two hyperparameters really matters, a 3 × 3 grid tests just three distinct values of the important one. Nine random points would test nine.
Use n_jobs=-1 to run fits in parallel across CPU cores. Candidates and folds are independent, so the speedup is close to linear until you run out of cores or memory. Set verbose=2 to watch progress on long runs.
Conditional parameters with a list of grids
Some hyperparameters only make sense for certain values of others. gamma has no effect when the kernel is linear. A single dictionary would waste fits on meaningless combinations. GridSearchCV also accepts a list of dictionaries, and the grids are searched separately and then pooled.
import pandas as pd
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__kernel": ["linear"], "svc__C": [0.1, 1, 10]},
{
"svc__kernel": ["rbf"],
"svc__C": [0.1, 1, 10],
"svc__gamma": [0.001, 0.01, 0.1],
},
]
search = GridSearchCV(pipe, param_grid, cv=5, n_jobs=-1)
search.fit(X_train, y_train)
results = pd.DataFrame(search.cv_results_)
columns = [
"param_svc__kernel",
"param_svc__C",
"param_svc__gamma",
"mean_test_score",
"std_test_score",
"rank_test_score",
]
print(results[columns].sort_values("rank_test_score").head(5).to_string())This grid has 3 + 9 = 12 candidates instead of the 18 you would get from crossing every kernel with every C and gamma. For linear rows, the param_svc__gamma column shows as missing, because that parameter was never set.
Reading `cv_results_`
cv_results_ is a dictionary of arrays with one entry per candidate. The most useful keys are:
mean_test_scoreandstd_test_score: the average and spread across folds.rank_test_score: rank 1 is the best. Ties share a rank.mean_fit_timeandmean_score_time: what each candidate costs.param_*: the values tried.
Do not look at the winner alone. If the top five candidates differ by less than one std_test_score, the data cannot tell them apart. In that case, prefer the cheaper or simpler one. Scikit-learn's refit option can also be a function, which lets you encode a rule such as "the simplest model within one standard deviation of the best". The function receives cv_results_ and returns the index of the chosen candidate.
Choosing grid values
Pick values on the scale the hyperparameter works on. Regularization strengths, learning rates, and gamma act multiplicatively, so space them by powers of 10, or by factors of about 3 for finer resolution: [0.001, 0.01, 0.1, 1, 10]. Evenly spaced values such as [1, 2, 3, 4, 5] are appropriate for counts like max_depth or n_neighbors.
A widely used workflow is coarse to fine:
- Run a coarse grid over a wide range, such as powers of 10.
- Look at where the best scores sit.
- Run a second, denser grid around that region.
Always check whether the best value sits on the edge of the grid. If best_params_ shows C = 10 and 10 is your largest value, the true optimum may lie beyond it. Extend the grid in that direction and rerun.
Other settings that change results
scoring. The default for classifiers is accuracy. If classes are imbalanced, use"f1","roc_auc", or another metric that matches your goal. You can pass a list of metrics, but thenrefitmust name the one used to pick the winner.cv. An integer uses stratified k-fold for classifiers and plain k-fold for regressors. Pass a splitter object, such asStratifiedKFold(5, shuffle=True, random_state=0), when you need control over shuffling and seeds. For time series, useTimeSeriesSplitso folds never train on the future.error_score. Some combinations fail, for example an invalid solver and penalty pairing. By default, a failure is recorded asnanwith a warning, and the search continues. Seterror_score="raise"while developing so that bugs are not silently hidden.return_train_score=True. It adds training scores tocv_results_. A large gap between train and validation scores marks candidates that overfit.
When to choose grid search
Grid search fits when you have few hyperparameters, each with a small set of sensible values, and when you want a complete, easily explained record of what you tried. It is also good for final refinement of one or two parameters after a broader search. For many hyperparameters, continuous ranges, or an expensive model, move to random search or sequential methods.
Exercise
A grid has C with 4 values, gamma with 5 values, and kernel fixed to "rbf". You run GridSearchCV with cv=3 and default settings. How many model fits happen in total? After the search, best_params_ shows the largest value of C from your list. What should you do next?
Show answer
There are 4 × 5 = 20 candidates, and each is fit on 3 folds, so 60 fits. The default refit=True adds one final fit of the best candidate on the whole training set, for 61 fits in total. A best value at the edge of the grid suggests the optimum may lie beyond it. Extend the C values upward (for example, add values 10 times and 100 times larger), rerun the search, and check whether the best value moves inside the grid.