Sub topic 6
Why the best cross-validation score is too optimistic
This chapter assumes you can run GridSearchCV and cross_val_score, and that you know what a cross-validation fold is. It explains why the number in best_score_ overstates how well the chosen model will do on new data. The next chapters build on that to introduce nested cross-validation.
What `best_score_` actually is
Grid search fits every candidate on each fold and averages the validation scores. It then keeps the candidate with the highest average. The best_score_ attribute is that highest average.
That makes it two things at once:
- The score used to choose the winner.
- The number many people then report as the winner's expected performance.
Using one number for both jobs is the problem. Here is the setup from the earlier chapter on tuning.
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 printed score comes from the same folds that picked best_params_. Those folds have already influenced the model, so they are no longer an independent test.
The mechanism: a maximum of noisy numbers
Each candidate's cross-validation score is an estimate. It has a true value, which is the performance you would get on unlimited fresh data. It also has noise, because the data you have is a finite sample and the folds are one particular split of it.
Write the cross-validation score of candidate i as the true quality plus noise:
score_i = true_i + noise_i
The noise has mean zero for any single, fixed candidate. If you picked one candidate in advance, its cross-validation score would be an unbiased estimate of its quality.
Grid search does not pick in advance. It picks the candidate with the largest score_i. A large score_i happens when true_i is high, when noise_i is lucky, or both. Selection favors the lucky draws, so the winner's noise is positive on average. In symbols, the expected value of the maximum is at least the maximum of the expected values:
E[max(score_1, ..., score_m)] >= max(true_1, ..., true_m)
The gap is the selection bias. It is a property of taking a maximum over noisy estimates. Nothing is wrong with the cross-validation splitter, and the model is not necessarily overfit in the usual sense.
A demonstration where the true answer is known
You can see the effect cleanly when no model can possibly work. In the script below, the labels are random coin flips, independent of the features. Every classifier has a true accuracy of 0.5. We tune n_neighbors, then score the tuned model on 5000 fresh rows from the same random process.
import numpy as np
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.neighbors import KNeighborsClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 20))
y = rng.integers(0, 2, size=100)
X_new = rng.normal(size=(5000, 20))
y_new = rng.integers(0, 2, size=5000)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
grid = {"n_neighbors": list(range(1, 40, 2))}
search = GridSearchCV(KNeighborsClassifier(), grid, cv=cv)
search.fit(X, y)
print("best_score_:", search.best_score_)
print("fresh-data accuracy:", search.score(X_new, y_new))Run it and compare the two numbers. best_score_ should sit clearly above 0.5, because the maximum over 20 noisy scores is rarely close to the average. The fresh-data accuracy should land near 0.5, which is the truth. The exact values depend on your library versions. The direction of the gap does not.
This is a deliberately extreme case. On real data the candidates differ in true quality, so the bias is smaller relative to the signal. It does not vanish, though.
What controls the size of the bias
Several quantities decide how large the gap is.
| Factor | Effect on the bias | Why |
|---|---|---|
| Number of candidates | More candidates, more bias | The maximum of more draws is larger on average. |
| Dataset size | Smaller data, more bias | Fewer rows mean noisier fold scores. |
| Correlation between candidates | Highly correlated candidates, less bias | Neighboring settings share most of their noise, so there are fewer independent draws. |
| Spread of true quality | Large real differences, less bias | If one candidate is clearly best, noise rarely changes the winner. |
| Metric noise | Noisy metrics, more bias | Metrics such as F1 on a rare class, or AUC on few positives, vary more between folds. |
Two consequences follow in practice. A wide random search over many hyperparameters, with a small dataset, is the worst case. A three-value grid on 100,000 rows is usually close to harmless.
Common misreadings
The bias claim is narrow, so it is easy to over-read. These points come up often.
- The winner is not necessarily a bad choice. Selection still tends to find a good candidate. Only the reported score is inflated.
- Averaging over folds does not remove it. The mean over folds reduces noise in each candidate's score. It does not stop the maximum from preferring positive noise.
- More folds do not fix it. Going from 5 to 10 folds changes the variance of each score a little. The same data still serves as both selector and judge.
- A different
random_statedoes not fix it. Reshuffling the folds gives different noise, but you would again keep the maximum. - It is not the same as data leakage. Leakage means information from validation rows reaches the fitted model through preprocessing. Selection bias remains even with a perfect
Pipeline. The two problems stack, and a later chapter covers leakage separately.
The same error with a holdout set
The bias is not specific to cross-validation. Suppose you have a single test set and check it after every tuning round, keeping whatever scored best. That test set has now been used to select, and its score is optimistic for the same reason: you are taking a maximum over noisy evaluations.
Cross-validation does not escape this just by being repeated. The data used for scoring candidates and the data used for reporting the final number must be kept apart. A plain holdout split does this only if the holdout is touched once. Cross-validation as used inside a grid search never keeps that separation, since every row is used for validation in some fold.
What an honest estimate needs
To get an unbiased number for the procedure "tune with grid search, then predict," the evaluation rows must play no part in choosing hyperparameters. This implies:
- Hold some data out of the selection step entirely.
- Run the complete selection procedure, including the search, on the remaining data.
- Score the selected model on the held-out data.
- Repeat with different held-out portions so that every row contributes and the estimate is stable.
Step 4 is what turns a single holdout into an outer cross-validation loop, with the grid search running inside each outer training set. That structure is nested cross-validation, the subject of the following chapters. The estimate it produces describes the whole tuning procedure rather than one fixed set of hyperparameters.
Checking your own results
You can often spot a likely optimistic score without running anything new.
- Count the candidates. A grid of 3 × 3 is 9 candidates. A random search with 500 iterations is 500.
- Compare
best_score_with the scores of the other candidates insearch.cv_results_["mean_test_score"]. If many candidates are within the fold-to-fold standard deviation (std_test_score) of the best, the ranking is mostly noise and the winner's lead is probably luck. - Note how much data you have per fold. A few dozen validation rows per fold means scores that swing by several points.
Exercise
A colleague tunes a model on a 200-row dataset with a random search of 300 candidates and reports bestscore as the expected accuracy. They propose switching from 5 to 20 folds to make the score "more reliable." Does this fix the optimism? Explain.
Show answer
No. More folds reduce the noise in each candidate's mean score only slightly, and the real problem is that the same folds both rank the 300 candidates and score the winner. Taking the maximum over 300 noisy scores on 200 rows keeps favoring candidates with positive luck, so bestscore stays biased upward. They need an evaluation that keeps outer test data out of the search, such as nested cross-validation.
Exercise
In the random-label demonstration, why is the fresh-data accuracy close to 0.5 while bestscore is higher, even though every candidate has a true accuracy of exactly 0.5?
Show answer
Each candidate's fold score is 0.5 plus noise, so some candidates score above 0.5 by chance. GridSearchCV keeps the maximum, and the maximum of 20 noisy scores is above 0.5 on average. The fresh data was not used to choose a candidate, so its noise averages to zero and the accuracy sits near the true value of 0.5.