PeaBox Lab › PeaLang › Learn › Chapter 18 › Lesson 4

Part III — Advanced Systems · Chapter 18 · Lesson 4 of 7 · 7 min read

Lesson 4: Train/Test Splits and Error Metrics

Lesson level: Advanced

Purpose: Evaluate forecasts the way they will be used — predicting a future the method has not seen — and choose error metrics that reflect the cost of being wrong.

Learning objectives

By the end of this lesson you will be able to:

4.1 Why random splits fail

In ordinary machine learning, rows are shuffled and split at random. For time series this is wrong. A random split lets the model train on Wednesday and Friday and then "predict" Thursday, which it can interpolate from its neighbours. In production it will never see Friday before predicting Thursday. Random splits therefore overstate accuracy, sometimes dramatically.

The rule is simple: everything used to produce a forecast must be available at the moment the forecast would have been made. That covers training rows, features, window statistics, scaling parameters, and even data-quality fixes that relied on later information.

4.2 Chronological holdout

The simplest valid split chooses a cut-off date. Rows on or before the cut-off are training data; rows after it are test data. The test period should be at least as long as the forecast horizon and should include the seasonal patterns that matter, such as a full week for daily data.

Illustrative listing.

from datetime import date, timedelta

cutoff = date(2026, 6, 30)
horizon_days = 28

train = series.filter(col("date") <= cutoff)
test  = series.filter((col("date") > cutoff) &
                      (col("date") <= cutoff + timedelta(days=horizon_days)))

assert train.column("date").max() < test.column("date").min()

Fit any feature scaling, imputation, or seasonal index on the training rows only, then apply it to the test rows. Computing a seasonal index on the full dataset and then splitting is a subtle and common leak.

4.3 Rolling-origin backtesting

One cut-off gives one test result, which may be lucky or unlucky. A rolling-origin or walk-forward backtest repeats the process with several cut-offs: train up to origin 1 and forecast the next h periods, then move the origin forward and repeat. Averaging across origins gives a much more reliable estimate.

def backtest(series, fit, predict, origins, horizon):
    rows = []
    for origin in origins:
        train = series.filter(col("date") <= origin)
        actual = series.filter((col("date") > origin) &
                               (col("date") <= origin + timedelta(days=horizon)))
        model = fit(train)
        forecast = predict(model, actual.column("date"))
        rows.append(actual.with_columns(origin=origin, forecast=forecast))
    return concat(rows)

Two design choices matter. An expanding training window uses all history up to each origin; a sliding window uses only the most recent fixed span. Expanding windows suit stable processes; sliding windows suit processes whose behaviour drifts. Space the origins so that test windows cover different seasons, and keep the number small enough to run routinely.

4.4 Horizon matters

The horizon is how far ahead a forecast looks. A forecast made on Monday for Tuesday (horizon 1) is easier than one for next month (horizon 30). Report error by horizon, not just one average, because users rely on different horizons for different decisions: tomorrow's staffing, next month's purchasing, next quarter's budget.

Every feature must also respect the horizon. A lag 1 feature is available for a horizon 1 forecast but not for horizon 7: when forecasting seven days ahead, yesterday's value relative to the target date has not happened yet. Either build separate features per horizon, or use only lags at least as long as the horizon.

4.5 Error metrics

Let y be the actual value, ŷ the forecast, e = y − ŷ the error, and n the number of evaluated points.

MetricDefinitionStrengthsWeaknesses
MAEmean of |e|Same units as the data; easy to explainNot comparable across series of different scale
RMSEsquare root of mean of e²Penalizes large errors heavilyDominated by a few big misses; scale-dependent
MAPEmean of |e / y| × 100Percentage; intuitiveUndefined at y = 0; explodes near zero; penalizes over-forecasts more
sMAPEmean of 2|e| / (|y| + |ŷ|) × 100Bounded; handles some zerosStill unstable when both are near zero; not truly symmetric
MASEMAE divided by the in-sample MAE of a seasonal naive forecastScale-free; works with zeros; below 1 beats the naive baselineLess familiar to business users
Biasmean of e (or sum of e / sum of y)Shows systematic over- or under-forecastingPositive and negative errors cancel; use alongside an absolute metric

Illustrative listing.

def metrics(df, naive_mae):
    e = df.col("actual") - df.col("forecast")
    nonzero = df.filter(col("actual") != 0)
    return {
        "mae":  e.abs().mean(),
        "rmse": (e ** 2).mean() ** 0.5,
        "mape": ((nonzero.col("actual") - nonzero.col("forecast")).abs()
                 / nonzero.col("actual").abs()).mean() * 100,
        "mase": e.abs().mean() / naive_mae,
        "bias": e.sum() / df.col("actual").sum(),
        "n": df.height, "mape_n": nonzero.height,
    }

Note that the MAPE calculation drops zero actuals and reports how many points remain. Silently dropping zeros makes MAPE look better than reality for intermittent series; always publish the count.

4.6 Choosing metrics from business cost

A metric is a statement about what errors cost. Ask the business owner, then choose:

Report at least one absolute measure, one relative or scaled measure, and bias. Aggregate by summing errors and actuals across items before dividing, rather than averaging per-item percentages, so that small, volatile items do not dominate the headline number.

4.7 Annotated example: a misleading accuracy claim

A team reports "92% forecast accuracy" for a new demand model. Review uncovers four problems, each of which inflated the figure:

Re-evaluated with a rolling-origin backtest, a training-only seasonal index, WAPE aggregated across products, and MASE against a seasonal naive baseline, the model's error was 31% WAPE and its MASE was 0.94 — only slightly better than repeating last week. The honest result is less exciting, but it is the one the business can plan with, and it shows exactly how much room the next model must improve.

Common mistakes

Guided practice

Hands-on lab: A reusable backtesting harness

Review questions

Applied challenge

A procurement team orders stock weekly with a two-week lead time. Spoiled stock costs three times as much per unit as a lost sale. Design an evaluation protocol for their demand forecasts: the horizon to evaluate, the backtest origins, the metrics (including how you reflect the asymmetric cost), and the report format. Apply it to two candidate forecasts and recommend one.

Lesson summary

Evaluate forecasts as they will be used: chronological splits, preprocessing fitted on training data only, features available at the horizon, and several backtest origins. Choose metrics from business cost, combine an absolute measure, a scaled measure, and bias, aggregate before dividing, and always publish point counts and exclusions.

Transition to Lesson 5

An evaluation harness needs something to evaluate. Lesson 5 builds the baseline forecasts — naive, trend, moving average, and exponential smoothing — that every more sophisticated model must beat.

Lesson status: Ready for review.

← Previous Next →