Which CV strategy
Cross-validation estimates how a model will score on data it has not seen. That estimate is honest only if each validation fold looks like the future data relative to its training folds. If the model will meet new customers, new stores or next month, the folds must hold out whole customers, whole stores or later dates. This guide maps the shape of the data to a scikit-learn splitter and lists the leaks that inflate scores.
flowchart TD
A{"Ordered in time,<br/>predict the future?"} -->|yes| T["TimeSeriesSplit<br/>test_size = horizon, gap"]
A -->|no| B{"Several rows per customer,<br/>store or patient?"}
B -->|yes| B1{"Rare class?"}
B1 -->|yes| SG["StratifiedGroupKFold"]
B1 -->|no| G{"Fewer than<br/>about 20 groups?"}
G -->|yes| LOGO["LeaveOneGroupOut"]
G -->|no| GK["GroupKFold"]
B -->|no| C{"Classification?"}
C -->|yes| S["StratifiedKFold"]
C -->|no| K["KFold, shuffle=True"]
S --> N{"Under about<br/>1,000 rows?"}
K --> N
N -->|yes| R["RepeatedStratifiedKFold /<br/>RepeatedKFold"]
N -->|no| F["5 folds"]
If you also tune hyperparameters, the tuning needs its own inner splitter: nested cross-validation (see below).
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| one hold-out test set | train_test_split(X, y, test_size=0.2, random_state=42) |
add stratify=y for classification |
| a hold-out set for time data | X.iloc[:-n], X.iloc[-n:] on rows sorted by time |
never shuffle |
| a hold-out set by group | GroupShuffleSplit(n_splits=1, test_size=0.2) |
next(gss.split(X, y, groups)) |
| k folds of independent rows (regression) | KFold(n_splits=5, shuffle=True, random_state=42) |
|
| keep class shares in every fold | StratifiedKFold(n_splits=5, shuffle=True, random_state=42) |
the default for classifiers with cv=5 (no shuffle) |
| keep all rows of a customer together | GroupKFold(n_splits=5) |
pass groups= |
| groups and a rare class | StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42) |
|
| one fold per store, site or hospital | LeaveOneGroupOut() |
for few, large groups |
| train on the past, test on the future | TimeSeriesSplit(n_splits=5, test_size=h) |
rows sorted by time |
| a delay between data and prediction | TimeSeriesSplit(..., gap=g) |
skips g rows between train and test |
| a sliding training window | TimeSeriesSplit(..., max_train_size=w) |
when old data is stale |
| a steadier estimate on small data | RepeatedStratifiedKFold(n_splits=5, n_repeats=10) |
50 fits |
| leave one row out | LeaveOneOut() |
very small data only; high variance |
| custom folds (a fixed validation period) | PredefinedSplit(test_fold) |
−1 = always in training |
| scores for any splitter | cross_val_score(model, X, y, cv=splitter, groups=g) |
|
| several metrics and fit times | cross_validate(model, X, y, cv=..., scoring=[...]) |
return_train_score=True for overfitting |
| out-of-fold predictions | cross_val_predict(model, X, y, cv=...) |
for plots and stacking, not for a score |
| tune without leaking into the estimate | cross_val_score(GridSearchCV(model, grid, cv=inner), X, y, cv=outer) |
nested CV |
| groups inside a search | search.fit(X, y, groups=g) with a group splitter as cv |
|
| groups at both levels of nested CV | sklearn.set_config(enable_metadata_routing=True), then cross_val_score(search, X, y, cv=GroupKFold(5), params={"groups": g}) |
see below |
| preprocessing inside each fold | make_pipeline(preprocess, model) |
the whole pipeline goes into CV |
| resampling inside each fold | imblearn.pipeline.make_pipeline(SMOTE(), model) |
never resample before the split |
| a threshold chosen without the test set | TunedThresholdClassifierCV(model, cv=...) |
|
| see the folds | for tr, te in splitter.split(X, y, groups): ... |
check sizes, dates, groups |
Data shape → splitter
Section titled “Data shape → splitter”| Data shape | Splitter | Why | Leakage risk if you use plain KFold |
|---|---|---|---|
| independent rows, regression | KFold(5, shuffle=True) |
rows are exchangeable | low; shuffle in case the file is sorted |
| independent rows, classification | StratifiedKFold(5, shuffle=True) |
every fold has the class shares of the data | folds without positives on small or rare data |
| imbalanced classes (1–10% positive) | StratifiedKFold, plus AP or recall as the metric |
stable positive counts per fold | a fold with 0 positives gives undefined scores |
| several rows per entity, new entities later | GroupKFold |
the model must generalize to unseen entities | memorizes entities; scores far too high |
| groups and a rare class | StratifiedGroupKFold |
both at once, as far as possible | as above |
| few large groups (12 stores, 5 hospitals) | LeaveOneGroupOut |
“does it work at a new site?” | site effects leak |
| time series, forecasting | TimeSeriesSplit(test_size=h, gap=g) |
the past predicts the future | the model interpolates between future and past days |
| events with a delay (labels known 30 days later) | TimeSeriesSplit(gap=30) |
the gap mimics the delay | the latest training labels would not exist yet |
| panel data: many series over time | split by date, and by series when new series appear | both kinds of leakage | trends and series identity leak |
| small data (under about 1,000 rows) | RepeatedStratifiedKFold / RepeatedKFold |
averages out the luck of one split | high variance, not leakage |
| tuning and reporting together | nested CV: inner search, outer evaluation | best_score_ is biased upward |
an optimistic final score |
| duplicated or near-duplicate rows | deduplicate, or group by the duplicate key | copies land on both sides of a split | memorized copies inflate the score |
Worked scenarios
Section titled “Worked scenarios”import numpy as npimport pandas as pdfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.feature_selection import SelectKBest, f_classiffrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import ( GroupKFold, KFold, StratifiedKFold, TimeSeriesSplit, cross_val_score,)from sklearn.neighbors import KNeighborsClassifierfrom sklearn.pipeline import make_pipeline“100 rows, 10 positives”: stratify
Section titled ““100 rows, 10 positives”: stratify”y_small = np.r_[np.ones(10, dtype=int), np.zeros(90, dtype=int)] # sorted fileX_small = np.zeros((100, 1))splitters = { "KFold": KFold(5), "KFold shuffled": KFold(5, shuffle=True, random_state=0), "StratifiedKFold": StratifiedKFold(5, shuffle=True, random_state=0),}for name, splitter in splitters.items(): positives = [int(y_small[te].sum()) for _, te in splitter.split(X_small, y_small)] print(f"{name:<16} positives per fold {positives}")KFold positives per fold [10, 0, 0, 0, 0]KFold shuffled positives per fold [3, 2, 4, 0, 1]StratifiedKFold positives per fold [2, 2, 2, 2, 2]Unshuffled KFold on a sorted file puts every positive in one fold. Shuffling helps but leaves a fold with none. StratifiedKFold gives each fold 2.
“Many rows per customer”: group the folds
Section titled ““Many rows per customer”: group the folds”Here each customer has 8 rows with similar features and one label. The label is random per customer, so no model can predict it for a new customer: the honest score is 50%.
rng = np.random.default_rng(42)n_customers, rows_each = 100, 8customer = np.repeat(np.arange(n_customers), rows_each)centers = rng.normal(size=(n_customers, 4))X_grp = centers[customer] + rng.normal(scale=0.3, size=(len(customer), 4))y_grp = rng.integers(0, 2, n_customers)[customer] # one random label per customerknn = KNeighborsClassifier(n_neighbors=5)kf = cross_val_score(knn, X_grp, y_grp, cv=KFold(5, shuffle=True, random_state=42))gkf = cross_val_score(knn, X_grp, y_grp, groups=customer, cv=GroupKFold(5, shuffle=True, random_state=42))print(f"KFold {kf.mean():.2f} GroupKFold {gkf.mean():.2f}")KFold 0.80 GroupKFold 0.50KFold puts rows of the same customer in training and validation, so the model recognizes customers instead of learning a pattern. GroupKFold gives the true answer.
“Forecast daily visits”: split by time
Section titled ““Forecast daily visits”: split by time”A random forest on a time index, the weekday and the month. Random folds let it interpolate between neighboring days; time-ordered folds make it forecast:
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])traffic["visits"] = traffic["visits"].interpolate() # 5 tracking outagesX_ts = pd.DataFrame({ "t": np.arange(len(traffic)), "dow": traffic["date"].dt.day_of_week, "month": traffic["date"].dt.month,})forest = RandomForestRegressor(n_estimators=100, random_state=42)for name, cv in { "KFold shuffled": KFold(5, shuffle=True, random_state=42), "TimeSeriesSplit": TimeSeriesSplit(n_splits=5, test_size=90),}.items(): mae = -cross_val_score(forest, X_ts, traffic["visits"], cv=cv, scoring="neg_mean_absolute_error").mean() print(f"{name:<16} MAE {mae:,.0f} visits")KFold shuffled MAE 319 visitsTimeSeriesSplit MAE 771 visitsThe shuffled estimate is less than half the real forecasting error. Set test_size to the forecast horizon and gap to the delay before data arrives:
splitter = TimeSeriesSplit(n_splits=3, test_size=28, gap=7)for train_idx, test_idx in splitter.split(traffic): dates = traffic["date"] print(f"train to {dates[train_idx[-1]]:%Y-%m-%d} ({len(train_idx)} days), " f"test {dates[test_idx[0]]:%Y-%m-%d} to {dates[test_idx[-1]]:%Y-%m-%d}")train to 2024-10-01 (1005 days), test 2024-10-09 to 2024-11-05train to 2024-10-29 (1033 days), test 2024-11-06 to 2024-12-03train to 2024-11-26 (1061 days), test 2024-12-04 to 2024-12-31“Select features, then cross-validate”: the classic leak
Section titled ““Select features, then cross-validate”: the classic leak”Random features and random labels: the honest accuracy is 50%. Selecting the 20 “best” features on all rows before CV lets the selector see the validation labels:
X_rand = rng.normal(size=(200, 1000))y_rand = rng.permutation(np.repeat([0, 1], 100))folds = StratifiedKFold(5, shuffle=True, random_state=42)X_selected = SelectKBest(f_classif, k=20).fit_transform(X_rand, y_rand) # all rowsleaky = cross_val_score(LogisticRegression(), X_selected, y_rand, cv=folds)pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())honest = cross_val_score(pipe, X_rand, y_rand, cv=folds) # selects inside each foldprint(f"leaky {leaky.mean():.2f} honest {honest.mean():.2f}")leaky 0.75 honest 0.48Nested cross-validation
Section titled “Nested cross-validation”The inner splitter tunes; the outer splitter scores the whole “tune, then refit” procedure. Use the same kind of splitter at both levels (groups or time if the data need them; groups need one extra setting, shown after this example):
from sklearn.datasets import load_breast_cancerfrom sklearn.model_selection import GridSearchCVfrom sklearn.tree import DecisionTreeClassifier
X_bc, y_bc = load_breast_cancer(return_X_y=True)inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)search = GridSearchCV(DecisionTreeClassifier(random_state=42), {"max_depth": [2, 3, 4, 6]}, cv=inner)nested = cross_val_score(search, X_bc, y_bc, cv=outer)best = search.fit(X_bc, y_bc).best_score_ # the search on all rows: the shipped modelprint(f"nested {nested.mean():.3f} best_score_ {best:.3f}")nested 0.912 best_score_ 0.935Report the nested estimate. best_score_ is the maximum of several noisy scores, so it tends to be optimistic.
With groups, both levels need them. cross_val_score(..., groups=g) passes the groups to the outer splitter only, so every inner GroupKFold gets groups=None and all fits fail. Turn on metadata routing and pass the groups as params; scikit-learn then routes them to the inner splitter too. Here with the customer data from above, where the honest score is 50%:
import sklearn
sklearn.set_config(enable_metadata_routing=True) # route groups to the inner searchgrouped_search = GridSearchCV(KNeighborsClassifier(), {"n_neighbors": [5, 15]}, cv=GroupKFold(3))nested_grp = cross_val_score(grouped_search, X_grp, y_grp, cv=GroupKFold(5), params={"groups": customer})sklearn.set_config(enable_metadata_routing=False) # back to the defaultprint(f"grouped nested CV {nested_grp.mean():.2f}")grouped nested CV 0.48Time series need no routing: TimeSeriesSplit uses the row order, so GridSearchCV(..., cv=TimeSeriesSplit()) inside cross_val_score(..., cv=TimeSeriesSplit()) works as written.
Leakage risks
Section titled “Leakage risks”| Leak | Example | Symptom | Fix |
|---|---|---|---|
| preprocessing on all rows | StandardScaler().fit(X) before CV |
slightly optimistic scores | put every learned step in a Pipeline |
| feature selection on all rows | SelectKBest().fit(X, y) before CV |
random data scores far above chance | selector inside the pipeline |
| target encoding on all rows | groupby(cat)[y].mean() mapped onto training rows |
high-cardinality columns look magical | TargetEncoder inside the pipeline |
| resampling before the split | SMOTE().fit_resample(X, y), then CV |
recall and F1 far too high | imblearn.pipeline.Pipeline |
| shared entities across folds | the same customer in train and validation | score drops in production | GroupKFold |
| random folds on time data | KFold(shuffle=True) on daily data |
the backtest beats production by far | TimeSeriesSplit |
| future information in features | rolling(7, center=True), bfill(), totals over the whole period |
a perfect-looking backtest | shift(1) before rolling; features known at prediction time only |
| a label delay ignored | the last week’s labels not yet known in production | the model relies on very fresh data | gap= in TimeSeriesSplit |
| post-outcome columns | a “cancellation reason” for churn | one feature explains everything | drop columns created after the outcome |
| duplicates across the split | the same review twice | inflated text-classification scores | deduplicate before the split |
| tuning on the test set | choosing the threshold or model by test score | a test score you cannot reproduce | choose with CV; look at the test set once |
reporting best_score_ |
the maximum over many candidates | optimistic by a few points | nested CV or a fresh test set |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| nested CV with a group splitter inside | all fits fail: the inner groups is None |
metadata routing and params={"groups": g} |
groups= with KFold or StratifiedKFold |
ignored, with a warning | a group splitter |
cv=5 with a classifier |
StratifiedKFold without shuffling |
pass StratifiedKFold(5, shuffle=True, random_state=42) |
cv=5 with a regressor on a sorted file |
each fold holds one range of the target | KFold(5, shuffle=True, random_state=42) |
TimeSeriesSplit on unsorted rows |
folds mix past and future | sort by time first |
TimeSeriesSplit on panel data with one row per series per day |
test days overlap training days of other series | split on unique dates, then select rows |
shuffle=True without random_state |
different scores on every run | random_state=42 |
GroupKFold(shuffle=True) |
TypeError on old versions |
scikit-learn 1.6 or newer |
| a single train/test split on small data | the score depends on the seed | repeated CV, report mean ± std |
LeaveOneOut for model selection |
slow and noisy | 5 or 10 folds, repeated |
| comparing models on different folds | differences come from the splits | the same splitter object (fixed seed) for all models |
cross_val_predict scored as a whole |
not the same as the mean fold score | use it for plots; report cross_val_score |
| standard deviation of fold scores read as a CI | the training sets overlap, so the fold scores are correlated and the spread understates the uncertainty | treat it as a rough spread |
| the search refit forgotten | the best parameters, but no fitted model | refit=True (default), then search.best_estimator_ |
Learn more
Section titled “Learn more”- Module 34: scikit-learn workflow and its cheat sheet
- Module 37: model evaluation and tuning and its cheat sheet
- Module 40: time series and its cheat sheet
- Module 33: feature engineering for the leakage checklist
- Decision guides: which metric and which algorithm