All formulas

Machine learning building blocks

Huber loss

ml.huber-lossAlso called huber loss, huber, robust loss, huberloss

Lδ=1n∑i=1n{12ri2∣ri∣≤δδ(∣ri∣−12δ)∣ri∣>δL_\delta = \frac{1}{n}\sum_{i=1}^{n}\begin{cases}\frac{1}{2}r_i^2 & |r_i| \le \delta \\ \delta\left(|r_i| - \frac{1}{2}\delta\right) & |r_i| > \delta\end{cases}

whereri=yi−y^ir_i = y_i - \hat{y}_i

Mean loss that is quadratic for residuals up to δ and linear beyond, so outliers weigh less than in squared error. Matches torch.nn.HuberLoss with mean reduction.

Notation

yy

targets

y ∈ ℝn

y^\hat{y}

predictions

ŷ ∈ ℝn

δ\delta

threshold between the quadratic and linear parts

δ > 0 · default 1

nn

number of entries

Size, at least 1

LδL_\delta

Result: the mean loss

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    y=[0,0],y^=[0.5,3],δ=1y = [0, 0], \hat{y} = [0.5, 3], \delta = 1

    Result

    Lδ=2116\displaystyle L_\delta = \frac{21}{16}

    ≈ 1.3125

  2. Given

    y=[1],y^=[1]y = [1], \hat{y} = [1]

    Result

    Lδ=0\displaystyle L_\delta = 0
  3. Given

    y=[2,−1],y^=[0,0],δ=2y = [2, -1], \hat{y} = [0, 0], \delta = 2

    Result

    Lδ=54\displaystyle L_\delta = \frac{5}{4}

    ≈ 1.25

Common mistakes

  • Computes the smooth L1 loss

    Smooth L1 with threshold β equals the Huber loss divided by β; the two agree only when δ = 1.

    Fix: Multiply the smooth L1 loss by δ, or use torch.nn.HuberLoss(delta=δ).

  • Sums instead of averaging

    The per-example losses are summed.

    Fix: Divide by n, or use reduction='mean'.

Source

  • Huber 1964

    Huber, Peter J. Robust Estimation of a Location Parameter. The Annals of Mathematical Statistics 35(1): 73-101, 1964. doi:10.1214/aoms/1177703732

    doi.org