Sub topic 5
Tuning with cross-validated grid search
This chapter assumes you know what a hyperparameter is, how k-fold cross-validation splits data, and how to fit scikit-learn estimators and pipelines. It covers what GridSearchCV does step by step, how to read its results, and which details cause trouble in practice. The next chapter explains why the headline score it reports is too optimistic.
What a grid search does
A hyperparameter is a setting you choose before training, such as the regularization strength C of a support vector machine. Learning cannot set it for you, so you try several values and keep the one that works best. Cross-validation supplies the "works best" part.
Grid search is the simplest way to do this. You list candidate values for each hyperparameter, and the search tries every combination.
- Build the grid: the Cartesian product of all candidate lists.
- For each combination (a candidate), run k-fold cross-validation on the data you give it.
- Average each candidate's k validation scores.
- Pick the candidate with the highest mean score.
- Refit that candidate on all the data you gave the search.
A first search
The example below tunes an SVM on the breast cancer dataset. The scaler sits inside a pipeline, so each fold fits it only on that fold's training part.
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_)Three details matter here.
- Parameter names. Inside a pipeline, a parameter is addressed as
<step name>__<parameter>.make_pipelinenames the SVM stepsvc, so the grid key issvc__C. A wrong key raises an error atfittime, not at construction. - The grid is a product. Three values of
Cand three ofgammagive nine candidates. Adding a third hyperparameter with four values gives 36. - The
cvargument. If you pass an integer and the estimator is a classifier, scikit-learn uses stratified k-fold without shuffling. Passing a splitter object, as above, makes the folds explicit and reproducible.
The comment in the code flags a problem. best_score_ is the maximum of nine means, all computed on the same five validation splits that did the choosing. The next chapter quantifies that effect. For now, treat best_score_ as a ranking tool, not as a performance report.
Counting the fits
The number of model fits is candidates × folds, plus one for the refit.
| Quantity | Value in the example |
|---|---|
| Candidates | 3 × 3 = 9 |
| Folds | 5 |
| Fits during the search | 9 × 5 = 45 |
| Refit on all data | 1 |
| Total | 46 |
Keep this arithmetic in mind. Nested cross-validation multiplies it again by the number of outer folds.
Reading cv_results_
best_params_ hides how close the competition was. The cv_results_ dictionary holds one entry per candidate, and each value is an array aligned across candidates.
results = search.cv_results_
rows = zip(
results["rank_test_score"],
results["mean_test_score"],
results["std_test_score"],
results["params"],
)
for rank, mean, std, params in sorted(rows, key=lambda r: r[0]):
print(f"rank {rank}: {mean:.3f} +/- {std:.3f} {params}")Run this after the search above. The useful keys are:
mean_test_scoreandstd_test_score: the average and spread of the k validation scores. "Test" here means the validation part of each fold.split0_test_score,split1_test_score, and so on: the individual fold scores.rank_test_score: rank 1 is best. Tied candidates share a rank.mean_fit_timeandmean_score_time: cost per candidate, useful when deciding what to prune.params: the dictionary of values for each candidate.
Look at the standard deviation next to the gap between candidates. If the top three candidates differ by 0.002 and their standard deviation is 0.015, the ranking is mostly noise. The search still returns a single winner, but the data do not clearly prefer it. This observation returns when we discuss variance later in the tutorial.
The refit step
By default refit=True. After the search, scikit-learn fits a fresh copy of the best candidate on all the data passed to fit and stores it in best_estimator_. Calling search.predict(...) or search.score(...) delegates to that model.
print(search.best_estimator_)
print(search.predict(X[:5]))Two consequences follow.
- Scoring
searchonXandyafterfitevaluates on data the refit model has already seen. That number is a training score and says nothing about new data. - With several metrics in
scoring,refitmust name the metric used to choose the winner, for examplerefit="roc_auc". Otherwise scikit-learn cannot decide which score to optimize.
Choosing the metric
The search optimizes whatever scoring says. The default is the estimator's own score method, which is accuracy for classifiers and R² for regressors. Set it explicitly when accuracy is a poor fit for the problem.
search = GridSearchCV(pipe, param_grid, cv=cv, scoring="roc_auc")The metric you tune on should match the metric you will report. Tuning on accuracy and then reporting AUC mixes two objectives and makes the result harder to interpret.
Designing the grid
- Use log-spaced values for scale parameters.
Candgammaact multiplicatively, so[0.01, 0.1, 1, 10, 100]covers more useful ground than[1, 2, 3, 4, 5]. - Check the edges. If the best value sits at the border of the grid, the true optimum may lie outside it. Extend the grid in that direction and search again.
- Go coarse, then fine. A wide, sparse grid first, then a denser grid around the winner, costs less than one dense grid over the full range.
- Use a list of dictionaries for conditional parameters. Some parameters only make sense with certain others, such as
gammawith an RBF kernel but not a linear one.
param_grid = [
{"svc__kernel": ["linear"], "svc__C": [0.1, 1, 10]},
{"svc__kernel": ["rbf"], "svc__C": [0.1, 1, 10], "svc__gamma": [0.01, 0.001]},
]This grid has 3 + 6 = 9 candidates. A plain product would waste fits on gamma values the linear kernel ignores.
If the product grows too large, RandomizedSearchCV samples a fixed number of candidates from distributions instead. It has the same interface and the same selection bias, so everything in this tutorial applies to it as well.
Common errors
| Symptom | Likely cause |
|---|---|
| `ValueError: Invalid parameter ...` | The key lacks the step prefix, or the step name is wrong. Check `pipe.get_params().keys()`. |
| Best value always at a grid edge | The grid range is too narrow. |
| Search is far slower than expected | Candidates × folds is larger than you assumed. Count it first. |
| Scores are `nan` for some candidates | Those fits failed. By default `error_score=np.nan` records a warning and continues. Set `error_score="raise"` to see the exception. |
| Different winners on each run | Shuffled folds without a `random_state`, or a stochastic estimator without a seed. |
What the search gives you and what it does not
A grid search gives you a model chosen by a reasonable rule, a ranked table of candidates, and a mean score for each candidate. It does not give you an honest estimate of how the chosen model will perform on new data. The winner was selected because it scored highest on these folds, so part of its score comes from luck on those particular splits. The next chapter shows how large that effect can be and why it grows with the number of candidates.
Exercise
A grid has C in [0.1, 1, 10, 100], gamma in [0.1, 0.01, 0.001], and you use 5-fold cross-validation with refit=True. How many model fits does the search perform in total? Then name one reason the score from search.score(X, y) after search.fit(X, y) cannot be used as a performance estimate.
Show answer
There are 4 × 3 = 12 candidates, so 12 × 5 = 60 fits during the search, plus 1 refit on all the data, for 61 fits. The search.score(X, y) value is computed by the refit model on the same data it was trained on, so it measures training performance and not performance on unseen data.
Exercise
After a search, the top two candidates have mean validation scores of 0.962 and 0.960, with standard deviations of 0.018 across folds. What should you conclude about the ranking, and what is one practical response?
Show answer
The 0.002 gap is much smaller than the fold-to-fold spread, so the data do not clearly prefer the first candidate and the ranking is mostly noise. A practical response is to prefer the cheaper or simpler candidate, or to check whether the grid and metric are discriminating enough, rather than treating the winner as meaningfully better.