smartyfy.mrindigi.com

Python Master Course V2 — 139. Time-Aware Validation and Forecasting Baselines

Purpose and learning outcomes

A forecast predicts a value that has not yet happened. Randomly shuffling historical rows can accidentally train on observations from after the prediction being evaluated. This lesson creates daily demand, constructs only backward-looking features, and compares a lag-based regressor with persistence and weekly-seasonal baselines using rolling one-day-ahead evaluation.

  • Build lag features without future leakage
  • Compare persistence and seasonal baselines
  • Use chronological splits and rolling-origin evaluation

Prerequisites: 078: dates and times; 123: pandas; 133 and 136: regression and evaluation.

Environment and run order

Use a dedicated Python 3.11 or 3.12 virtual environment. These exercises use local synthetic or bundled data; no account, API key, or dataset download is needed. The shell commands install free packages. Run the Python blocks in order in one lesson file; worked solutions continue from that file unless stated otherwise.

Shell

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy pandas scikit-learn matplotlib joblib
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Define the forecast origin and horizon

The origin is the time when the prediction is issued; the horizon is how far ahead it predicts. Here, at the end of day t-1, all demand through that day is known and we predict day t. During a held-out block, yesterday’s realized value becomes available before the next prediction. This is rolling one-step-ahead evaluation, not a single forecast of an entire unseen month issued at its beginning.

Build features that could really exist

shift(1) places yesterday’s observation beside today’s target, and shift(7) supplies the previous week’s value. A rolling mean must first shift the series; rolling over unshifted data includes today’s target and leaks it directly. Rows at the beginning lack sufficient history and are dropped. The date itself may be known in advance, but a same-day outcome is not. Carefully distinguish known future calendar features from future measurements.

Start with strong simple baselines

Persistence predicts yesterday’s value. A seasonal baseline predicts the same weekday last week. They cost almost nothing to fit and often capture substantial temporal structure. A complex model must improve on relevant baselines under the same forecast origin and information availability. Comparing a regression model with future lags against a baseline without them is not a fair experiment.

Chronology changes cross-validation

TimeSeriesSplit creates expanding training windows followed by later validation windows. Our lag features use only historical values and our one-day target has no overlapping future label window, so no gap is needed here. Longer horizons, delayed labels, or overlapping target intervals may require a gap or purging. The exact gap should follow information timing rather than be copied blindly from a tutorial.

Incremental worked example

1. Generate demand and backward-looking predictors

The weekly component and slow trend make both seasonal and trend behavior visible. Noise means that exact daily demand is not predictable. The first seven rows are excluded because all lagged features must be available.

Python

import numpy as np
import pandas as pd
from sklearn.model_selection import TimeSeriesSplit
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error

rng = np.random.default_rng(39)
day = np.arange(320)
demand = pd.Series(80 + 0.08 * day + 12 * np.sin(2 * np.pi * day / 7)
                   + rng.normal(0, 3, len(day)),
                   index=pd.date_range("2025-01-01", periods=len(day), freq="D"))
table = pd.DataFrame({"target": demand, "lag1": demand.shift(1),
    "lag7": demand.shift(7), "mean7": demand.shift(1).rolling(7).mean()}).dropna()
features = ["lag1", "lag7", "mean7"]
development, test = table.iloc[:-60], table.iloc[-60:]
assert development.index.max() < test.index.min()
cv = TimeSeriesSplit(n_splits=3, test_size=30)
fold_mae = []

2. Run rolling-origin comparisons and a final block

Within each validation block we use actual previous-day demand as it becomes known. The regression model remains fixed during that block. Fold scaling is fitted only on earlier training rows. The final test block is evaluated once with the prespecified ridge configuration.

Python

for fold, (train_ids, valid_ids) in enumerate(cv.split(development), start=1):
    train = development.iloc[train_ids]
    valid = development.iloc[valid_ids]
    assert train.index.max() < valid.index.min()
    model = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
    model.fit(train[features], train["target"])
    predictions = model.predict(valid[features])
    value = mean_absolute_error(valid["target"], predictions)
    fold_mae.append(value)
    print(fold, "ridge", value, "persistence",
          mean_absolute_error(valid["target"], valid["lag1"]), "seasonal",
          mean_absolute_error(valid["target"], valid["lag7"]))
final = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
final.fit(development[features], development["target"])
print("test ridge MAE", mean_absolute_error(test["target"], final.predict(test[features])))
print("test seasonal MAE", mean_absolute_error(test["target"], test["lag7"]))
print("test persistence MAE", mean_absolute_error(test["target"], test["lag1"]))

Expected output / interpretation

Three chronological validation comparisons and one final 60-day comparison are printed.
All errors are in the synthetic demand units.
Results evaluate rolling one-day-ahead prediction with observed historical lags, not 60-step forecasting.

Guided lab and acceptance criteria

  1. For one row in the first validation block, list the exact calendar dates supplying lag1, lag7, and mean7. Verify that none is the target date or later. This manual audit catches off-by-one leakage more reliably than a high score.
  2. Plot actual and predicted demand over the final validation block before opening test. Add the seasonal baseline. Label the forecast horizon and avoid visually aligning a prediction with the day its features were recorded instead of the day it predicts.
  3. Compare fold errors in chronological order. Discuss whether trend, noise, or a changing relationship makes later folds harder. Do not treat their average as evidence that performance will remain constant indefinitely.
  4. Deliver a forecasting protocol with issue time, horizon, label delay, retraining schedule, and baseline definitions. Passing work explicitly states that tomorrow’s forecast can use today’s observed demand, while a month-ahead forecast issued today cannot use future realized lags.

Common mistakes and repairs

  • Applying rolling(7).mean directly to the target and predicting that same row: shift first so the feature excludes the value being predicted.
  • Randomly shuffling a time series for a future-prediction claim: preserve chronology and address repeated entities or overlapping windows too.
  • Calling the entire held-out block a multi-step forecast: distinguish rolling one-step prediction from recursively forecasting several unobserved steps.

Questions that test understanding

Why is a lag inside the test block allowed here?

At each new daily origin, the previous day has already happened and its value is assumed observed. Using it matches the declared rolling one-step deployment. It would be invalid if all 60 predictions had to be issued before the block began or if observations arrived with a longer delay.

Does TimeSeriesSplit prevent every kind of leakage?

No. It enforces an index ordering, but cannot inspect whether a feature secretly contains future data, whether labels arrive late, or whether observations are irregularly spaced. Feature construction, time stamps, and the forecast contract still require explicit audits.

When would a gap be necessary?

A gap can help when the training target spans future dates that overlap validation, or when labels would not yet be available at the forecast origin. Its size depends on horizon and data latency. An arbitrary gap is neither universally necessary nor sufficient.

Why keep a seasonal naive baseline?

A repeating weekly process can be predicted surprisingly well using last week’s same-day observation. It tests whether additional complexity captures more than obvious seasonality. It also remains understandable and inexpensive, making it a meaningful operational reference.

What changes for a seven-day forecast issued today?

Future lag1 values are unavailable. You must use only features known at today’s origin, fit horizon-specific direct models, or feed previous predictions recursively while accounting for error accumulation. Reusing the one-step table with actual future lags would overstate performance.

Why might fold scores drift over time?

The data distribution or relationship may change, or a fixed model may lag behind a trend. Even without drift, finite samples differ. Report dates and conditions beside each score and consider a justified retraining policy rather than assuming all historical folds are interchangeable.

Exercises with worked solutions

Exercise 1: Verify the first lag by timestamp

Reveal the worked solution and reasoning

The first usable row comes after seven historical observations. Looking up its preceding calendar day verifies the alignment directly rather than trusting a shift call by inspection.

Python

first_date = table.index[0]
assert np.isclose(table.loc[first_date, "lag1"],
                  demand.loc[first_date - pd.Timedelta(days=1)])
assert np.isclose(table.loc[first_date, "lag7"],
                  demand.loc[first_date - pd.Timedelta(days=7)])
print("lag alignment checked")

Exercise 2: Repair a future-centered rolling mean

Reveal the worked solution and reasoning

A centered window can include future observations. Replace it with demand.shift(1).rolling(7).mean for the stated one-day forecast. If the requirement changes to a seven-day horizon, recompute features relative to each issue date and redesign targets; a cosmetic rename of the column does not repair information timing.

Recap and next step

Forecast validity comes from the information available at the prediction origin. Backward-looking features, chronological evaluation, and strong naive baselines make that assumption visible. The applied ML capstone now combines these habits into a local predictor with a checked interface, a model card, and a trustworthy saved artifact.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.