Sub topic 2
MAE: the average size of the error
This chapter assumes you can read basic NumPy code, know what a mean is, and have a rough idea that a regression model predicts a number. It also assumes you know that a model is scored on a test split it did not train on. Here you learn the first and simplest regression metric, Mean Absolute Error (MAE). You will compute it by hand, with NumPy, and with scikit-learn. You will also learn what it measures, what it hides, and where people misuse it.
What MAE measures
A residual is the difference between a prediction and the true value for one example. In this tutorial a residual is prediction - truth. A positive residual means the model overshot. A negative residual means it undershot.
MAE answers one question: on average, how far off is the model, ignoring direction? It takes the absolute value of each residual, which drops the sign. Then it averages those sizes.
MAE = (1/n) * sum(|y_pred_i - y_true_i|)The result has the same units as the target. If you predict house prices in dollars and the MAE is 18,000, the model is off by about 18,000 dollars per house on average. If you predict delivery time in minutes, an MAE of 4.2 means 4.2 minutes. That unit match is the main reason MAE is easy to explain to people who do not work with models.
Computing MAE by hand
Use four examples where the model predicts a numeric target.
| Example | True value | Prediction | Residual | Absolute error |
|---|---|---|---|---|
| 1 | 3.0 | 2.5 | -0.5 | 0.5 |
| 2 | 5.0 | 5.0 | 0.0 | 0.0 |
| 3 | 2.5 | 4.0 | 1.5 | 1.5 |
| 4 | 7.0 | 8.0 | 1.0 | 1.0 |
The absolute errors sum to 0.5 + 0.0 + 1.5 + 1.0 = 3.0. Divide by 4 examples and you get an MAE of 0.75. The model is off by 0.75 target units on a typical example.
The same calculation in NumPy:
import numpy as np
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
residuals = y_pred - y_true # [-0.5, 0.0, 1.5, 1.0]
abs_errors = np.abs(residuals) # [0.5, 0.0, 1.5, 1.0]
mae = np.mean(abs_errors)
print(residuals)
print(abs_errors)
print(mae) # 0.75Because np.abs of a difference is the same in either direction, |pred - true| equals |true - pred|. The order of the two arguments does not change MAE. That is not true of every metric you will meet, so do not build a habit of ignoring argument order.
Why the absolute value matters
Without the absolute value, positive and negative residuals cancel. The plain average of the residuals is called the mean error, or bias. It tells you whether the model tends to overshoot or undershoot. It does not tell you how large the misses are.
For the four examples above, the residuals [-0.5, 0.0, 1.5, 1.0] average to 0.5. That says the model leans slightly high. The MAE of 0.75 says the typical miss is larger than that lean.
The difference becomes extreme with a model that is wrong in both directions:
import numpy as np
residuals = np.array([-2.0, 2.0, -2.0, 2.0])
print(np.mean(residuals)) # 0.0, looks perfect
print(np.mean(np.abs(residuals))) # 2.0, every prediction misses by 2A mean error of zero does not mean a good model. It means the over- and under-predictions balance. Always report an error size metric, not only the signed average.
Using scikit-learn
In practice you call mean_absolute_error from sklearn.metrics. It takes the true values first and the predictions second.
from sklearn.metrics import mean_absolute_error
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
print(mean_absolute_error(y_true, y_pred)) # 0.75Two options are worth knowing.
The first is sample_weight. It lets some examples count more than others. The result is a weighted average of the absolute errors, so the weights are divided by their sum. If the last example counts three times as much:
from sklearn.metrics import mean_absolute_error
y_true = [3.0, 5.0, 2.5, 7.0]
y_pred = [2.5, 5.0, 4.0, 8.0]
weighted = mean_absolute_error(y_true, y_pred, sample_weight=[1, 1, 1, 3])
print(weighted) # (0.5 + 0.0 + 1.5 + 3.0) / 6 = 0.8333...The second is multioutput, for models that predict several targets at once. By default scikit-learn averages the per-target MAEs into one number. Pass multioutput="raw_values" to see each target separately.
from sklearn.metrics import mean_absolute_error
y_true = [[0.5, 1], [-1, 1], [7, -6]]
y_pred = [[0.0, 2], [-1, 2], [8, -5]]
print(mean_absolute_error(y_true, y_pred)) # 0.75
print(mean_absolute_error(y_true, y_pred, multioutput="raw_values")) # [0.5 1. ]Averaging across targets only makes sense when the targets share units. If one column is dollars and another is square meters, the averaged number mixes units and means nothing. Use raw_values in that case.
Interpreting an MAE value
An MAE is meaningful only against some reference. A value of 0.75 can be excellent or terrible depending on the target.
Compare it to the spread of the target. If the target ranges from 0 to 1,000, an MAE of 0.75 is tiny. If the target ranges from 2 to 7, as in our example, it is large.
The cleanest reference is a baseline that ignores the inputs entirely. Predict the mean of the true values for every example and compute its MAE. For our four examples the mean is 4.375, and the absolute errors are 1.375, 0.625, 1.875, and 2.625. They sum to 6.5, so the baseline MAE is 1.625.
import numpy as np
from sklearn.metrics import mean_absolute_error
y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
baseline = np.full_like(y_true, y_true.mean())
model_mae = mean_absolute_error(y_true, y_pred)
baseline_mae = mean_absolute_error(y_true, baseline)
print(model_mae) # 0.75
print(baseline_mae) # 1.625
print(model_mae / baseline_mae) # about 0.46The model's errors are about 46 percent as large as the baseline's. That is a statement you can defend. A raw "MAE is 0.75" is not. The next chapters build on this baseline idea.
MAE and the median
MAE has a precise statistical meaning. Suppose you must predict one constant number for every example, with no inputs. The constant that minimizes the MAE is the median of the true values. The constant that minimizes squared error is the mean. This shows that MAE is tied to the median, not the mean.
A small example makes this visible.
import numpy as np
y = np.array([1.0, 2.0, 10.0])
for name, constant in (("mean", y.mean()), ("median", np.median(y))):
mae = np.mean(np.abs(y - constant))
print(name, round(constant, 3), round(mae, 3))
# mean 4.333 3.778
# median 2.0 3.0Predicting the median gives a lower MAE than predicting the mean. The single large value, 10, pulls the mean upward, and the mean then sits far from most of the data. The median ignores how large the outlier is.
This is why MAE is described as more robust to outliers than squared-error metrics. Each error counts in proportion to its size, no more. A miss of 100 counts exactly ten times as much as a miss of 10. A model trained to minimize MAE tends to aim for the conditional median, a typical value, instead of being dragged toward rare extreme cases. The next chapters compare this directly with MSE and RMSE.
Properties and limits
The strengths of MAE:
- It is in the units of the target, so it reads naturally.
- Every unit of error counts the same, so the metric is simple to reason about.
- A few extreme values affect it less than they affect squared-error metrics.
The limits:
- It is scale dependent. An MAE of 20 means nothing without the target's scale. You cannot compare MAE across different targets, or across the same target measured in different units. A model with an MAE of 20,000 dollars and one with an MAE of 20 (thousand dollars) are the same model.
- It does not penalize large misses extra. If one big miss is far more costly than several small ones, such as a stock-out in inventory, MAE understates the problem. It treats one miss of 10 the same as ten misses of 1.
- It hides the shape of the errors. Two models can share an MAE while one has uniform errors and the other has mostly perfect predictions plus a few huge failures. Plot or summarize the residuals as well.
- It is not smooth at zero. The absolute value has a corner at a residual of 0, so its gradient is undefined there. Gradient-based training can handle this with subgradients, and libraries do. Many optimizers still prefer squared error, which has a smooth gradient.
- It does not say whether the model is biased. Pair it with the mean of the signed residuals when direction matters.
Common mistakes
- Computing MAE on training data only. A model can fit its training examples far better than new ones. Compute MAE on a held-out test split, and keep the training MAE only as a diagnostic. A large gap between the two signals overfitting.
- Dropping
abs. Writingnp.mean(y_pred - y_true)computes the mean error, not MAE. The cancellation hides the real error size. - Mismatched lengths or shapes. Passing a
(n, 1)column against a(n,)array can broadcast silently in NumPy and produce an(n, n)matrix of differences. The result is a wrong number with no error. Use.ravel()or checky_true.shape == y_pred.shapefirst. scikit-learn validates shapes for you, which is another reason to prefer it. - Comparing MAE across different targets. An MAE of 3 on temperature in Celsius and an MAE of 3 on population in millions are not comparable. Compare to a baseline on the same target instead.
- Averaging group MAEs without weights. If group A has 10 examples and group B has 10,000, the mean of the two group MAEs is not the overall MAE. Compute MAE on the pooled data, or weight each group by its size.
- Ignoring missing values.
np.meanreturnsnanif any residual isnan. scikit-learn raises an error onnaninput. Decide how to handle missing predictions or targets before scoring. Do not let the metric decide silently.
When MAE is a good choice
Choose MAE as your main metric when:
- Each unit of error costs about the same. A forecast that is 5 minutes late is half as bad as one that is 10 minutes late.
- Your data has occasional extreme targets or noisy labels that you do not want to dominate the score.
- You must explain the number to a non-technical audience in plain units.
Look at a squared-error metric as well when large misses are disproportionately costly. The chapter on choosing and reporting a metric returns to this decision with a full comparison.
Exercise
A model predicts the delivery time in minutes for four orders. The true times are [20, 35, 15, 50]. The predictions are [25, 30, 15, 60]. Compute the residuals (prediction minus truth), the MAE, and the mean error. What does the gap between the MAE and the mean error tell you?
Show answer
The residuals are [5, -5, 0, 10]. The absolute errors are [5, 5, 0, 10], which sum to 20, so MAE = 20 / 4 = 5 minutes. The mean error is (5 - 5 + 0 + 10) / 4 = 2.5 minutes. The mean error is smaller than the MAE because the positive and negative residuals partly cancel. The model's typical miss is 5 minutes, but it leans only 2.5 minutes late on average. The mean error alone would understate how far off individual predictions are.
Exercise
You have the true values y = [2, 4, 6, 100]. Without running code, which constant prediction gives the lower MAE: the mean of y (28) or the median of y (5)? Then give both MAE values.
Show answer
The median, 5, gives the lower MAE. For the median: the absolute errors are |2-5| = 3, |4-5| = 1, |6-5| = 1, and |100-5| = 95, which sum to 100, so MAE = 25. For the mean, 28: the absolute errors are 26, 24, 22, and 72, which sum to 144, so MAE = 36. The median minimizes MAE, and the outlier 100 pulls the mean far from the typical values.
Exercise
Two teams report MAE for their house price models. Team A reports 15,000 and Team B reports 15. Team B's prices are in thousands of dollars. Can you say which model is better? What would you ask for?
Show answer
No. Team B's 15 means 15,000 dollars, so on these numbers the two models have the same MAE. Even then, you cannot say which is better unless both were scored on the same test data. Ask for both teams' MAE on the same held-out test set, in the same units, along with the baseline MAE (predicting the mean price) on that set. Then compare each model's ratio to the baseline.