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:
- explain why random splits are invalid for time series
- create a chronological holdout split with an explicit cut-off
- run rolling-origin (walk-forward) backtests
- define the forecast horizon and evaluate each horizon separately
- compute and interpret MAE, RMSE, MAPE, sMAPE, MASE, and bias
- choose metrics that match business cost and report them honestly
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.
| Metric | Definition | Strengths | Weaknesses |
|---|---|---|---|
| MAE | mean of |e| | Same units as the data; easy to explain | Not comparable across series of different scale |
| RMSE | square root of mean of e² | Penalizes large errors heavily | Dominated by a few big misses; scale-dependent |
| MAPE | mean of |e / y| × 100 | Percentage; intuitive | Undefined at y = 0; explodes near zero; penalizes over-forecasts more |
| sMAPE | mean of 2|e| / (|y| + |ŷ|) × 100 | Bounded; handles some zeros | Still unstable when both are near zero; not truly symmetric |
| MASE | MAE divided by the in-sample MAE of a seasonal naive forecast | Scale-free; works with zeros; below 1 beats the naive baseline | Less familiar to business users |
| Bias | mean of e (or sum of e / sum of y) | Shows systematic over- or under-forecasting | Positive 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:
- When every unit of error costs the same, use MAE.
- When large misses are disproportionately harmful (stock-outs at peak, capacity overload), add RMSE or a high-quantile error.
- When comparing across products or stores of different size, use MASE or a weighted percentage error such as total absolute error divided by total actuals (often called WAPE).
- When over- and under-forecasting have different costs — spoiled stock versus lost sales — report bias and consider asymmetric or quantile loss.
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:
- The data was split at random, so many test days had training days on both sides.
- The seasonal index was computed on the full two years before splitting.
- Accuracy was defined as 100 − MAPE, and the 18% of days with zero demand were dropped without being reported.
- The headline averaged per-product MAPE, so 40 slow-moving items with tiny volumes counted as much as the top sellers.
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
- Random splits: always split chronologically.
- Fitting preprocessing on all data: fit scalers, imputers, and seasonal indices on training rows only.
- Features unavailable at the horizon: lag 1 cannot be used to forecast seven days ahead.
- One cut-off only: use several origins to avoid a lucky or unlucky test window.
- MAPE with zeros: it is undefined; use MASE or WAPE and report excluded points.
- Averaging percentages across items: aggregate errors and actuals first.
- Ignoring bias: an accurate-looking model can still be consistently low.
Guided practice
- Evaluate the same simple model with a random split and a chronological split. Compare MAE and explain the difference.
- Run a rolling-origin backtest with six origins and a 14-day horizon. Plot MAE by horizon day.
- Construct a small dataset where MAPE ranks two forecasts in the opposite order to MAE, and explain why.
Hands-on lab: A reusable backtesting harness
- Write a backtest function that accepts a series, a fit function, a predict function, a list of origins, a horizon, and a window type (expanding or sliding).
- Write a metrics function returning MAE, RMSE, WAPE, MASE, bias, and point counts, both overall and by horizon.
- Add a leakage guard: assert that the latest training date is before the first test date for each origin, and that any fitted preprocessing used only training rows.
- Run the harness on the store panel from Lesson 3 with a placeholder forecast that repeats the last observed value.
- Save the per-origin, per-horizon results as a table; you will reuse it to compare models in Lesson 5.
Review questions
- Why does a random split overstate time-series accuracy?
- What is a rolling-origin backtest, and why is it better than a single holdout?
- When would you choose a sliding training window over an expanding one?
- Why must lag features respect the forecast horizon?
- What does a MASE below 1 mean?
- Why should errors be aggregated before computing a percentage across many items?
- Why report bias alongside an absolute error metric?
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.