Overview
Mean absolute error measures how far predictions are from targets on average, in the units of the target. An error of 10 costs exactly ten times an error of 1, no more. That makes it steady in the presence of outliers: one wildly wrong target shifts the loss but does not take it over. The gradient has the same size for every element, only the sign changes with the direction of the error. A model trained with this loss learns to predict the median of the targets, the value with half the data above and half below.
A short history
Fitting by least absolute deviations is older than least squares. Roger Boscovich used it in the 1750s to combine measurements of the shape of the Earth, and Laplace studied it later that century. It lost ground to least squares because it has no simple closed-form solution. It minimises toward the median, not the mean, which makes it resistant to outliers, and modern optimisers removed the computational obstacle.
How it works
- Compute the error as prediction minus target for each element.
- Take the absolute value of each error.
- Reduce with
reduction: the mean over all elements by default. - In
backward, return for each element, taken as 0 where the error is exactly zero, divided by the element count for the mean.
Watch out for
- The gradient does not shrink as the error does. Near the optimum a fixed learning rate makes predictions oscillate around the target, so the rate must be decayed.
- The loss has a corner at zero error, where the derivative is undefined. The template returns 0 there, which is one valid choice of subgradient.
- It predicts the median, not the mean. If you need totals or averages to add up, such as forecast revenue, the result will be biased for skewed data.
- Large errors get no extra attention. If big misses are much worse than small ones in your application, this loss understates them.
Use cases
When to use it
Regression where outliers or heavy-tailed noise are present and you want the typical case predicted well, or where the loss should be readable in the target's own units.
In industry
- Retail forecasting
- Demand forecasts are often trained and reported in absolute error because it is in the same units as the product and is not dominated by a few unusual days.
- Property valuation
- Automated house price models are judged on absolute error, where a few luxury properties would otherwise dominate a squared error measure.
- Image restoration
- Super-resolution and denoising networks are commonly trained with a per-pixel L1 loss, which gives sharper results than squared error.
Choosing it: what must hold
- A regression target where the median is the right thing to predict.
- Outliers or heavy tails that you do not want to dominate training.
- Tolerance for a gradient of constant size, which can make the last steps of training less precise without a decaying learning rate.
When to choose something else
| If | Use instead |
|---|---|
| Large errors are much worse than small ones and the data has few outliers | Mean squared error |
| You want smooth behaviour near zero and robustness to outliers | Huber loss |
| The target has several plausible values for one input | Mixture density loss |
Math foundations
The loss
The average size of the error. It is also called the L1 loss, because it is the L1 norm of the error vector divided by .
The subgradient
Every element pushes with the same strength, , in the direction that reduces its own error. The size of the error does not enter.
The best constant prediction is the median
The subgradient with respect to is the count of targets below minus the count above. It is zero when the two counts are equal, which is the median.
The noise model behind it
The negative log-likelihood of a Laplace distribution with scale . Minimising absolute error is maximum likelihood under Laplace noise, which has heavier tails than Gaussian noise.
Symbols
- the prediction for element i,
pred - the target for element i,
target - the number of elements
- the mean absolute error
- +1 for positive, -1 for negative, 0 at zero
- a constant prediction used for every example
- the scale of the Laplace distribution
Worked by hand
Predictions against targets .
The loss is 1.6667. The elements with errors of 1 and 4 receive gradients of the same size, which is the source of the robustness.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import MAELoss
from config import MAELossConfig
loss = MAELoss(MAELossConfig(reduction="mean"))
pred, target = np.array([1.0, 2.0, 3.0]), np.array([1.0, 4.0, 0.0])
print(loss.forward(pred, target)) # 1.6667
print(loss.backward(pred, target)) # [0.0, -0.3333, 0.3333]Read the implementation (56 lines)
"""Mean absolute error: loss = mean(|pred - target|).
NumPy only. `forward` returns the loss, `backward` its (sub)gradient with respect to the prediction.
"""
from __future__ import annotations
import numpy as np
try:
from .config import MAELossConfig
except ImportError: # run from the template's own folder
from config import MAELossConfig
def _pair(pred, target) -> tuple[np.ndarray, np.ndarray]:
"""Both inputs as float arrays of one shape. Raises ValueError when the shapes differ."""
pred, target = np.asarray(pred, dtype=float), np.asarray(target, dtype=float)
if pred.shape != target.shape:
raise ValueError(f"pred and target must have the same shape, got {pred.shape} and {target.shape}")
return pred, target
def _reduce(values: np.ndarray, reduction: str):
"""Reduce per-element losses: "mean" and "sum" give a float, "none" returns the array unchanged."""
if reduction == "mean":
return float(values.mean())
if reduction == "sum":
return float(values.sum())
return values
def _grad_scale(count: int, reduction: str) -> float:
"""Factor the reduction puts on every per-element gradient: 1 / count for "mean", otherwise 1."""
return 1.0 / count if reduction == "mean" else 1.0
class MAELoss:
"""Absolute difference between prediction and target, reduced as the config says."""
def __init__(self, config: MAELossConfig | None = None) -> None:
self.config = config or MAELossConfig()
def forward(self, pred: np.ndarray, target: np.ndarray):
"""pred, target: same shape, any number of axes. Returns a float, or the per-element array for "none"."""
pred, target = _pair(pred, target)
return _reduce(np.abs(pred - target), self.config.reduction)
def backward(self, pred: np.ndarray, target: np.ndarray) -> np.ndarray:
"""Subgradient of the reduced loss with respect to pred, same shape as pred.
The per-element derivative is sign(pred - target), taken as 0 where the two are equal. For "none" the
per-element derivative is returned unscaled (the gradient of the sum).
"""
pred, target = _pair(pred, target)
return np.sign(pred - target) * _grad_scale(pred.size, self.config.reduction)
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Build MAELoss(MAELossConfig()) and reproduce the worked example with forward and backward. Then take targets 1, 2, 3, 4, 100 and evaluate forward for a constant prediction at every integer from 1 to 30. Find the best constant and compare it with the mean and the median of the targets.
Check on learning
- For the targets 1, 2, 3, 4, 100, the mean is 22 and the median is 3. Which would you rather a house-price model predict, and which loss gives you each?
A way to think about it
Decide whether the 100 is a real, important case or a data error. Then match: squared error chases the mean, absolute error the median.
- Near the optimum, why does training with this loss and a constant learning rate fail to settle?
A way to think about it
The gradient size is the same at an error of 0.001 as at an error of 10. Work out the step taken when the prediction is already very close.
- The derivative at zero error is undefined. Does that cause a problem in practice?
A way to think about it
Exact zeros are rare in floating point, and any value between and 1 is a valid subgradient there. Consider what choosing 0 does when a prediction is already perfect.
- Half of your examples have tiny errors and one has an enormous error. How do squared error and absolute error divide their gradient among them?
A way to think about it
Under squared error the gradient is proportional to the error. Under absolute error it is constant. Compute each example's share in both cases.