Sub topic 2
Why the Best Cross-Validation Score Is Too Optimistic
This chapter assumes you know supervised learning, overfitting, NumPy, and scikit-learn’s fit and score methods.
Why the Best Cross-Validation Score Is Too Optimistic
A hyperparameter is a setting chosen before training, such as an SVM’s C or gamma. A hyperparameter search evaluates many candidates with cross-validation and selects the candidate with the highest score.
That highest score is usually optimistic. Every candidate receives some random advantage from the particular folds. Selecting the maximum also selects candidates that benefited from that advantage. Therefore, best_score_ estimates performance on the search folds, not reliably on new data.
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)
model = make_pipeline(StandardScaler(), SVC())
search = GridSearchCV(
model,
{"svc__C": [0.1, 1, 10], "svc__gamma": ["scale", 0.01]},
cv=cv,
)
search.fit(X, y)
print(search.best_score_) # selection score, often optimisticKeeping Preprocessing Inside the Folds
Preprocessing learns values from data. For example, StandardScaler learns each feature’s mean and standard deviation. If it is fitted before cross-validation, information from validation rows influences training.
A Pipeline fits the scaler separately inside each training fold, then applies those fitted values to that fold’s validation data.
Nested Cross-Validation: Inner Loop Selects, Outer Loop Evaluates
Nested cross-validation uses two independent loops:
- The inner loop selects hyperparameters using only the outer training portion.
- The outer loop evaluates that selected pipeline on untouched data.
flowchart TD
A[All data] --> B[Outer training fold]
A --> C[Outer test fold]
B --> D[Inner cross-validation selects hyperparameters]
D --> E[Fit selected pipeline on outer training fold]
E --> Cfrom sklearn.model_selection import cross_val_score
inner = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(model, {
"svc__C": [0.1, 1, 10],
"svc__gamma": ["scale", 0.01],
}, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(scores.mean(), scores.std())The mean outer score estimates the performance of the whole tuning procedure on new data.
Choosing Splitters That Match Your Data
| Data pattern | Splitter |
|---|---|
| Classification with class imbalance | `StratifiedKFold` |
| Multiple rows per person or device | `GroupKFold` |
| Time-ordered observations | `TimeSeriesSplit` |
Never put related rows in both training and test folds. For time data, do not train on future observations to predict the past.
Exercise
Why does nested cross-validation need an outer loop?
Show answer
It evaluates hyperparameters on data that the inner search never used for selection.