Sub topic 3
Measuring forecast error
This chapter assumes you know Python, NumPy and pandas basics, and what a regression loss is. Every later chapter judges a model by the numbers defined here, so the choice of metric shapes which model "wins". You will learn four metrics, what each one rewards, where each one breaks, and how to code them correctly for time series.
Why the metric choice matters
A forecast error is the actual value minus the forecast, e_t = y_t - ŷ_t. A metric collapses many errors into one number. Different collapses answer different questions:
- How far off are we in the units of the data?
- Do large misses matter much more than small ones?
- Can we compare across series with different scales?
- Did we beat a trivial method?
No single metric answers all four. Pick the one that matches the cost of being wrong in your application, and report a second one as a cross-check.
MAE: mean absolute error
MAE averages the absolute errors:
MAE = mean(|y_t - ŷ_t|)
It is in the units of the data. An MAE of 12 on daily unit sales means the forecast is off by 12 units on a typical day. Every unit of error counts the same, so one large miss does not dominate.
MAE is minimized by predicting the conditional median. This matters when you train a model. HistGradientBoostingRegressor(loss="absolute_error") optimizes a median-targeting loss, so it matches MAE evaluation directly.
RMSE: root mean squared error
RMSE squares the errors, averages them, then takes the square root:
RMSE = sqrt(mean((y_t - ŷ_t)^2))
Squaring makes large errors count much more. Two errors of 5 give an RMSE of 5. One error of 10 and one of 0 give an RMSE of about 7.07, though both cases have an MAE of 5. RMSE is always at least as large as MAE. A big gap between them signals a few large misses.
RMSE is minimized by predicting the conditional mean, which is what the default squared-error loss in gradient boosting targets. Choose RMSE when large misses are disproportionately costly, such as running out of stock on a spike.
MAPE: mean absolute percentage error
MAPE divides each error by the actual value:
MAPE = mean(|y_t - ŷ_t| / |y_t|) * 100
A percentage is easy to explain to non-specialists, and it looks scale-free. It has three known problems:
- Undefined at zero. If any
y_tis 0, the term divides by zero. Many retail and energy series contain zeros. - Explodes near zero. Small actuals inflate the percentage, so a few low-volume points dominate the average.
- Asymmetric. Over-forecasting is penalized more than under-forecasting. If the actual is 100 and you forecast 150, the error is 50%. If the actual is 150 and you forecast 100, the error is 33%. An under-forecast can never exceed 100%, while an over-forecast has no cap. Minimizing MAPE therefore pushes models to forecast low.
Use MAPE only when the series is strictly positive and well away from zero.
MASE: mean absolute scaled error
MASE divides your MAE by the MAE of a naive forecast on the training data:
MASE = MAE_test / mean(|y_t - y_{t-m}|) where the denominator is computed over the training set.
The period m sets the naive method. Use m = 1 for "repeat the last value". Use m = 7 for daily data with a weekly pattern, where the naive forecast repeats the value from a week earlier.
Interpretation is direct:
- MASE below 1 means your model's errors are smaller than the naive method's in-sample errors.
- MASE above 1 means they are larger.
Because the scale comes from the series itself, MASE is comparable across series of different magnitudes, and it is defined when the series contains zeros. The next chapter builds these naive baselines as forecasters. Here you only need their in-sample errors as a scale.
The denominator must come from the training data only. Computing it from the test period uses information the model never had.
Comparing the metrics
| Metric | Units | Penalizes large errors | Safe with zeros | Comparable across series |
|---|---|---|---|---|
| MAE | Data units | Linearly | Yes | No |
| RMSE | Data units | Quadratically | Yes | No |
| MAPE | Percent | Linearly, but biased against over-forecasts | No | Yes, with caveats |
| MASE | Ratio to naive | Linearly | Yes | Yes |
Implementing the metrics
The functions below use NumPy only, so you can see exactly what each metric computes. The example uses small numbers that you can check by hand.
import numpy as np
def mae(y_true, y_pred):
y_true, y_pred = np.asarray(y_true, float), np.asarray(y_pred, float)
return float(np.mean(np.abs(y_true - y_pred)))
def rmse(y_true, y_pred):
y_true, y_pred = np.asarray(y_true, float), np.asarray(y_pred, float)
return float(np.sqrt(np.mean((y_true - y_pred) ** 2)))
def mape(y_true, y_pred):
y_true, y_pred = np.asarray(y_true, float), np.asarray(y_pred, float)
if np.any(y_true == 0):
raise ValueError("MAPE is undefined when y_true contains zeros")
return float(np.mean(np.abs((y_true - y_pred) / y_true)) * 100)
def mase(y_true, y_pred, y_train, m=1):
y_train = np.asarray(y_train, float)
if len(y_train) <= m:
raise ValueError("y_train must be longer than the period m")
scale = np.mean(np.abs(y_train[m:] - y_train[:-m]))
if scale == 0:
raise ValueError("Training series is constant, so MASE is undefined")
return mae(y_true, y_pred) / float(scale)
train = [10, 12, 11, 13, 12, 14, 13, 15]
actual = [14, 16, 15]
forecast = [13, 17, 12]
print("MAE ", round(mae(actual, forecast), 2))
print("RMSE", round(rmse(actual, forecast), 2))
print("MAPE", round(mape(actual, forecast), 1), "%")
print("MASE", round(mase(actual, forecast, train, m=1), 2))The output is MAE 1.67, RMSE 1.91, MAPE 11.1 % and MASE 1.06. The errors are 1, -1 and 3. The single error of 3 pulls RMSE above MAE. The naive in-sample MAE on the training data is about 1.57, so the model is slightly worse than naive on this tiny test set.
Scikit-learn has mean_absolute_error, root_mean_squared_error (version 1.4 and later) and mean_absolute_percentage_error. The last one returns a fraction, not a percent, and replaces zeros in the denominator with a tiny constant instead of raising an error. That produces enormous values rather than a warning. Scikit-learn has no MASE, so you write it yourself as above.
Edge cases and common errors
- Scoring on the wrong rows. Compute metrics on the test rows only. Scoring on training rows hides overfitting.
- Leaky MASE scale. Take the denominator from training data. In walk-forward validation, recompute it for each fold from that fold's training window.
- Dropped NaN rows. Lag features create missing values at the start of the series. After
dropna(), the first test rows may start later than the naive baseline expects. Make sure the model and the baseline are scored on exactly the same rows. - Averaging across series. To summarize many series, compute MASE per series, then average. Pooling raw MAE across series lets the largest series dominate.
- One number hides the horizon. Error usually grows with the forecast horizon. When you forecast several steps ahead, report the metric per horizon step as well as overall.
- Intermittent series. If most values are zero, MAE can look excellent for a forecast of all zeros. Check the forecast against business needs, not only the number.
- Short test sets. A metric from 10 test points is noisy. Later chapters use walk-forward validation to get several scores instead of one.
Exercise
You forecast daily sales with a weekly pattern and compute MASE with m=7 on a test set. The result is 0.8. What does it mean, and what would change if you used m=1 for the scale instead?
Show answer
A MASE of 0.8 means the model's mean absolute error on the test set is 80% of the in-sample mean absolute error of the seasonal-naive method, which predicts each day from the same day one week earlier. The model is about 20% better than that baseline. With m=1, the scale is the in-sample error of "repeat yesterday". On data with strong weekly seasonality that scale is usually larger, because yesterday is a poorer predictor than last week. The same test MAE would then give a lower MASE, making the model look better. MASE values are comparable only when they use the same m.
Exercise
Actual values are [100, 200] and the forecasts are [150, 150]. Compute MAE, RMSE and MAPE by hand. Then swap them: actual [150, 150] and forecast [100, 200]. Which metrics change?
Show answer
First case: errors are -50 and 50. MAE = 50, RMSE = 50. MAPE = mean(50/100, 50/200) = mean(0.5, 0.25) = 37.5%. Second case: the errors are again 50 and -50, so MAE = 50 and RMSE = 50, unchanged. MAPE = mean(50/150, 50/150) = 33.3%. Only MAPE changes, because it divides by the actual value, which shows its asymmetry.