Sub topic 3
Nested Cross-Validation with scikit-learn
Assume you know supervised learning, overfitting, NumPy, and scikit-learn estimators. Nested cross-validation separates model selection from performance estimation.
Implementing the two loops
The inner loop chooses hyperparameters. The outer loop evaluates that entire choice process on data it never saw during tuning.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import (
GridSearchCV, StratifiedKFold, cross_val_score
)
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)
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
model = make_pipeline(StandardScaler(), SVC())
grid = {"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01, 0.001]}
search = GridSearchCV(model, grid, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(scores)
print(f"{scores.mean():.3f} +/- {scores.std():.3f}")GridSearchCV runs inside each outer training set. The outer test fold is used only for the final score. The pipeline also fits StandardScaler separately inside each fold, preventing preprocessing leakage.
Reading scores and chosen hyperparameters
The mean of scores estimates the performance of the tuning procedure on unseen data. Its standard deviation shows variation across outer folds. To inspect the selected parameters, repeat the outer loop manually with clone(search) and record each fold's best_params_. Different choices across folds indicate that the data does not strongly identify one setting.
Fitting the final model
After estimating performance, rerun the search once on all available data:
final_search = GridSearchCV(model, grid, cv=inner)
final_search.fit(X, y)
final_model = final_search.best_estimator_The nested score estimates future performance. The final model uses all data but has no independent score unless evaluated on new data.
Cost, noise, and alternatives
With five outer folds, five inner folds, and nine candidates, the search performs about 225 candidate fits, plus refits. Reduce cost with fewer candidates, randomized search, successive halving, or parallel jobs such as n_jobs=-1.
Nested estimates can be noisy. Repeated nested cross-validation averages results across new fold assignments but multiplies the cost. Use it when the dataset is small and the decision matters.
Nested cross-validation is unnecessary when hyperparameters were fixed in advance or when a large untouched test set is reserved. It also does not fix biased labels, distribution shift, or an unsuitable metric.
Exercise
What does the nested score estimate?
Show answer
It estimates the generalization performance of the complete hyperparameter-selection procedure, not merely the best candidate's cross-validation score.