Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathData and Features in Production
  1. 1
    Time Splits and Group Splits: Make the Split Match How the Model Is Used
  2. 2
    Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
  3. 3
    Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
  4. 4
    Point-in-Time Correctness: Join Features as of Each Event with merge_asof
  5. 5
    Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
  6. 6
    Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
  7. 7
    Feature Stores: Offline and Online Stores, and When You Actually Need One
  8. 8
    Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. MLOps and Production ML

Learning path: Data and Features in Production · Step 1 of 8

Time Splits and Group Splits: Make the Split Match How the Model Is Used

One model on Rain in Australia, scored after a random split, a time split and a group split by town. The gaps are small here, but the spread across towns is wide, and the split you pick decides what the score means.

Chaand Sheikh

·27 November 2026Data and Features in Production

What you will learn

  • Cut the rows by date so the model trains on earlier days and is tested on later ones
  • Make several walk-forward cuts with TimeSeriesSplit and read the spread
  • Hold out whole towns with GroupShuffleSplit and LeaveOneGroupOut
  • Pick the split that copies how the model will really be used, then report the gap and the spread

Before you start

  • Train-Test Split and Data Leakage
  • Cross-Validation: KFold and StratifiedKFold
  • Pipelines and ColumnTransformer

Imagine a student who practises with next week's exam paper. He gets a great score, and it's useless, because it says nothing about a paper he hasn't seen. Another student practises with old papers, then sits next week's paper cold. That score tells you something.

In our data, the old papers are the earlier days and next week's paper is the later days. A random split mixes later days into training. In Train-Test Split and Data Leakage we learned to split first. Now we ask a second question: does the split match how the model will be used?

We'll take one model and one dataset, Rain in Australia, cut the rows in three ways, and measure the gap. To be honest up front: the big score drop people warn about did not show up on this data. What did show up is just as useful.

One table, three ways to cut it

Picture the data as a table where every column is a date and every row is a town.

Random, time and group splits of the same table Random split dates → Every town and nearly every date on both sides Time split dates → Train on earlier dates, test on later ones Group split dates → Whole towns go to test, the model never meets them towns train test
The same rows, cut three ways. Each cut asks the model a different question.
  • A random split picks cells from everywhere, so every town and nearly every date sits on both sides.
  • A time split cuts down the table. Training gets the earlier dates, the test gets the later ones.
  • A group split cuts across it. Whole towns go to the test, and the model never meets them.

The data, in date order

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import (
    GroupShuffleSplit, LeaveOneGroupOut, TimeSeriesSplit,
    train_test_split)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("weatherAUS.csv")
df["Date"] = pd.to_datetime(df["Date"])
df = df.sort_values("Date").reset_index(drop=True)
print(df.shape, df["Location"].nunique(), "towns")
print(df["Date"].min().date(), "to", df["Date"].max().date())
(142193, 24) 49 towns
2007-11-01 to 2017-06-25

Sorting by date matters later: TimeSeriesSplit counts rows, so the rows must already be in time order.

# Date and RISK_MM stay out, as in the leakage lesson
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = (df["RainTomorrow"] == "Yes").astype(int)
rows = np.arange(len(df))
towns = df["Location"]
print(X.shape, round(y.mean(), 3))
(142193, 21) 0.224

21 input columns, and it rains tomorrow on 22.4% of days.

One model, one way to score it

Every split gets the same check, so only the split changes. The model is a two-lane pipeline (see Pipelines and ColumnTransformer) plus logistic regression:

def make_model():
    nums = X.select_dtypes("number").columns
    cats = X.select_dtypes(exclude="number").columns
    num = make_pipeline(SimpleImputer(strategy="median"),
                        StandardScaler())
    cat = make_pipeline(
        SimpleImputer(strategy="most_frequent"),
        OneHotEncoder(handle_unknown="ignore"))
    both = ColumnTransformer([("num", num, nums),
                              ("cat", cat, cats)])
    return make_pipeline(both,
                         LogisticRegression(max_iter=1000))

def check(train, test):
    model = make_model()
    model.fit(X.iloc[train], y.iloc[train])
    proba = model.predict_proba(X.iloc[test])[:, 1]
    truth = y.iloc[test]
    acc = accuracy_score(truth, proba >= 0.5)
    auc = roc_auc_score(truth, proba)
    return acc, auc, 1 - truth.mean()

check takes the row numbers for train and test, builds a fresh model, fits it on the train rows only, and returns three numbers: accuracy, AUC, and what always saying "no rain" would score on those test rows. A small report helper prints the mean and the range of each:

def report(name, runs):
    acc, auc, no = np.array(runs).T
    for what, v, f in [("acc", acc, ".2%"), ("auc", auc, ".3f"),
                       ("no ", no, ".2%")]:
        print(f"{name:7}{what} {v.mean():{f}} "
              f"({v.min():{f}} to {v.max():{f}})")

Random split, twenty seeds

random_runs = []
for seed in range(42, 62):
    train, test = train_test_split(
        rows, test_size=0.2, stratify=y, random_state=seed)
    random_runs.append(check(train, test))
print(len(train), len(test))
report("random", random_runs)
113754 28439
random acc 84.75% (84.32% to 85.18%)
random auc 0.870 (0.864 to 0.874)
random no  77.58% (77.58% to 77.58%)

Same model, different rows, and the score moves from 84.32% to 85.18%. One seed can move it by nearly a point, so run several before you claim anything.

Time split: train on earlier, test on later

cut = df["Date"].quantile(0.8)
train = rows[df["Date"] < cut]
test = rows[df["Date"] >= cut]
print(cut.date(), len(train), len(test))
acc, auc, no = check(train, test)
print(f"time   acc {acc:.2%}  auc {auc:.3f}  no {no:.2%}")
2015-11-10 113748 28445
time   acc 84.32%  auc 0.857  no 77.68%

quantile(0.8) finds the date that cuts off the last 20% of rows. Everything before it trains, everything from it on tests. There's no seed, because nothing here is random.

84.32%: a gap of 0.43 of a point, level with the lowest random seed. That's small. But one cut is one stretch of time, so let's make more.

Several cuts with TimeSeriesSplit

cuts = TimeSeriesSplit(n_splits=5).split(rows)
cut_runs = [check(a, b) for a, b in cuts]
print([round(r[0] * 100, 2) for r in cut_runs])
report("5 cuts", cut_runs)
[83.73, 84.53, 85.34, 85.34, 83.89]
5 cuts acc 84.57% (83.73% to 85.34%)
5 cuts auc 0.867 (0.856 to 0.878)
5 cuts no  77.39% (74.65% to 79.29%)

It looks like the k-fold splitters from Cross-Validation, with one difference: the test block always comes after the training rows, never before. Each cut trains on everything before it. The scores move by 1.61 points from one stretch to another, which is bigger than our gap. So on this data, which stretch you test on matters more than the split itself. (Walking forward through time gets its own lesson in Time Series Basics.)

Group split: no town on both sides

gss = GroupShuffleSplit(n_splits=20, test_size=0.2,
                        random_state=42)
town_runs = []
for train, test in gss.split(rows, groups=towns):
    town_runs.append(check(train, test))
seen, new = set(towns[train]), set(towns[test])
print(len(seen), len(new), "shared:", len(seen & new))
report("town", town_runs)
39 10 shared: 0
town   acc 83.68% (80.77% to 87.24%)
town   auc 0.857 (0.823 to 0.897)
town   no  77.65% (74.55% to 81.02%)

GroupShuffleSplit holds out 20% of the towns, not the rows. 39 towns train, 10 test, and none are shared.

Why handle_unknown="ignore" matters here. The test towns are new to the encoder. Without that setting, the pipeline stops with an error the first time it meets one.

The mean is 83.68%, about one point below random. Look at the spread, though: 80.77% to 87.24%, nearly six and a half points. Even "always no" moves, because the towns you happen to pick change how rainy the test is.

Accuracy by split, every run as a dot Random, 20 seeds Time, one cut Time, 5 cuts Town, 20 splits 80% 82% 84% 86% 88% accuracy red line = mean
Every run as a dot, from the notebook's own scores. Random seeds sit in a tight band; town splits spread across almost the whole axis.

Every town held out once

scores = {}
for train, test in LeaveOneGroupOut().split(rows, groups=towns):
    acc, auc, no = check(train, test)
    scores[towns.iloc[test[0]]] = [acc, no]
by_town = pd.DataFrame(scores, index=["acc", "no"]).T
by_town = by_town.sort_values("acc").round(3)
print(by_town.iloc[[0, -1]])
print(by_town[by_town["acc"] < by_town["no"]])
               acc     no
MountGinini  0.725  0.718
Woomera      0.945  0.932
              acc     no
Wollongong  0.754  0.761

LeaveOneGroupOut holds out every town once: 49 towns, 49 models. Mount Ginini is the lowest at 72.5%, Woomera the highest at 94.5%. But it rarely rains in Woomera, so always saying no already gets 93.2% there.

And Wollongong: the model gets 75.4%, always-no gets 76.1%. For that one town, the model does worse than saying no every day, and the overall average hides it.

Is the gap the split, or just harder rows?

The scores above come from different test rows. To measure only "has the model met this period or this town?", the notebook scores the same rows twice. It keeps half the test rows to judge, and lends the other half to training (keeping the training size the same). One model never met those rows; the other has met their neighbours.

def same_rows(train, test, seed):
    rng = np.random.RandomState(seed)
    mixed = rng.permutation(test)
    half = len(mixed) // 2
    judge, seen = mixed[:half], mixed[half:]
    both = np.r_[train, seen]
    both = rng.permutation(both)[:len(train)]
    blind = check(train, judge)
    knows = check(both, judge)
    return knows[0] - blind[0], knows[1] - blind[1]

Run over 20 seeds for the time cut and over the 20 town splits, the notebook prints the average gain from having seen the neighbours:

time  acc +0.05 points (+0.01 to +0.13)
time  auc +0.002
town  acc +0.82 points (+0.16 to +1.69)
town  auc +0.007

For time, seeing the period adds just 0.05 of a point, so most of the time gap came from a harder stretch of days, not from seeing the future. For towns, knowing the town adds 0.82 points, and all 20 runs came out above zero. Both gaps are small here, and the town gap is the one that holds up.

Match the split to the use

If the gap is this small, why bother? Because the split decides what your score means.

How the model will be usedSplit that copies it
Predict tomorrow, in towns it knowsTime split (date cut or TimeSeriesSplit)
Go to a town it has never seenGroup by town (GroupShuffleSplit, LeaveOneGroupOut)
One customer has many rowsGroup by customer, so one person is never on both sides
No clock and no groupsRandom is fine

Weather is a kind case, because this model has no date and no id to memorise. Other data can show a much bigger gap. You run it and you see.

Common mistakes

  • Using a random split for a forecast. Later days leak into training, and the score answers a question nobody asked.
  • Forgetting to sort by date before TimeSeriesSplit. It cuts by row position.
  • Trusting one cut or one seed. Here, five time cuts moved more than the whole gap.
  • Reporting only the average. The town average hid Wollongong, where the model lost to always-no.
  • An encoder that can't meet new groups. Use handle_unknown="ignore" when groups are held out.

Quick recap

SplitAccuracySpread
Random, 20 seeds84.75%84.32% to 85.18%
Time, one cut at 2015-11-1084.32%one answer
Time, 5 cuts84.57%83.73% to 85.34%
Town, 20 splits83.68%80.77% to 87.24%
Each town once (49)-72.5% to 94.5%

Try it yourself

Move the time cut from quantile(0.8) to quantile(0.6). Does the time score move, and how does it compare with the random split?

The notebook and the dataset are in the StudyEasy AI Community, free to join.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
Next →
Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Python Virtual Environments: One Project, One Toolbox

Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.

Git and GitHub Fundamentals: Commits, Branches, Push and Pull

The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.

Testing a FastAPI App with pytest: Three Small Tests

A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.

Config and Logging Instead of Hard-Coded Values in ML Training

Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.

On this page
  • One table, three ways to cut it
  • The data, in date order
  • One model, one way to score it
  • Random split, twenty seeds
  • Time split: train on earlier, test on later
  • Several cuts with TimeSeriesSplit
  • Group split: no town on both sides
  • Every town held out once
  • Is the gap the split, or just harder rows?
  • Match the split to the use
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.