Sub topic 11
Related metrics: median absolute error and MAPE
This chapter covers two metrics that sit next to MAE and RMSE: median absolute error and mean absolute percentage error (MAPE). It assumes you can already compute residuals, MAE, and RMSE, and that you know the difference between a training set and a held-out test set. Basic NumPy and scikit-learn use is also assumed.
Why look beyond MAE, RMSE, and R squared
MAE, RMSE, and R squared answer most evaluation questions. Two situations they handle poorly:
- A handful of extreme errors dominates the summary, and you want to know how the model behaves on a typical row.
- The target spans several orders of magnitude, and a miss of 50 units is trivial for a value of 10,000 but severe for a value of 100.
Median absolute error addresses the first. MAPE addresses the second. Each solves its problem by changing what the metric treats as "typical" or "large", and each brings its own failure modes.
Median absolute error
Median absolute error (MedAE) takes the absolute residuals and returns their median instead of their mean:
MedAE = median(|ytrue - ypred|)
It has the same units as the target, like MAE. Its interpretation is direct: half of the predictions are off by no more than this amount, and half are off by at least this amount.
The median ignores how large the biggest errors are. Changing the worst residual from 60 to 6000 does not move the median at all, while it moves MAE and RMSE a lot.
A worked comparison
The next script uses six rows. Five predictions are off by 1, and one is off by 60.
import numpy as np
from sklearn.metrics import (
mean_absolute_error,
mean_absolute_percentage_error,
mean_squared_error,
median_absolute_error,
)
y_true = np.array([10.0, 12.0, 11.0, 13.0, 12.0, 100.0])
y_pred = np.array([11.0, 11.0, 12.0, 12.0, 13.0, 40.0])
mae = mean_absolute_error(y_true, y_pred)
rmse = np.sqrt(mean_squared_error(y_true, y_pred))
medae = median_absolute_error(y_true, y_pred)
mape = mean_absolute_percentage_error(y_true, y_pred)
print(f"MAE={mae:.4f} RMSE={rmse:.4f} MedAE={medae:.4f} MAPE={mape:.4f}")
# MAE=10.8333 RMSE=24.5119 MedAE=1.0000 MAPE=0.1724The absolute errors are 1, 1, 1, 1, 1, and 60. MAE is 65 / 6, about 10.83. RMSE is about 24.51 because the single miss of 60 contributes 3600 to the sum of squares. MedAE is exactly 1.0, because the middle two sorted errors are both 1.
Which number is right depends on the question. MedAE says the model is usually accurate. MAE and RMSE say the model sometimes fails badly. Both statements are true, and a report that includes only one of them is incomplete.
What MedAE hides
The robustness of the median is also its main risk. MedAE is blind to the worst half of the errors. A model that is off by 1 on 51 percent of rows and off by 10,000 on the other 49 percent has a MedAE of 1. If large misses are expensive, MedAE alone can make a dangerous model look excellent.
For this reason, report MedAE next to MAE or RMSE and not in place of them. A large gap between MedAE and MAE signals a heavy tail of big errors, and the gap itself is informative.
Practical notes
median_absolute_erroris insklearn.metrics. Its arguments are(y_true, y_pred), in that order, like the other metrics.- It is an evaluation metric. You can use it with
cross_val_scorethrough the scorer name"neg_median_absolute_error". scikit-learn scorers follow the "greater is better" convention, so the score is the negated error. - For multi-output targets, the default is to compute the median per output and average the results across outputs.
- The mean-versus-median distinction also appears in training. Minimizing squared error targets the conditional mean. Minimizing absolute error targets the conditional median. A model trained on absolute loss is therefore already aimed at the quantity MedAE measures.
Mean absolute percentage error (MAPE)
MAPE measures each error relative to the true value, then averages:
MAPE = mean(|ytrue - ypred| / |y_true|)
It is unitless, so you can compare a model of house prices in dollars with a model of electricity demand in megawatts. It also matches how many stakeholders speak: "the forecast is typically about 17 percent off."
Check the arithmetic on the six-row example. The percentage errors are 0.100, 0.083, 0.091, 0.077, 0.083, and 0.600. Their mean is about 0.1724.
The fraction versus percent trap
scikit-learn returns MAPE as a fraction, not a percentage. The value 0.1724 means 17.24 percent. Multiply by 100 yourself before printing "%". Reports that show "MAPE = 0.17%" when the real figure is 17% come from forgetting this.
Failure mode 1: zeros and near-zeros in the target
MAPE divides by the true value. When a true value is zero, the ratio is undefined. When it is near zero, the ratio explodes and one row can dominate the average.
scikit-learn does not raise an error for zeros. It replaces the denominator with a tiny constant, the floating-point epsilon of about 2.2e-16. The output is a number that looks valid but is astronomically large.
import numpy as np
from sklearn.metrics import mean_absolute_percentage_error
y_true = np.array([0.0, 10.0])
y_pred = np.array([1.0, 10.0])
print(f"{mean_absolute_percentage_error(y_true, y_pred):.3e}")
# Around 2.3e+15, driven entirely by the row where y_true is 0.Whenever your data can contain zeros, such as intermittent demand, counts, or temperatures in Celsius, MAPE is the wrong default. Temperatures also show a subtler problem: a percentage of a value measured on an arbitrary zero point has no meaning.
Failure mode 2: asymmetry
MAPE does not treat over-prediction and under-prediction equally, because the denominator is the true value.
| True value | Prediction | Absolute error | Percentage error |
|---|---|---|---|
| 100 | 50 | 50 | 50% |
| 50 | 100 | 50 | 100% |
The absolute error is identical, but the second row is penalized twice as heavily. Under-prediction of a non-negative target is capped at 100 percent, since the prediction cannot go below zero. Over-prediction has no cap.
A model trained or tuned to minimize MAPE therefore tends to be pulled toward predicting low. If that bias matters, for example in inventory planning where under-forecasting causes stockouts, MAPE can steer you toward the wrong model.
Failure mode 3: small actuals dominate
Even without zeros, rows with small true values produce large percentage errors for modest absolute misses. In the six-row example, the single row with true value 100 contributes 0.6 to the sum of 1.03, so it is the largest term, but only because its absolute miss is 60. On a dataset where most values are in the thousands and a few are near 5, those few rows can control the metric.
A common alternative: WAPE
Weighted absolute percentage error (WAPE) divides total absolute error by total absolute actuals:
WAPE = sum(|ytrue - ypred|) / sum(|y_true|)
It is MAE divided by the mean of the absolute actuals. Large-valued rows get proportionally more weight, and a single near-zero actual no longer causes a blowup unless the whole target sums near zero. On the six-row example it is 65 / 158, about 0.411. scikit-learn has no built-in function for it, but it is one line of NumPy.
import numpy as np
y_true = np.array([10.0, 12.0, 11.0, 13.0, 12.0, 100.0])
y_pred = np.array([11.0, 11.0, 12.0, 12.0, 13.0, 40.0])
wape = np.sum(np.abs(y_true - y_pred)) / np.sum(np.abs(y_true))
print(f"WAPE={wape:.4f}") # WAPE=0.4114Note how different the two percentage summaries are on identical data: MAPE is 0.17 and WAPE is 0.41. The mean of per-row ratios and the ratio of totals answer different questions. State which one you used.
Comparing the metrics
| Metric | Units | Reaction to one huge error | Needs nonzero targets | Main use |
|---|---|---|---|---|
| MAE | Target units | Linear increase | No | Average cost of a miss |
| RMSE | Target units | Strong increase (squared) | No | Large misses are disproportionately costly |
| MedAE | Target units | None, until it affects half the rows | No | Typical-row accuracy, outlier-resistant |
| MAPE | Fraction (unitless) | Depends on the true value's size | Yes | Comparing across scales, communicating relative error |
| R squared | Unitless | Strong increase (squared) | No | Improvement over the mean baseline |
Choosing between them
A reporting pattern that works well in practice:
- Pick one primary metric tied to the cost of errors, usually MAE or RMSE.
- Add MedAE if you suspect a heavy tail, and read the gap between it and MAE.
- Add MAPE or WAPE only if the target is strictly positive and relative error is meaningful to the audience.
- Always compute everything on held-out data, as covered earlier in this tutorial.
Common errors
- Reading scikit-learn's MAPE as a percentage. It is a fraction.
- Computing MAPE on data with zeros and trusting the result. Check
(y_true == 0).any()first. - Reporting MedAE alone. It can hide a large class of bad predictions.
- Comparing MAPE across datasets with different value ranges and assuming the figures are equally meaningful. A 5 percent MAPE on values near 5 and on values near 5000 reflect very different absolute misses.
- Swapping argument order. For MAPE the order matters, because
y_trueis the denominator. Swappingy_trueandy_predsilently changes the answer.
Exercises
Exercise
A model has absolute errors [2, 3, 3, 4, 90]. Compute the MAE and the MedAE, and say what the gap between them indicates.
Show answer
MAE = (2 + 3 + 3 + 4 + 90) / 5 = 102 / 5 = 20.4. MedAE is the middle value of the sorted errors, which is 3. The large gap shows that one extreme error pulls the mean up while most predictions are close. A typical row is off by about 3, but a rare failure of 90 exists and should be investigated.
Exercise
You are forecasting daily sales of a product, and some days have zero sales. A colleague proposes MAPE as the headline metric. Give two reasons it is a poor choice and name one replacement.
Show answer
First, MAPE divides by the true value, so zero-sales days make the ratio undefined, and scikit-learn substitutes a tiny epsilon that produces an enormous, meaningless value. Second, MAPE penalizes over-prediction more than under-prediction, which biases model selection toward low forecasts. Replacements include MAE, or WAPE (total absolute error divided by total actual sales), which stays finite as long as total sales are nonzero.
Exercise
scikit-learn returns 0.08 from meanabsolutepercentage_error. What should the report say, and what does the number tell you about the typical size of the miss?
Show answer
The report should say MAPE is 8 percent, because the function returns a fraction and you multiply by 100. On average, predictions are off by 8 percent of the true value. This is a mean of per-row ratios, so a few rows with small true values can contribute disproportionately.