Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » General » Tips » How to Spot Data Leakage in a Python Time Series Split
Guest Author Categories: Tips. No Comments on How to Spot Data Leakage in a Python Time Series Split
Data Leakage in a Python Time Series Split

Join our newsletter! - Tips, contests and more. Click here to subscribe!


The training row that knows tomorrow’s sales

Suppose you run an online store. Every morning at midnight, you predict how many orders will arrive over the next 72 hours. To test your model, you train it on rows dated January 1 through January 6. Your first test prediction is for January 7. The rows are in order, and you never shuffled them. Can you trust the split?

 

Look at the training row dated January 6. Its inputs may all be available that morning. Its target, however, is the total number of orders from January 6 through January 8. When the model makes its January 7 prediction, some of those orders have yet to happen. Training on that row gives the model information it could never have used in production.

 

You can catch this problem before fitting a model. All you need are two timestamps for each row.

 

Give each training row two timestamps

The prediction time is when you would make the forecast. The evaluation time is when you have all the observations needed to calculate its target.

 

For this example, assume each order appears instantly in your database. The January 4 target counts orders from midnight on January 4 up to, but excluding, midnight on January 7. At midnight on January 7, that total is complete. The January 5 and January 6 totals are still open. That gives us a concrete expectation: keep January 4 in training and remove January 5 and 6.

 

Check the split in Python

Install purgedcv from PyPI with pip install purgedcv. The example uses scikit-learn to create a chronological split. Then the purge function removes training rows whose target windows overlap a test window.

import numpy as np
import pandas as pd
from sklearn.model_selection import TimeSeriesSplit

from purgedcv import purge

starts = pd.date_range("2025-01-01", periods=12, freq="D")
ends = starts + pd.Timedelta(hours=72)
X = np.arange(len(starts)).reshape(-1, 1)

cv = TimeSeriesSplit(n_splits=3, test_size=2)
train, test = next(cv.split(X))
clean_train = purge(train, test, starts, ends)
removed = np.setdiff1d(train, clean_train)

print("First test day:", starts[test[0]].date())
print("Removed from training:", starts[removed].strftime("%b %d").tolist())
print("Last training day:", starts[clean_train[-1]].date())

 

The first split produces:

First test day: 2025-01-07
Removed from training: ['Jan 05', 'Jan 06']
Last training day: 2025-01-04

 

Why remove only two rows for a three-day target? The January 4 window ends exactly when the January 7 window starts. They share no orders. Moving the cutoff back one more day would discard a training example whose answer was already available.

 

Apply the check to your own data

Start with one fold from your current validation code. Print the first test timestamp. Then inspect the last few training rows and ask: could I have calculated this target at the exact moment of that first test prediction?

 

Use the time the answer actually became available. For example, if a warehouse posts its final order count at 02:00, the January 4 total is still unavailable for a midnight forecast. Use 02:00 on January 7 as the evaluation time for the January 4 row. That row must also drop out of training for the midnight forecast.

 

This gives you a way to audit a split even when you have no benchmark score to compare against. Pick a boundary, work out which rows you expect to keep, and check the indices before you fit the model. Python package and examples on GitHub

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *


Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory