Sub topic 9
Choosing splitters that match your data
This chapter assumes you know K-fold cross-validation, GridSearchCV, and Pipeline in scikit-learn. Nested cross-validation only gives an honest estimate if both the inner and outer loops split the data in a way that matches how the model will be used. A splitter that ignores the structure of your data leaks information between training and test folds, and the score is optimistic again.
Why the splitter matters
A cross-validation score estimates performance on new data. That estimate is only valid if each test fold resembles "new" data relative to its training fold. Three common structures break this:
- Imbalanced classes, where a random fold can have too few rare cases.
- Groups of related rows, such as several samples from one patient.
- Time order, where the future must not be used to predict the past.
Stratified splits for classification
StratifiedKFold keeps the class proportions in every fold. When you pass an integer such as cv=5 with a classifier, scikit-learn already uses it. Set it explicitly so you can control shuffling and the random seed.
Grouped splits for related rows
If rows from the same group appear in both training and test folds, the model can memorize group-specific traits. Use GroupKFold or StratifiedGroupKFold, and pass the group labels when you split.
Time-ordered splits
For time series, use TimeSeriesSplit. Each test fold comes after its training fold, so the model never sees the future.
| Data situation | Splitter | Key point |
|---|---|---|
| Independent rows, classification | `StratifiedKFold` | Keeps class ratios |
| Independent rows, regression | `KFold` | Use `shuffle=True` if rows are ordered |
| Repeated measures per subject | `GroupKFold` | Pass `groups` |
| Groups and imbalanced classes | `StratifiedGroupKFold` | Pass `groups` |
| Ordered in time | `TimeSeriesSplit` | No shuffling |
Using the splitters in both loops
Use the same kind of splitter in the inner and outer loops. If the outer loop is grouped but the inner loop is not, the inner search can still leak group information. That makes it choose hyperparameters that favor memorization.
Pass groups through params in cross_val_score. In scikit-learn 1.4 and later this argument is named params, and the older name fit_params is deprecated. Recent versions route the groups to the inner search as well, but only when metadata routing is enabled, as the example does. This example assumes scikit-learn 1.6 or later.
import numpy as np
import sklearn
from sklearn.datasets import make_classification
from sklearn.model_selection import (
GridSearchCV,
StratifiedGroupKFold,
cross_val_score,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
sklearn.set_config(enable_metadata_routing=True)
X, y = make_classification(n_samples=300, random_state=0)
groups = np.repeat(np.arange(60), 5) # 60 groups of 5 rows each
inner_cv = StratifiedGroupKFold(n_splits=3)
outer_cv = StratifiedGroupKFold(n_splits=5)
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10]}
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
search.set_fit_request(groups=True)
scores = cross_val_score(
search, X, y, groups=groups, cv=outer_cv, params={"groups": groups}
)
print(scores.round(3), scores.mean().round(3))Exercise
Your dataset has 10 blood samples per patient and you plan to deploy the model on new patients. Which splitter should you use in the outer loop, and which in the inner loop?
Show answer
Use a grouped splitter in both loops, such as GroupKFold, or StratifiedGroupKFold if the classes are imbalanced, with patient ID as the group. The outer loop then tests on unseen patients. The inner loop also keeps each patient's samples together, so hyperparameter selection does not reward memorizing individual patients.