Skip to content
Visual explainer 3h 30m to learn 5 steps

Train-test splits, cross-validation and data leakage

Choose stratified, grouped or temporal splits, tune with cross-validation and keep a held-out test set free of leakage.

By Invicly Tech, , in AI and Machine Learning with Python. About 12 minutes to read.

Topic 11 of 34

In short

A test score is only worth trusting if the test rows look like the data the model will meet in use and nothing from them reached training. That means choosing a split that matches reality: stratified for rare classes, grouped when rows belong to the same customer or patient, and time-ordered when you predict the future. Cross-validation on the training part is used for tuning, and the held-out test set is scored once at the end.

Think of it like this: The test set is the final exam: you can practise on as many mock papers as you like, but if you see the real questions in advance, your grade says nothing about what you know.

Explained simply

A model is only useful if it works on data it has never seen. To check that, you hide some data from it during training and test it there afterwards. The hidden part is the test set. If the model does well on it, you have some reason to believe it will do well in real use.

How you split matters. If you predict whether a new customer will buy, the test set should hold customers the model never saw. If you predict tomorrow, the test set should be later in time than the training data. A split that does not copy real use gives a score that is too kind.

Cross-validation is a way to get several practice scores from the training data. You cut it into, say, five folds, train on four and score on the fifth, and repeat so each fold gets a turn. You use these scores to compare models and settings, keeping the test set for the very end.

Leakage is when the model gets a hint it would not have in real life. A classic example is a column filled in after the outcome, such as a cancellation reason when predicting cancellations. Another is fitting a scaler on all the data before splitting. Leakage makes models look great in testing and fail in production.

Press Play on a diagram to walk through it one step at a time.

MapWhich split fits your data?
How will the model be used?
  • Rows independent, rare class
    • StratifiedKFold
    • train_test_split(stratify=y)
  • Several rows per person or device
    • GroupKFold
    • StratifiedGroupKFold
  • Predict the future from the past
    • TimeSeriesSplit
    • Cut the test set by date
  • Rows independent, balanced
    • KFold with shuffle
    • Plain random split
FlowAn honest evaluation workflow
  1. 1
    Split once

    Lock away the test set

  2. 2
    Cross-validate

    Folds of the training set only

  3. 3
    Tune

    Search hyperparameters inside the folds

  4. 4
    Refit

    Best settings on all training data

  5. 5
    Test once

    Report the held-out score

SequenceWho sees which data during tuning
Training folds
Validation fold
Search
Test set
  1. 1Fit pipeline for each candidate
    Training folds to Search: Fit pipeline for each candidate
  2. 2Return a fold score
    Validation fold to Search: Return a fold score
  3. 3Average folds, pick best settings
    Search to Search: Average folds, pick best settings
  4. 4Refit best settings on all training data
    Search to Training folds: Refit best settings on all training data
  5. 5Score once at the very end
    Search to Test set: Score once at the very end

In depth

Stratified, grouped and temporal splits

Stratified splitting keeps the class mix the same in every fold. With 2 percent positives and plain random folds, one fold might get far fewer positives than another, making its score noisy. For classifiers, passing an integer cv to cross_val_score already uses StratifiedKFold.

Grouped splitting keeps every row from one group together. If a patient has ten scans, and some are in training and some in testing, the model can recognise the patient rather than the disease. GroupKFold handles this, and StratifiedGroupKFold also tries to keep class balance.

Temporal splitting trains on the past and tests on the future. TimeSeriesSplit produces expanding training windows, each followed by a later test window, and its gap parameter leaves a buffer between them when labels take time to arrive.

CompareWhat each splitter protects against
Stratified
  • Uneven class mix between folds
  • Noisy scores for rare classes
  • Use for most classification
Grouped
  • Same person on both sides
  • Model memorising identities
  • Pass groups= to split or cv
Temporal
  • Training on the future
  • Ignoring drift over time
  • Use TimeSeriesSplit or a date cut

Cross-validation and hyperparameter search

GridSearchCV tries every combination in a grid; RandomizedSearchCV samples a fixed number of combinations, which is usually better when there are many settings. Both run cross-validation for each candidate, pick the best mean score and, by default (refit=True), retrain the best settings on all the training data.

The best cross-validation score is slightly optimistic, because you chose it as the maximum of many noisy numbers. That is one reason to keep a separate test set. If you need an unbiased estimate without a test set, for example on small data, use nested cross-validation: an inner search inside each outer fold. Use the same splitter, such as StratifiedGroupKFold, in both the search and any outer loop, or leakage creeps back in.

  • Grid: every combination; random: a sample of them
  • refit=True retrains the winner on all training data
  • best_score_ is optimistic; the test set corrects that
  • Pass the right splitter and groups to the search

Finding leakage before it finds you

There are two families of leakage. Train-test leakage happens when information from evaluation rows shapes training: scaling, imputing, resampling or selecting features on the full dataset, or duplicate rows appearing on both sides. Pipelines solve most of it, because every step is fitted inside each training fold.

Target leakage happens when a feature encodes the answer or is only known after it. Ask for each feature: would I have this value at the moment of prediction? Warning signs include a score that is too good to be true, one feature dominating permutation importance, and a big drop when the model meets truly new data. Check timestamps of when each column is filled, and search for duplicates or near-duplicates across the split.

  • Would this value exist at prediction time?
  • Score suspiciously close to perfect
  • One feature dominates importance
  • Duplicates across train and test

Treating the test set with respect

Decide the test set first and do not look at it while you explore. Make every modelling choice with cross-validation or a validation set: features, model family, hyperparameters and threshold. Then refit and score the test set once. Write that number down along with the split method and the random seed.

If the test score disappoints and you change the model, you can do that, but be honest: the old test set is now part of development, and the next score you report from it is optimistic. On a long project, keep a fresh holdout aside, or collect newer data, for the final sign-off.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Pick stratified, grouped or time splits~40m
  2. 2
    Run cross-validation~40m
  3. 3
    Tune hyperparameters with search~40m
  4. 4
    Check for target and train-test leakage~40m
  5. 5
    Touch the test set once~40m

Key points

  • The split should copy the real situation: new customers, new days or new hospitals, not random rows from the same ones.
  • Put every preprocessing step in a Pipeline so scalers, imputers and encoders are fitted on training folds only.
  • Target leakage is a feature that would not be known at prediction time, such as a refund flag when predicting fraud.
  • Hyperparameter search with GridSearchCV or RandomizedSearchCV uses cross-validation; the test set stays out of it.
  • If you look at the test score and then change the model, the test set has become a validation set and its score is now optimistic.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
search = GridSearchCV(pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]},
                      cv=cv, scoring="roc_auc").fit(X_tr, y_tr)
print(search.best_params_, round(search.best_score_, 3))
print("test", round(search.score(X_te, y_te), 3))  # scored once

The scaler sits inside the pipeline, so each fold fits it on its own training part.

Seeing leakage from preprocessing in numbers

This demo uses pure random noise, so the honest score is about 50 percent. Step 1: create 100 rows with 10,000 random features and random labels. Step 2: the leaky way selects the 20 features most correlated with the label on all rows, then cross-validates a classifier. Step 3: the honest way puts the same SelectKBest step inside a pipeline. Expect the leaky version to report accuracy far above chance, and the pipeline version to sit near 0.5. The only difference is when feature selection saw the labels.

python
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.default_rng(0)
X = rng.normal(size=(100, 10000)); y = rng.integers(0, 2, 100)
X_leak = SelectKBest(f_classif, k=20).fit_transform(X, y)
print("leaky ", cross_val_score(LogisticRegression(), X_leak, y, cv=5).mean())
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
print("honest", cross_val_score(pipe, X, y, cv=5).mean())

Grouped versus random folds on repeated customers

You have support tickets, several per customer, and want to predict escalation for new customers. Step 1: run 5-fold KFold with shuffle. Step 2: run GroupKFold with customer_id as groups. Step 3: compare the scores. If customers have stable habits, the random version scores higher because the model has seen each customer before. The grouped score is the one that matches using the model on new customers, so report that one.

python
from sklearn.model_selection import GroupKFold, KFold, cross_val_score

# X, y, groups (customer_id) come from your synthetic ticket table
random_cv = KFold(n_splits=5, shuffle=True, random_state=0)
rand = cross_val_score(model, X, y, cv=random_cv, scoring="roc_auc")
grouped = cross_val_score(model, X, y, cv=GroupKFold(n_splits=5),
                          groups=groups, scoring="roc_auc")
print("random folds ", rand.mean().round(3))
print("grouped folds", grouped.mean().round(3))

Quick reference

  • Split off the test set first; never fit anything on it
  • Rare classes: StratifiedKFold or train_test_split(..., stratify=y)
  • Repeated entities: GroupKFold or StratifiedGroupKFold with groups=
  • Forecasting: TimeSeriesSplit; use gap= when labels arrive late
  • Put scalers, imputers, encoders and feature selection inside a Pipeline
  • Pipeline step parameters in a grid use the step name: logisticregression__C
  • Ask of every feature: is it known at prediction time?

Common mistakes

  • Scaling, imputing or selecting features on the whole dataset before splitting.
  • Random splits on data with repeated customers or time order, which lets the model memorise people or peek at the future.
  • Reporting the best cross-validation score from a big search as if it were the expected score on new data.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You predict whether a machine fails next week from sensor logs. Which split is most realistic?

Question 2

2Which of these is target leakage when predicting loan default?

Question 3

3What does GridSearchCV do with the best settings when refit=True?

Question 4

4Why should StandardScaler be inside the pipeline used for cross-validation?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Split the breast cancer data 80/20 with and without stratify=y and print the share of positives in each test set.

  2. Exercise 2medium

    Use RandomizedSearchCV to tune max_depth and min_samples_leaf of a DecisionTreeClassifier with stratified 5-fold CV, then score the test set once.

  3. Exercise 3hard

    Create a synthetic daily series with a trend, build lag-1 and lag-7 features, and compare a shuffled KFold score with a TimeSeriesSplit score for a Ridge model. Explain the gap.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How big should the test set be?
Big enough that the metric is stable, which depends on how many positives it contains, not only on its total size. Common choices are 15 to 25 percent; check the confidence interval of the test metric.
Do I still need a test set if I use cross-validation?
Yes, if you tune with cross-validation. The best cross-validation score is optimistic, and the test set gives an independent final check.
How many folds should I use?
Five or ten is typical. More folds give more training data per fold but cost more time; with very small data, repeated cross-validation reduces noise.
Is oversampling before splitting a problem?
Yes. Copies of a minority row can land in both training and validation. Resample inside each training fold only, for example with a pipeline from imbalanced-learn.

Go deeper

ShareXLinkedInWhatsApp