Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 111/ 160
06. Feature Engineering & Model Evaluation

Time-Series Split Validation

Validate temporal models with forward-chaining splits that respect time order.

AdvancedTimeSeriesSplit · Walk-forward3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

For data over time, you always train on earlier data and test on later data, rolling forward, because that's how the model will really be used.

Think of it like…

Judging a weather forecaster: you can't hand them next week's data and then ask for a prediction; you give them data up to today, ask about tomorrow, then move the date forward and repeat, scoring each day on what they didn't know.

Where you’ve seen it

A demand dataset has 60 months. TimeSeriesSplit(n_splits=5) uses a test size of n/(n_splits + 1) = 10 months: folds train on months 1–10 and test 11–20, train 1–20 and test 21–30, train 1–30 and test 31–40, train 1–40 and test 41–50, train 1–50 and test 51–60. Errors by fold are MAE 8.1, 8.4, 9.0, 11.2 and 12.9, rising as the training window grows because demand patterns changed after month 35, an insight a random split would hide (it reports MAE 6.2 on the same data because neighbouring months leak). Features include a 28-day rolling mean and a forecast horizon of 7 days, so the validation block must start at least 7 days (gap = 7) after training ends, and rolling features are computed only from data available at the forecast origin. The team compares an expanding window (uses all history) with a 24-month sliding window and finds the sliding window better in later folds (MAE 10.6 versus 12.9) because older patterns are stale, and chooses to retrain monthly on the last 24 months.

Words you’ll hear

Forward chaining
Training on all data up to a point and validating on the next block, repeatedly.
Expanding vs sliding window
Growing training history versus a fixed-length recent window.
Gap / embargo
A buffer between training and validation to prevent leakage from overlap or lags.
Walk-forward validation
Repeated retrain-and-forecast cycles across many origins.

Visual diagram

Loading interactive diagram

Theory & deep dive

Splitters and what they guarantee

TimeSeriesSplit(n_splits=5, test_size=None, gap=0, max_train_size=None) yields (train, test) index pairs in time order: with 60 observations and the default test size of 60/6 = 10, the first fold trains on 10 and tests on the next 10, the second trains on 20 and tests on the following 10, and so on up to training on 50 and testing on the last 10. Setting max_train_size gives a sliding window; gap skips observations between the end of training and the start of validation. The data must be sorted by time and must not be shuffled. For panel data (many entities over time) use group-and-time aware splits such as splitting by date across all entities, or GroupTimeSeriesSplit implementations, ensuring that no future rows of any entity are in training.

Why random splits fail: observations at adjacent times are strongly correlated, so a random validation point has near-duplicates in training (the previous and next day), and the model scores well by interpolation. In the example, random K-fold reported MAE 6.2 versus 8.1 to 12.9 under forward chaining: the difference is leakage, not skill. Also think about what changes over time: seasonality (include at least one full cycle in training), trends and regime shifts, and the availability of external variables at forecast time (a promotion calendar you know in advance versus weather you don't).

Fold boundaries

60 months, 5 splits, test size 10. Fold k trains on months 1..(10k) and tests on (10k + 1)..(10k + 10): (1–10 | 11–20), (1–20 | 21–30), (1–30 | 31–40), (1–40 | 41–50), (1–50 | 51–60).

Key takeaway: Use time-ordered, forward-chaining splits (expanding or sliding), never shuffle, and ensure validation lies in the future.

Gaps, leakage, window choice and reporting

Embargo and gap: if the model predicts 7 days ahead, targets and features near the boundary overlap in time. A feature computed from a 28-day window ending at the last training day contains information that overlaps the validation period's targets when the horizon is 7 days; use gap ≥ horizon (and ≥ the longest label or feature window overlap) so validation is truly out-of-sample. Build features as of the forecast origin: rolling statistics, target encodings and aggregates computed using only data up to that time (shift before rolling), and recompute them within each fold when they depend on training statistics. Exogenous variables must be those available at forecast time, not values observed later.

Window choice: an expanding window uses all history and suits stable processes; a sliding window (for example 24 months) adapts to drift by discarding old patterns, and often wins when the process is non-stationary (MAE 10.6 versus 12.9 in later folds of the example). Treat window length and retraining cadence as hyperparameters selected by walk-forward validation. Report per-fold errors and their trend (rising error signals drift), use metrics suited to the problem (MAE, MASE against a seasonal-naive baseline, quantile loss for intervals), and aggregate over many origins rather than a single split. For hyperparameter tuning, use a nested scheme in time (inner splits within the training period), keep the final most recent period as an untouched test set and monitor production error against backtest expectations after deployment.

Gap for a 7-day horizon

Features include a 28-day rolling mean and the target is demand 7 days ahead. With gap = 0 the last training row's target (7 days later) falls inside the validation block. Using gap = 7 (or more) ensures no training target overlaps validation inputs or labels.

Key takeaway: Add a gap at least as long as the horizon and label windows, compute features as of the origin, and choose window and retraining cadence by walk-forward backtests.

How it works, step by step

Step 1 of 4
Analyst

1. Sort by time and define the horizon

Order the data, fix the forecast horizon and decide which variables are known at forecast time.

7-day-ahead forecast
Key numbers at this step
No
shuffling

When to use it & trade-offs

What it is

Time-series validation evaluates models the way they'll be used: train on the past, test on the future. Random K-fold is invalid because it lets the model learn from later observations and tests on earlier ones. The standard scheme is forward chaining (an expanding window): TimeSeriesSplit creates successive folds where the training set grows and the validation block always comes after it; a sliding (rolling) window keeps the training length fixed. A gap (embargo) between train and validation prevents leakage from lagged features or overlapping targets, and walk-forward validation repeats this over many origins, retraining each time, to give a distribution of future-performance estimates.

Why it matters: Time-ordered data is autocorrelated and non-stationary: a random split places neighbours of every test point in training, so the model interpolates rather than forecasts, and scores look wonderful until production. Proper temporal validation also reveals drift (error rising in later folds), lets you choose training-window length and retraining cadence and gives realistic confidence about how a model will behave next month.

When to reach for it

  • Forecasting demand, traffic and prices
  • Any model deployed forward in time (churn, fraud)
  • Choosing retraining windows and cadence

When to avoid or be careful

  • Random splits on time-ordered data
  • Features computed with data from after the forecast origin
  • A single backtest period as the only evidence

Validation schemes for temporal data

Expanding window forward chaining
Best for: Stable processes where more history helps

Strengths: Uses all past data; simple.

Watch out: Old patterns can dominate if the process drifts.

Sliding window walk-forward
Best for: Non-stationary series

Strengths: Adapts to recent behaviour; models retraining cadence.

Watch out: Discards history; shorter training sets.

Random K-fold
Best for: Not suitable for time-ordered data

Strengths: None for forecasting.

Watch out: Leaks future information and overstates accuracy.

Interview signals & numbers to know

When this topic comes up

  • “The model degrades after deployment”
  • TimeSeriesSplit
  • Walk-forward validation
  • Gap and embargo
  • Concept drift

Benchmarks & rules of thumb

n / (n_splits + 1) -
default TimeSeriesSplit test size: 60/6 = 10
6.2 vs 8.1–12.9 -
MAE from a random split versus forward chaining
gap ≥ horizon -
buffer to prevent label and feature overlap

Common mistakes & follow-ups

Common interview mistakes

  • Shuffling a time series before splitting.
  • Using centred rolling windows that include future values.
  • Ignoring that error rising across folds signals drift.

Likely interviewer follow-ups

  • Why can't you use random K-fold for time series?
  • What is a gap in time-series cross-validation?
  • How do you choose between expanding and sliding windows?
Interview tip: Show errors by fold and mention drift. It converts validation from a single number into evidence about how the model ages.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Time-Series Split Validation with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
K-Fold & Stratified Cross-Validation
Next topic
Regression Metrics (MAE, MSE, RMSE, R², MAPE)