Sub topic 9
Choosing splitters that match your data
Nested cross-validation has two loops, and each loop needs a splitter that reflects how your data was collected. A splitter that ignores the structure of the data gives leaky folds, and leaky folds make the outer score optimistic, which is the problem nesting is meant to remove. This chapter covers how to pick splitters for the inner and outer loops.
This chapter assumes you know K-fold cross-validation, GridSearchCV, and how cross_val_score wraps an estimator. You should also know why preprocessing belongs inside a Pipeline.
Why the splitter is part of the method
A cross-validation estimate is only honest if each test fold looks to the model like genuinely new data. "New" depends on how the model will be used.
- If you will predict for new patients, the test fold must contain patients the model has never seen.
- If you will forecast the future, the test fold must come after the training data in time.
- If one class is rare, every fold must still contain it.
The splitter encodes these rules. The default behaviour of cv=5 encodes only one of them, and only for classifiers.
Stratified splitting for classification
StratifiedKFold keeps the class proportions of the full dataset in every fold. With a 5% positive class, plain KFold can produce a test fold with very few positives or none. The score on that fold is then very noisy or undefined.
Passing an integer such as cv=5 to GridSearchCV or cross_val_score uses StratifiedKFold automatically when the estimator is a classifier and y is binary or multiclass. Two details still matter:
- The integer shortcut does not shuffle. If your rows are sorted by class or by collection date, the folds will be contiguous blocks. Build the splitter yourself with
shuffle=Trueand a fixedrandom_state. - Each class needs at least
n_splitssamples. Otherwise scikit-learn warns, and some folds lack that class entirely. Remember that the inner loop splits only the outer training set, which is smaller than the full data. A class with 12 samples may pass a 5-fold outer split and still be thin in the inner one.
Grouped splitting for repeated measurements
Some rows are not independent. Several scans per patient, several photos per object, or several sessions per user all create groups of related rows. If rows from one group land on both sides of a split, the model can recognise the group instead of learning the general pattern. The score then reflects memorisation.
GroupKFold guarantees that no group appears in both the training and test part of a split. StratifiedGroupKFold does the same while keeping class proportions as close as it can. Both take a groups array that has one entry per row.
In nested cross-validation the group rule must hold at both levels:
- The outer split must separate groups, so the outer test fold contains only unseen groups.
- The inner split, run inside each outer training set, must also separate groups. Otherwise the inner search picks hyperparameters that favour memorisation, such as a very flexible model, and the outer loop gets a worse model than it should.
Time-ordered splitting for forecasting
When rows have a time order and you will predict later values from earlier ones, shuffling lets the model train on the future. TimeSeriesSplit makes each training set an earlier stretch of rows and each test set the stretch right after it. It assumes your rows are already sorted by time.
Two options matter:
gapleaves out a number of rows between the training and test parts. Use it when the target at timetdepends on information that overlaps the next few rows, such as a 5-day average or a label that is only known after a delay.max_train_sizecaps the training window, which suits data whose behaviour drifts.
Never set shuffle=True on ordered data you plan to forecast.
Summary of splitters
| Situation | Splitter | Notes |
|---|---|---|
| Independent rows, balanced classes or regression | `KFold` with `shuffle=True` | Set `random_state`. |
| Independent rows, classification | `StratifiedKFold` | Each class needs at least `n_splits` samples. |
| Rows grouped by patient, user, or object | `GroupKFold` | Needs a `groups` array. |
| Grouped rows and imbalanced classes | `StratifiedGroupKFold` | Class balance is approximate. |
| Time-ordered rows | `TimeSeriesSplit` | Sort by time first. Consider `gap`. |
Grouped nested cross-validation in code
The simplest correct way to pass groups through both loops is to write the outer loop by hand, as in the manual loop earlier in this tutorial. You slice groups the same way you slice X and y, so the inner search receives only the groups in its own training set.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedGroupKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=600, n_features=20, n_informative=5,
weights=[0.8, 0.2], random_state=0,
)
# 100 patients with 6 rows each.
groups = np.repeat(np.arange(100), 6)
inner_cv = StratifiedGroupKFold(n_splits=4, shuffle=True, random_state=1)
outer_cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=2)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
param_grid = {"logisticregression__C": [0.01, 0.1, 1, 10]}
search = GridSearchCV(
pipe, param_grid, cv=inner_cv, scoring="balanced_accuracy"
)
scores = []
for fold, (train_idx, test_idx) in enumerate(
outer_cv.split(X, y, groups)
):
# No patient may appear on both sides of the outer split.
assert set(groups[train_idx]).isdisjoint(groups[test_idx])
fold_search = clone(search)
fold_search.fit(X[train_idx], y[train_idx], groups=groups[train_idx])
score = fold_search.score(X[test_idx], y[test_idx])
scores.append(score)
print(fold, fold_search.best_params_, round(score, 3))
print(f"nested balanced accuracy: {np.mean(scores):.3f} +/- {np.std(scores):.3f}")The groups argument to fold_search.fit is handed to the inner splitter. GridSearchCV uses it only for splitting. The pipeline never sees it.
Time-ordered nested cross-validation
For time series, no groups are needed, and cross_val_score works directly. The inner TimeSeriesSplit runs inside each outer training set. That training set is already an earlier stretch of time, so the inner folds stay in the past relative to the outer test fold.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import (
GridSearchCV, TimeSeriesSplit, cross_val_score,
)
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 5))
y = X @ np.array([1.0, 0.5, 0.0, 0.0, -1.0]) + rng.normal(scale=0.5, size=500)
# Rows are assumed to be sorted by time, oldest first.
inner_cv = TimeSeriesSplit(n_splits=4, gap=5)
outer_cv = TimeSeriesSplit(n_splits=5, gap=5)
search = GridSearchCV(
Ridge(),
{"alpha": [0.01, 0.1, 1, 10]},
cv=inner_cv,
scoring="neg_mean_squared_error",
)
scores = cross_val_score(
search, X, y, cv=outer_cv, scoring="neg_mean_squared_error"
)
print("outer MSE per fold:", -scores)
print(f"mean outer MSE: {-scores.mean():.3f}")Two consequences of time-ordered splitting are worth knowing:
- The first outer fold trains on a small early slice, and the inner loop then splits that slice again. Its hyperparameters are chosen from little data, so early folds are often worse and noisier than later ones.
- Every test fold is a different period. Differences between folds can reflect drift in the data and not just sampling noise, so look at the scores in time order before you average them.
Common errors
- Using a grouped outer split and a plain inner split. The outer score stays honest about new groups, but the inner search selects on leaky folds and can pick an overfit configuration.
- Shuffling ordered data.
KFold(shuffle=True)on a time series mixes future rows into training. Scores look excellent and fail in production. - Too few groups.
GroupKFold(n_splits=5)needs at least five groups in each training set it splits. After the outer split removes one fold, the inner loop has fewer groups than the full data had. - Mismatched strictness between loops. Use the same kind of splitter in both loops. The sizes can differ, but the structure of the data should be respected equally.
- Assuming stratification fixes dependence. Stratifying keeps class ratios. It does nothing to stop related rows from straddling a split.
Exercise
A dataset has 40 patients with 10 rows each, and the label is rare (about 8% positive). You want nested cross-validation to estimate performance on new patients. Which splitter would you use in the outer and inner loops, and how does the patient identifier reach each loop in a hand-written outer loop?
Show answer
Use StratifiedGroupKFold in both loops, because rows share patients and the classes are imbalanced. Build the outer folds with outercv.split(X, y, groups), so no patient appears in both outer training and test rows. Then call foldsearch.fit(X[trainidx], y[trainidx], groups=groups[trainidx]), so the inner GridSearchCV splits only the patients in that outer training set and also keeps each patient on one side of every inner split. With only 40 patients and a rare label, keep nsplits small, since each inner training set has fewer patients than the full data.