Sub topic 9
Time-ordered data: forward-chaining splits
This chapter assumes you know how k-fold cross-validation works, why preprocessing belongs inside a pipeline, and the basics of scikit-learn's fit/predict API. It covers what changes when your rows have a time order, and how to split them so the score still means something.
Why shuffled k-fold fails on time-ordered data
Ordinary k-fold assigns rows to folds without regard to when they occurred. With shuffle=True it mixes them freely. For data like daily sales, sensor readings, or stock prices, this causes two problems.
- Training on the future. A fold may train on March and April and test on February. In production you never have tomorrow's data when you predict tomorrow, so the score answers a question you will never ask.
- Neighbouring rows are not independent. Time series are usually autocorrelated, meaning that today's value is similar to yesterday's. If Tuesday is in the training set and Wednesday is in the test set, the model can score well by recognizing near-copies of rows it has already seen. The estimate is optimistic for the same reason a training-set score is optimistic.
The fix is to make the validation scheme mimic deployment. Train only on the past, test only on the future.
How forward-chaining splits work
Forward-chaining splitting is also called rolling-origin evaluation. It cuts the data into consecutive blocks. In each split, the training set contains everything up to some point, and the test set is the block right after it. The training window grows from split to split.
scikit-learn implements this as TimeSeriesSplit.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(6, 2)
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
print("train:", train_idx, "test:", test_idx)The output is:
train: [0 1 2] test: [3]
train: [0 1 2 3] test: [4]
train: [0 1 2 3 4] test: [5]Several details differ from KFold.
- The rows must already be sorted by time.
TimeSeriesSplitknows nothing about timestamps. It only uses row positions. Sort your data first. - There is no shuffling. Shuffling would destroy the order the splitter depends on.
- The first block is never tested. With
n_splits=3, the data is cut into 4 blocks. The first block is only ever training data. - Not every row is tested. In ordinary k-fold, each row is tested exactly once. Here, the earliest rows are never in a test set. The folds also use different amounts of training data, so early folds have noisier models.
- The test sets do not overlap. Each one is a separate block, so each later row is tested once.
Fixed-size windows and gaps
TimeSeriesSplit has three parameters that change this basic behaviour.
| Parameter | Effect | When to use it |
|---|---|---|
| `max_train_size` | Caps the training window, giving a sliding window instead of an expanding one | The process drifts and old data hurts, or you want equal training cost per fold |
| `test_size` | Fixes the number of rows in each test block | You want test sets that match your real forecast horizon |
| `gap` | Skips that many rows between the end of training and the start of the test block | Features use lagged or rolling values, or labels look ahead in time |
The next example uses all three.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(20).reshape(10, 2)
tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=1, max_train_size=4)
for train_idx, test_idx in tscv.split(X):
print("train:", train_idx, "test:", test_idx)The output is:
train: [1 2 3 4] test: [6 7]
train: [3 4 5 6] test: [8 9]Only two splits appear here, not three. With 10 rows, test_size=2, and gap=1, a third split would need more rows than exist. Setting test_size and gap reduces how many splits fit. Always check the number of splits you actually get with tscv.get_n_splits(X) and by iterating.
The gap deserves its own explanation. Suppose you predict whether a customer will churn within the next 7 days, and the label for day t is only known at day t + 7. A training row at day t then contains information about days up to t + 7. If the test block starts at t + 1, the training labels overlap in time with the test period. A gap at least as long as the label horizon removes that overlap. The same applies when a feature is a 30-day rolling mean. Rows near the boundary share data across the split.
Running a time-series cross-validation
You pass a TimeSeriesSplit object as cv to cross_val_score, exactly as with any other splitter. The following example builds a synthetic series with a trend and a weekly cycle, adds lag features, and compares forward-chaining against shuffled k-fold.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score
rng = np.random.default_rng(0)
n = 400
t = np.arange(n)
y = 0.05 * t + 3 * np.sin(2 * np.pi * t / 7) + rng.normal(0, 1, n)
df = pd.DataFrame({"y": y})
df["lag1"] = df["y"].shift(1)
df["lag2"] = df["y"].shift(2)
df["lag7"] = df["y"].shift(7)
df["day_of_week"] = t % 7
df = df.dropna().reset_index(drop=True)
X = df[["lag1", "lag2", "lag7", "day_of_week"]]
target = df["y"]
model = RandomForestRegressor(n_estimators=100, random_state=0)
shuffled = KFold(n_splits=5, shuffle=True, random_state=0)
forward = TimeSeriesSplit(n_splits=5, gap=1)
for name, cv in [("shuffled KFold", shuffled), ("TimeSeriesSplit", forward)]:
scores = cross_val_score(
model, X, target, cv=cv, scoring="neg_mean_absolute_error"
)
print(f"{name:16s} MAE = {-scores.mean():.2f} +/- {scores.std():.2f}")The exact numbers depend on your library versions, but the pattern is typical. Shuffled k-fold reports a lower error than forward-chaining. The series has an upward trend, and a random forest cannot extrapolate beyond the target values it saw in training. In forward-chaining, the test blocks sit at higher values than most of the training data, so the model underpredicts. Shuffled k-fold hides this weakness because every test row has training rows on both sides in time. The forward-chaining number is the honest one if you plan to forecast forward.
Note the use of neg_mean_absolute_error. scikit-learn scorers follow the rule that a higher value is better, so error metrics are negated. Flip the sign before reporting.
Preprocessing and leakage in time-ordered data
Everything from the pipeline chapter still applies. Fit scalers and imputers inside each training window. Time adds extra ways to leak.
- Future-looking features. Centered rolling windows,
shift(-1), and interpolation across the whole series all use future values. Use only trailing windows and positive shifts. - Global statistics. Normalizing a column by the mean of the entire series gives each training row information about the future. Put the scaler in a pipeline so it is fit on the training window only.
- Feature creation before splitting. Lag features built on the full series are fine, because each row uses only its own past. Aggregates like "the average target for this store" are not fine unless computed from training rows only.
- Hyperparameter search.
GridSearchCVaccepts any splitter ascv. Pass aTimeSeriesSplitso the search respects time. A shuffled inner loop would reintroduce the problem inside the tuning step.
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import GridSearchCV, TimeSeriesSplit
search = GridSearchCV(
GradientBoostingRegressor(random_state=0),
param_grid={"max_depth": [2, 3], "n_estimators": [50, 150]},
cv=TimeSeriesSplit(n_splits=4, gap=1),
scoring="neg_mean_absolute_error",
)For an unbiased final estimate, nested cross-validation also works with time order. Use a TimeSeriesSplit for both loops, and keep the inner loop entirely inside the outer training window.
Choosing between expanding and sliding windows
An expanding window uses all available history. It gives the model the most data and suits stable processes. A sliding window (max_train_size) uses only recent history. It suits data where the relationship changes over time, called concept drift, and it keeps every fold's training set the same size, which makes fold scores easier to compare.
You can decide empirically. Run both and compare the scores on the most recent folds, since recent behaviour is what you will face in production. Also think about which choice you will use when you deploy. If you will retrain on all history, validate with an expanding window.
Limitations and common mistakes
- Few usable folds. Each fold's training window is smaller than the full dataset, and early folds are especially small. Scores on early folds can be poor for reasons that say nothing about your final model.
- Fold scores are correlated. Expanding windows share most of their training rows. The standard deviation across folds understates uncertainty, so treat it as a rough guide.
- Non-stationary data. If the process changes, the average across folds mixes old and new behaviour. Look at the fold scores in order, not only the mean. A steady decline can show that the model is going stale.
- Panel data. If you have many entities (stores, patients) each with its own time series, a plain
TimeSeriesSpliton the pooled rows splits by row position and will mix entities in unintended ways. Sort by time across all entities and split on dates, or write a custom splitter that cuts on a date threshold. - Irregular timestamps.
TimeSeriesSplitcuts by row count, so uneven sampling gives test blocks that cover different durations. A custom splitter on calendar dates is more faithful in that case. - Not sorted. The most common bug. Check with
df.index.is_monotonic_increasingor sort explicitly before splitting.
Exercise
A dataset has one row per day, and the label for day t is the sales total over days t+1 to t+7. You use TimeSeriesSplit and your scores look better than the live results. What is the likely cause, and which parameter would you change and to what value?
Show answer
The training labels near the end of each training window cover days that fall inside the test block, so the training set overlaps the test period in time. This leaks information about the test period. Set gap to at least 7 (the label horizon in rows, since there is one row per day) so the training window ends at least 7 rows before the test block begins.
Exercise
You call TimeSeriesSplit(n_splits=4) on 500 rows sorted by time. Approximately how many rows are in the first training set and in each test set, and are the first 100 rows or so ever used for testing?
Show answer
The data is cut into 5 blocks of about 100 rows each. The first training set is the first block (about 100 rows), and each test set is about 100 rows. The first block is never used for testing, because every test block comes after at least one block of training data.