Sub topic 8
Nested cross-validation: inner loop selects, outer loop evaluates
This chapter assumes you know how k-fold cross-validation and GridSearchCV work, and that you have seen the previous chapter's point: the best score from a search is optimistic. Here we build the fix. The scikit-learn details and result reporting come in the next chapters.
The problem nested cross-validation solves
A hyperparameter search tries several candidate configurations and keeps the one with the highest cross-validation score. That score is a maximum over noisy numbers. Each candidate's score has some random error, because the folds are a finite sample. Taking the maximum favors candidates whose error happened to be positive. The reported best_score_ therefore overstates how the chosen configuration will do on new data.
The same folds also did two jobs. They ranked the candidates, and they produced the number you report. A fair estimate needs data that played no part in the choice.
Nested cross-validation fixes this with one rule: the data used to evaluate a model must never be used to choose that model's hyperparameters.
The structure: two loops
Nested cross-validation has two cross-validation loops, one inside the other.
- The outer loop splits the data into outer training and outer test parts. It exists only to estimate performance.
- The inner loop runs on each outer training part. It splits that part again and runs the hyperparameter search. It exists only to select a configuration.
For each outer fold, the procedure is:
- Hold out the outer test fold. Do not look at it.
- Run the full hyperparameter search on the outer training data, using inner cross-validation.
- Take the winning configuration and refit it on the whole outer training data.
- Score that refitted model once on the outer test fold.
After all outer folds, you have one outer score per fold. Their mean is the nested cross-validation estimate.
The key point is the arrow that is missing. Nothing flows from the outer test fold into the inner loop. The search never sees it, so its choice cannot be tuned to it.
What the outer score estimates
The outer score does not evaluate one particular model. Each outer fold may choose different hyperparameters. The nested estimate therefore measures the whole procedure: "split the data, search a grid with this inner cross-validation, refit the winner." It answers the question: if I apply this tuning procedure to a dataset of this size, how well will the resulting model perform on new data?
That is the right question for model selection. You can compare two procedures, such as an SVM tuned over one grid and a random forest tuned over another, by comparing their nested scores. Both are then judged under the same honest rule.
It also means the estimate does not belong to a specific set of hyperparameters. This matters when you build the final model, which a later chapter covers.
Seeing the bias on data with no signal
The clearest demonstration uses labels that carry no information. Any honest estimate of accuracy should be near 0.5. The plain search will usually report something higher, because it picks the luckiest candidate out of 30.
import numpy as np
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 10))
y = rng.integers(0, 2, size=60) # random labels: no real signal
param_grid = {
"n_neighbors": list(range(1, 30, 2)),
"weights": ["uniform", "distance"],
}
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(KNeighborsClassifier(), param_grid, cv=inner_cv)
# Plain search: the score is the maximum over 30 candidates on the same folds.
search.fit(X, y)
print(f"best_score_ (plain search): {search.best_score_:.3f}")
# Nested: the outer folds never take part in choosing hyperparameters.
nested = cross_val_score(search, X, y, cv=outer_cv)
print(f"nested CV accuracy: {nested.mean():.3f}")Exact values depend on the seeds and on scikit-learn's version. The pattern to expect is that the plain score sits clearly above 0.5, while the nested mean stays near 0.5 and may even fall slightly below it. With only 60 samples, each number is noisy. The gap between the two is the optimism that nesting removes.
Why the inner and outer loops must be separate
Several shortcuts look similar to nesting but do not give honest estimates.
| Approach | What goes wrong |
|---|---|
| Report `best_score_` from the search | The same folds rank candidates and produce the score, so the score is a maximum over noisy values. |
| Search on all the data, then run `cross_val_score` with the winning hyperparameters | The hyperparameters were chosen using every sample, including the ones in each test fold. The choice has already seen the test data. |
| Use the same splits for the inner and outer loops | If the splits coincide, the outer test fold can leak into the inner search. Use separate splitter objects. |
| Tune on the outer test fold "just a little" | The fold is now part of selection and no longer an unbiased test. |
The second shortcut is the most common and the most deceptive. Because the final cross_val_score call looks like clean cross-validation, it is easy to forget that the hyperparameters came from a search on the full dataset.
How much bias are we talking about?
Nested cross-validation is not needed in every project. The size of the optimistic bias grows with:
- the number of candidates compared (a bigger grid gives a larger maximum),
- the noise in each candidate's score (smaller datasets give noisier scores),
- how similar the candidates are (many near-identical candidates add little extra bias, while very different candidates add more).
With a large dataset and a small grid, the bias is often small compared with the other uncertainty. With a few hundred samples and a large grid, it can be several percentage points. On a small dataset, nested cross-validation is the more important to use.
Counting the work
Nesting multiplies the work. With K outer folds, k inner folds, and G candidate configurations, one nested run fits roughly
K × (G × k + 1)
models. The "+ 1" is the refit of the winner on each outer training set. In the example above, that is 5 × (30 × 5 + 1) = 755 fits, compared with 150 for the plain search plus one refit. The next chapters return to ways to reduce this cost.
Common errors
- Reusing one splitter for both loops. Create separate
StratifiedKFoldobjects with differentrandom_statevalues. The fold assignments then differ, so the two loops do not mirror each other. - Preprocessing outside the pipeline. If you scale or select features on the full dataset before the loops, information from the outer test folds leaks into training. Put preprocessing inside a
Pipelineso it is refit on each training part. - Reading the outer scores as the performance of one model. They are scores of different models, possibly with different hyperparameters.
- Choosing hyperparameters by looking at the outer scores. If you tune the grid after seeing nested results, the outer folds have become part of selection and you need a fresh layer of evaluation.
Check your understanding
Exercise
A colleague runs GridSearchCV on the full dataset, takes bestparams, and then calls crossvalscore with a fresh model using those parameters. They report the mean as an unbiased estimate. Why is it still optimistic, and what change makes it honest?
Show answer
The hyperparameters were chosen by a search that saw every sample, including the samples that later serve as test folds in crossvalscore. The selection has therefore already used the test data. To make the estimate honest, put the search inside the evaluation: pass the GridSearchCV object itself to crossvalscore, so each outer training set runs its own search and the outer test fold is never seen during selection.
Exercise
You use 5 outer folds, 3 inner folds, and a grid of 12 candidates, with the winner refitted on each outer training set. About how many models are fitted in total?
Show answer
K × (G × k + 1) = 5 × (12 × 3 + 1) = 5 × 37 = 185 fits.
Exercise
On data with random labels, the plain search reports 0.65 accuracy and the nested estimate is 0.51. Which number is closer to the truth, and what causes the gap?
Show answer
The nested estimate of 0.51 is closer, since random labels cannot be predicted better than chance (about 0.5). The plain search reports the maximum over many candidates on the same folds that picked it, so noise that happened to favor one candidate is counted as skill. That selection bias is the gap.