TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Random, Stratified, Group and Time-Based Splits

Random, Stratified, Group and Time-Based Splits

Every number you report about a model is only as honest as the split behind it. The test set must play the role of future data the model has never seen, and the way you cut the data decides whether it really does. The basic train/test split is covered in ML Train/Test; this section of the course goes through the eight split strategies of a careful project. This lesson covers the four ways to make a single hold-out split: random, stratified, group-based and time-based. The next lesson repeats splits as cross-validation, and Nested Cross-Validation adds model selection.

Three sets, three jobs

Set Used for Touched
Training fitting the model and every preprocessing step (imputer, scaler, encoder, sampler) all the time
Validation choosing models, hyperparameters, thresholds, features many times
Test one final, unbiased estimate once, at the end

A common choice is 60/20/20 or 70/15/15; with very large data the validation and test sets can be a small share and still contain many thousands of rows. Which rows go where is the real question:

random any row, anywhere group P1P2P3P4P5P6 rows of a patient together time JanDec past trains, future tests training validation test

Random and stratified splits

A random split is right when rows are independent and the classes are not rare. With a rare class, chance alone can put too few positives into a small test set. A stratified split keeps the class ratio the same in every part:

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split

y = np.array([1] * 12 + [0] * 228)          # 5% positives, 240 rows
X = np.arange(len(y)).reshape(-1, 1)

random_counts = [int(train_test_split(X, y, test_size=0.2, random_state=s)[3].sum()) for s in range(8)]
strat_counts = [int(train_test_split(X, y, test_size=0.2, stratify=y, random_state=s)[3].sum()) for s in range(8)]
print("positives in a 48-row test set, random:    ", random_counts)
print("positives in a 48-row test set, stratified:", strat_counts)

# A 60/20/20 three-way split: split twice, stratifying both times
X_tmp, X_te, y_tmp, y_te = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
X_tr, X_va, y_tr, y_va = train_test_split(X_tmp, y_tmp, test_size=0.25, stratify=y_tmp, random_state=0)
for name, part in [("train", y_tr), ("val", y_va), ("test", y_te)]:
    print(f"{name:<5} rows={len(part):>3}  positives={int(part.sum())}")
positives in a 48-row test set, random:     [3, 2, 1, 2, 2, 2, 3, 5]
positives in a 48-row test set, stratified: [2, 2, 2, 2, 2, 2, 2, 2]
train rows=144  positives=8
val   rows= 48  positives=2
test  rows= 48  positives=2

Twelve positives in 240 rows means 2.4 expected in a 48-row test set. Eight random splits put between 1 and 5 positives there: one split would judge the model on a single positive case, another on five. Stratified splits always give 2. In the three-way split the 12 positives become 8, 2 and 2. The second test_size=0.25 takes a quarter of the remaining 80%, which is 20% of the whole.

Group splits: keep related rows together

Many datasets contain several rows per entity: visits per patient, photos per person, transactions per customer, frames per video, readings per device. Rows of the same entity look alike. If some of a patient's rows train the model and others test it, the model can recognise the patient instead of learning the medical pattern, and the test score measures memory. A group split puts all rows of an entity into the same set:

python · try it yourself
import numpy as np
from sklearn.model_selection import train_test_split, GroupShuffleSplit
from sklearn.neighbors import KNeighborsClassifier

rng = np.random.default_rng(0)
n_patients, visits = 60, 8
patient = np.repeat(np.arange(n_patients), visits)
label = rng.integers(0, 2, n_patients)[patient]               # diagnosis per patient
signal = 0.4 * label[:, None] * np.array([1.0, -1.0, 0.5])      # weak true effect
fingerprint = rng.normal(0, 2, (n_patients, 3))[patient]        # each patient's own baseline
X = signal + fingerprint + rng.normal(0, 0.3, (len(patient), 3))

model = KNeighborsClassifier(n_neighbors=1)
X_tr, X_te, y_tr, y_te = train_test_split(X, label, test_size=0.25, random_state=0)
print(f"random row split:  accuracy {model.fit(X_tr, y_tr).score(X_te, y_te):.3f}")

gss = GroupShuffleSplit(n_splits=1, test_size=0.25, random_state=0)
tr, te = next(gss.split(X, label, groups=patient))
shared = set(patient[tr]) & set(patient[te])
print(f"group split:       accuracy {model.fit(X[tr], label[tr]).score(X[te], label[te]):.3f}"
      f"  (patients in both sets: {len(shared)})")
random row split:  accuracy 0.900
group split:       accuracy 0.533  (patients in both sets: 0)

Each of the 60 patients has 8 visits, a label that belongs to the patient, a weak real effect and a strong personal baseline. With a random row split, a 1-nearest-neighbour model scores 0.900: for almost every test visit it finds another visit of the same patient in the training set and copies that patient's label. Split by patient (no patient on both sides) and the accuracy falls to 0.533, close to the 0.5 of guessing. The 0.900 measured how well the model recognises patients it has met, not how well it diagnoses new ones.

How do you know the groups? From identifiers (patient_id, customer_id, device_id, video_id), from data collection (session, camera, recording day, annotator batch), and from duplicate detection for near-copies without an ID. When the model will be used on new entities, the split must be by entity.

Time-based splits: train on the past, test on the future

When the model will predict the future, the test set must lie after the training set in time. A random split lets the model see tomorrow's data while predicting today, and trends, seasons and slowly drifting behaviour all make that look better than it is.

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(1)
dates = pd.date_range("2025-01-01", periods=365, freq="D")
df = pd.DataFrame({"date": dates, "sales": np.round(100 + 0.2 * np.arange(365) + rng.normal(0, 5, 365), 1)})
df = df.sample(frac=1, random_state=0)                      # data often arrives unsorted

df = df.sort_values("date")
train = df[df["date"] < "2025-09-01"]
valid = df[(df["date"] >= "2025-09-01") & (df["date"] < "2025-11-01")]
test = df[df["date"] >= "2025-11-01"]
for name, part in [("train", train), ("valid", valid), ("test", test)]:
    print(f"{name:<5} {part['date'].min().date()} .. {part['date'].max().date()}  rows={len(part):>3}  mean sales={part['sales'].mean():.1f}")
train 2025-01-01 .. 2025-08-31  rows=243  mean sales=123.7
valid 2025-09-01 .. 2025-10-31  rows= 61  mean sales=153.8
test  2025-11-01 .. 2025-12-31  rows= 61  mean sales=166.5

Shuffled rows are sorted back into date order and cut at fixed dates: training from January to August (243 days), validation September–October (61), test November–December (61). Because sales grow through the year, the mean rises from 123.7 to 153.8 to 166.5: the validation and test periods really are a different, later world, and that is exactly what a forecasting model will face. Cut by a date, not by a row count, so that the cut means the same thing when the data is refreshed. If features are built from history (lags, rolling means), leave a gap between training and test at least as long as the longest window, so that no test-period value feeds a training feature. More in Preparing Time-Series Data.

Pitfalls

  • Splitting after preprocessing: split first, then fit every preprocessing step on the training part (The Leakage Rules).
  • Random split of grouped data: near-identical rows on both sides inflate the score. Ask "what is one independent unit here?" before splitting.
  • Random split of temporal data: the model learns from the future.
  • Looking at the test set "just once" many times: every decision made after seeing test results turns the test set into a validation set.

Practice

  1. A dataset has 5,000 photos of 400 people, used to build a face-based age estimator for new users. Which split do you use?
Answer

A group split by person (GroupShuffleSplit or GroupKFold with groups=person_id). New users are new people; with a random split the model can recognise a person's face from another photo and recall their age.

  1. You forecast daily electricity demand with features "demand 1, 7 and 28 days ago". Your training data ends on 31 May and the test period starts on 1 June. Is there a leak?
Answer

Not from the lag features themselves: the test-period features use values up to 28 days earlier, which are known at prediction time. But the training rows' features must not use test-period values, and if the model will forecast more than one day ahead, lags shorter than the horizon are not available in practice. Build the features exactly as they would be known at prediction time.

Test yourself

When is a stratified split especially important?

  1. When the dataset has many columns
  2. When one class is rare and the test set is small
  3. For time series
  4. When rows are grouped by customer

A random row split of patient visits gives 0.95 accuracy, a split by patient 0.62. Which number estimates performance on new patients?

  1. 0.95
  2. 0.62
  3. Their average
  4. Neither

Which split should a sales forecasting model use?

  1. Random
  2. Stratified
  3. Time-based: train on earlier dates, test on later ones
  4. Group by product only

Which set is used to choose hyperparameters?

  1. Training
  2. Validation
  3. Test
  4. All three