Sign in

MAE

Mean Absolute Error

A regression loss that averages the absolute difference between prediction and target, treating every unit of error the same.

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

  1. Compute the error ee as prediction minus target for each element.
  2. Take the absolute value of each error.
  3. Reduce with reduction: the mean over all elements by default.
  4. In backward, return sign⁡(e)\operatorname{sign}(e) 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

IfUse instead
Large errors are much worse than small ones and the data has few outliersMean squared error
You want smooth behaviour near zero and robustness to outliersHuber loss
The target has several plausible values for one inputMixture density loss

Math foundations

  1. The loss

    L=1n∑i=1n∣y^i−yi∣\mathcal{L} = \frac{1}{n}\sum_{i=1}^{n} \lvert \hat{y}_i - y_i \rvert

    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 nn.

  2. The subgradient

    ∂L∂y^i=1n sign⁡(y^i−yi)\frac{\partial \mathcal{L}}{\partial \hat{y}_i} = \frac{1}{n}\,\operatorname{sign}(\hat{y}_i - y_i)

    Every element pushes with the same strength, 1/n1/n, in the direction that reduces its own error. The size of the error does not enter.

  3. The best constant prediction is the median

    arg⁡min⁡c  ∑i=1n∣c−yi∣=median⁡(y1,…,yn)\arg\min_{c}\; \sum_{i=1}^{n} \lvert c - y_i \rvert = \operatorname{median}(y_1, \dots, y_n)

    The subgradient with respect to cc is the count of targets below cc minus the count above. It is zero when the two counts are equal, which is the median.

  4. The noise model behind it

    −ln⁡p(y∣y^)=∣y−y^∣b+ln⁡(2b)-\ln p(y \mid \hat{y}) = \frac{\lvert y - \hat{y} \rvert}{b} + \ln(2b)

    The negative log-likelihood of a Laplace distribution with scale bb. Minimising absolute error is maximum likelihood under Laplace noise, which has heavier tails than Gaussian noise.

Symbols

y^i\hat{y}_i
the prediction for element i, pred
yiy_i
the target for element i, target
nn
the number of elements
L\mathcal{L}
the mean absolute error
sign⁡\operatorname{sign}
+1 for positive, -1 for negative, 0 at zero
cc
a constant prediction used for every example
bb
the scale of the Laplace distribution

Worked by hand

Predictions (2,5,9)(2, 5, 9) against targets (3,5,5)(3, 5, 5).

e=(2−3,  5−5,  9−5)=(−1,  0,  4)e = (2 - 3,\; 5 - 5,\; 9 - 5) = (-1,\; 0,\; 4)
L=1+0+43=1.6667\mathcal{L} = \frac{1 + 0 + 4}{3} = 1.6667
∂L∂y^=13 (−1,  0,  1)=(−0.3333,  0,  0.3333)\frac{\partial \mathcal{L}}{\partial \hat{y}} = \tfrac{1}{3}\,(-1,\; 0,\; 1) = (-0.3333,\; 0,\; 0.3333)

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

  1. 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.

  2. 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.

  3. 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 −1-1 and 1 is a valid subgradient there. Consider what choosing 0 does when a prediction is already perfect.

  4. 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.