Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Loss functions

P4.635 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

The loss is the only definition of “good” that a training loop ever sees: whatever it scores badly gets changed, and whatever it ignores stays wrong. Choosing it is the first design decision in any model.

  • Logistic regression and softmax regression are trained by minimizing the binary and multi-class cross-entropy, and the gradient they hand to backpropagation is simply the prediction minus the target. (P3.A8: Softmax regression)
  • Backpropagation starts at the loss: the first number it needs is the gradient of the loss with respect to the network's output. (P4.8: Backpropagation: step by step with numbers)
  • Language-model pretraining minimizes the cross-entropy of the next token, averaged over the text. (P10.A1: What is a Large Language Model?, coming soon)
  • A regression with a few bad labels is often fitted with absolute error or Huber loss instead of squared error, so that one wild value does not drag the whole line. (P3.A2: Linear regression)

Before this: Maximum Likelihood Estimation, Cross-entropy, Logistic regression, Softmax regression

After this lesson you can

  • Tell a per-example loss from the average cost over a batch, and say what the reductions mean (average, sum, none)
  • Write the squared error, absolute error and Huber loss with their gradients, and say how each one treats a small and a large error
  • Write the binary cross-entropy and the multi-class cross-entropy, state their gradient with respect to the logits, and explain why they are computed from logits and why they train a confidently wrong model faster than squared error does
  • Connect each loss to a noise model (Gaussian, Laplace, Bernoulli, categorical) through maximum likelihood, and say why a loss is not the same thing as the metric you report

A model predicts 22 for a house whose true value is 33. Another model says there is a 1%1\% chance of rain, and it rains. How wrong is each? Training needs one number per mistake, and a rule for how that number should grow as the mistake gets worse. That rule is the loss function.

It matters more than it looks. The network never sees your goal. It sees only the loss and its slope, and it moves every weight to make that number smaller. Two losses that look alike can train a model to behave very differently.

What a loss is

A loss function takes a prediction and the right answer and returns a number that is 00 for a perfect prediction and grows as the prediction gets worse. For one example it is written LL. Over a data set the model is trained on the average, the cost L\mathcal{L} of P4.8:

L=1N∑i=1NLi.\mathcal{L}=\frac1N\sum_{i=1}^{N}L_i .

Two things are asked of a loss. It must say what “wrong” means for this problem. And it should be smooth enough that its slope, the gradient with respect to the prediction, tells gradient descent (P1.F3) which way to move and how hard to push. Backpropagation (P4.8) then carries that first gradient back to every weight.

Throughout this lesson the error is e=y^−ye=\hat y-y, prediction minus target, as in P4.8. (P3.A2 wrote the residual the other way round, y−y^y-\hat y; the sign does not matter for the losses below, but it flips the sign of the gradients.)

Reductions: average, sum, none. A framework returns one number for a batch, and it must decide how to combine the per-example losses. Take the two examples of P4.8, with errors −1-1 and 0.50.5. Their squared errors are 11 and 0.250.25.

  • Mean (the default in PyTorch, P2.7): 0.6250.625. The gradient with respect to ww is the average of −4-4 and 11, which is −1.5-1.5.
  • Sum: 1.251.25, and the gradient is −3-3. Every extra example adds to the gradient, so a batch of 6464 can push up to 6464 times as hard as a single example, and the best learning rate shifts with the batch size (P4.15).
  • None: the list (1, 0.25)(1,\,0.25), for when you want to weight each example yourself.

With the mean, the size of the gradient does not depend on how many examples are in the batch. That is why it is the usual choice.

Losses for predicting numbers

Suppose the model predicts a number: a price, a temperature, a position. Three losses are in common use. Each one is a price list: it says what an error of each size costs.

Squared error (MSE, mean squared error).

L=e2,∂L∂y^=2e.L=e^2,\qquad \frac{\partial L}{\partial\hat y}=2e .

It is the loss of P4.8 and P3.A2, and written for a batch it is 1N∥y^−y∥2\frac1N\lVert\hat{\mathbf y}-\mathbf y\rVert^2, the squared L2 norm of the error vector divided by NN (P1.B4). Its gradient is proportional to the error, so the push shrinks smoothly as the prediction gets close: gradient descent brakes by itself near the answer. The cost is that big errors count a lot. An error of 1010 costs 100100, a hundred times an error of 11, so a single far-off point can dominate the average. (Some books write 12e2\tfrac12e^2 so that the gradient is ee; that only rescales everything by 22. PyTorch’s MSELoss has no half.) For a model that always answers with one constant, the best constant under squared error is the mean of the targets (P1.D12).

Absolute error (MAE, mean absolute error).

L=∣e∣,∂L∂y^=sign⁡(e)=±1.L=|e|,\qquad \frac{\partial L}{\partial\hat y}=\operatorname{sign}(e)=\pm1 .

An error of 1010 costs 1010, only ten times an error of 11, so an outlier has far less say. The best constant is the median (P1.D12). Written for a batch it is 1N\frac1N times the L1 norm of the error vector (P1.B4). There are two prices. The gradient has size 11 whatever the error, so it does not shrink as the prediction closes in, and with a fixed step the prediction ends up hopping over the answer. And the graph has a sharp corner at e=0e=0, where the slope is not defined; software picks 00 there (PyTorch does).

Huber loss. Squared error is gentle near zero but harsh far away. Absolute error is robust but jumpy near zero. Huber loss takes the first inside a window of half-width δ\delta (“delta”) and the second outside it:

Lδ(e)={12e2∣e∣≤δ,δ(∣e∣−12δ)∣e∣>δ.L_\delta(e)=\begin{cases}\tfrac12e^2 & |e|\le\delta,\\[2pt] \delta\bigl(|e|-\tfrac12\delta\bigr) & |e|>\delta.\end{cases}

At ∣e∣=δ|e|=\delta both pieces equal 12δ2\tfrac12\delta^2 and both have slope δ\delta, so they join without a step or a kink. The gradient is the error clipped to the window:

∂Lδ∂y^=max⁡(−δ, min⁡(e, δ)).\frac{\partial L_\delta}{\partial\hat y}=\max\bigl(-\delta,\ \min(e,\ \delta)\bigr).

Inside the window it behaves like squared error and brakes near the answer; outside, a big error pushes with the fixed strength δ\delta and no more. The number δ\delta is in the units of the target, so pick it near the size of an ordinary error: with prices in thousands of dollars, δ=1\delta=1 is a different loss than it would be in dollars. For a huge δ\delta it becomes half the squared error, and for a tiny δ\delta it looks like δ\delta times the absolute error. PyTorch’s HuberLoss(delta) uses exactly this formula.

Here are the losses and their gradients for four errors. The first is P4.8’s mistake, a prediction of 22 for a target of 33. Each cell shows the loss, with the gradient in brackets. Huber uses δ=1\delta=1.

e=y^−ye=\hat y-yMSEMAEHuber
−1-111 (−2-2)11 (−1-1)0.50.5 (−1-1)
0.50.50.250.25 (11)0.50.5 (11)0.1250.125 (0.50.5)
3399 (66)33 (11)2.52.5 (11)
1010100100 (2020)1010 (11)9.59.5 (11)

Read the last row down the columns. At e=10e=10 squared error pushes 2020 times harder than the absolute error does, and a hundred such errors in a batch would drown the ordinary ones.

See it: loss against prediction

Loss against the error

−4−20240510152025error ŷ − y

Gradient: the slope of the loss, the push on ŷ

−4−224−10−5510error ŷ − y
error ŷ − y = −1
loss = 1
gradient with respect to ŷ = −2

Outlier fit: one line, three losses

Six points; the last one (square) starts as an outlier. Drag it, use the slider, or use its arrow keys.

012345602468xy
  • MSE: w = 0.257, b = 1.729
  • MAE: w = 0.875, b = 0.563
  • Huber (δ = 1): w = 0.6, b = 1.1

Blue and pink are losses; orange is always a gradient. Line style also tells them apart: solid, dashed or dotted.

Loss against prediction. In the Regression tab, choose MSE, MAE or Huber and slide the error ŷ − y (or drag the blue dot). The upper plot is the loss (blue, solid, round marker); the plot under it is the gradient, the push on the prediction (orange, square marker). Huber uses the δ slider. Below, six points are fitted with all three losses at once: the blue solid line is MSE, the pink dashed line is MAE and the dotted line is Huber. Drag the square last point, or use its slider or arrow keys, to make it an outlier. The Classification tab compares cross-entropy with squared error on a sigmoid output, and is used in the next section.

Things to try in the Regression tab:

  • P4.8’s mistake. The widget opens with MSE at e=−1e=-1: loss 11, gradient −2-2. Slide the error to 33 and the gradient becomes 66; at 55 it is 1010. Switch to MAE: at e=5e=5 the loss is 55 and the gradient is still 11.
  • Huber’s window. Choose Huber with δ=1\delta=1 and move the error from 00 outward. The gradient follows the error until ∣e∣=1|e|=1, then stays flat at 11. At e=3e=3 the loss is 2.52.5. Raise δ\delta to 33 and the loss at e=3e=3 is 4.54.5, half of MSE’s 99.
  • The outlier. The last point starts at y=1y=1 instead of its natural 5.55.5. Compare the three fitted slopes with the numbers below, then drag the point back up to 5.55.5 and watch the lines come together.

One outlier, three lines

P3.A2’s widget has six points near a line, (0.5, 1)(0.5,\,1), (1.5, 2)(1.5,\,2), (2.5, 2.5)(2.5,\,2.5), (3.5, 4)(3.5,\,4), (4.5, 4.5)(4.5,\,4.5) and (5.5, 5.5)(5.5,\,5.5). With squared error the best line is y^=0.9 x+0.55\hat y=0.9\,x+0.55. Now move the last target from 5.55.5 to 11, as the “Last one moved” preset of that widget does. The three losses give three lines (Huber with δ=1\delta=1; the last column is each line’s prediction at x=5.5x=5.5):

fitwwbbat x=5.5x=5.5
clean, MSE0.90.90.550.555.55.5
moved, MSE0.2570.2571.7291.7293.143.14
moved, MAE0.8750.8750.56250.56255.3755.375
moved, Huber0.60.61.11.14.44.4

Squared error is pulled hard: the slope falls from 0.90.9 to 0.2570.257, and the line misses the five good points by up to about 1.61.6. Absolute error barely moves; its line passes exactly through two of the good points and sits almost where the clean line was. Huber loss is in between: the outlier still pulls, but only with the clipped strength δ\delta.

Read this correctly. A robust loss reduces the pull of a far point; it does not remove it. And whether to reduce it depends on what the point is. A typing mistake should not move the line. A real but unusual case, such as a rare expensive house, may be exactly what you most need to predict, and a loss that shrugs it off will under-predict it.

Descent behaves differently too. To minimize ∣y^−3∣|\hat y-3| from y^=0\hat y=0 with steps of 0.4×0.4\timesgradient, the prediction hops to 2.82.8, overshoots to 3.23.2, and then bounces between those two forever. With Huber loss the gradient falls to the error itself inside the window, so the steps shrink and the prediction settles near 33. The code cells further down run both.

Losses for predicting labels

Now the model must say which class something is, as a probability. A probability needs its own kind of loss.

Binary cross-entropy (BCE). The model outputs a score zz (the logit) and turns it into a probability of the class “1” with the sigmoid, p=σ(z)p=\sigma(z) (P3.A7). The label is y∈{0,1}y\in\{0,1\}. The loss is the surprise of what actually happened (P1.E1, P1.E3):

L=−[ yln⁡p+(1−y)ln⁡(1−p) ]L=-\bigl[\,y\ln p+(1-y)\ln(1-p)\,\bigr]

For y=1y=1 this is −ln⁡p-\ln p, and for y=0y=0 it is −ln⁡(1−p)-\ln(1-p). Only the probability given to the true answer matters, and the loss falls toward 00 as that probability rises toward 11. It is measured in nats because it uses the natural logarithm, as in P1.E3.

A confident mistake. Take y=1y=1. The table shows BCE and the squared error (p−y)2(p-y)^2 on the probability itself.

predicted ppBCEsquared error
0.90.90.10540.10540.010.01
0.50.50.69310.69310.250.25
0.10.12.30262.30260.810.81
0.010.014.60524.60520.98010.9801

When the model gives the true class only 1%1\%, BCE charges −ln⁡0.01=4.605-\ln0.01=4.605 and keeps growing as pp approaches 00. Squared error on a probability can never exceed 11. This is the number P1.E3 and P3.A10 quote for a confident wrong answer, and P3.A10’s Brier score is exactly this squared error.

Why the gradient matters more than the value. Training does not use the loss, it uses the slope with respect to the logit. For BCE the chain rule (P1.C3) gives a very clean result: the sigmoid’s slope p(1−p)p(1-p) cancels the one in the loss, leaving

∂L∂z=p−y.\frac{\partial L}{\partial z}=p-y .

The push is just “prediction minus target”: the same form as the squared-error gradient 2e2e of a linear model. If you instead put the squared error on top of the sigmoid, the chain rule keeps the sigmoid’s slope and the gradient is 2(p−y) p(1−p)2(p-y)\,p(1-p). For y=1y=1:

logit zzppBCE gradient p−1p-1squared-error gradient
−5-50.00670.0067−0.9933-0.9933−0.0132-0.0132
−2-20.11920.1192−0.8808-0.8808−0.1850-0.1850
000.50.5−0.5-0.5−0.25-0.25
220.88080.8808−0.1192-0.1192−0.0250-0.0250

The top row is the case that matters. The model is sure and wrong (p=0.0067p=0.0067), and BCE pushes with almost its largest possible strength, 0.990.99. Squared error pushes with 0.0130.013, because the flat tail of the sigmoid (P1.A5) squashes the slope. The model that most needs to change learns the slowest. (P1.E3 halved the squared error, so its numbers are half of these; P1.C3 shows the z=−5z=-5 row.) Open the Classification tab of the widget: put the label at 11, switch the axis to the logit, and drag to −5-5.

Two facts follow from p−yp-y. The size of the push is always below 11 however wrong the model is, so a single badly wrong example cannot send the gradient to infinity even though its loss has no upper limit. And the push is 00 only when p=yp=y exactly. For a hard 0/10/1 label the loss never quite reaches 00, so a model keeps trying to push its logits to infinity on separable data, a point P3.A7 explores.

Compute it from the logit. The formula above breaks in floating point. For a logit of 4040 and a label of 00, the sigmoid σ(40)\sigma(40) rounds to exactly 1.01.0, the formula takes −ln⁡(1−1)=−ln⁡0=∞-\ln(1-1)=-\ln0=\infty, and the true loss is 4040. The remedy (P3.A7, P1.G2) is to work from the logit: the loss is softplus(−z)\mathrm{softplus}(-z) for a label of 11 and softplus(z)\mathrm{softplus}(z) for a label of 00, with softplus(u)=ln⁡(1+eu)\mathrm{softplus}(u)=\ln(1+\mathrm{e}^u) evaluated in a form that cannot overflow. This is why frameworks combine the sigmoid and the loss in one function, BCEWithLogitsLoss, which takes the logit. Do not put a sigmoid before it.

Many classes: cross-entropy (CE). With KK classes the model outputs KK logits z\mathbf z, a softmax turns them into probabilities p\mathbf p (P3.A8), and the loss is the surprise of the true class cc:

L=−ln⁡pc=ln⁡∑jezj−zc.L=-\ln p_c=\ln\sum_j\mathrm{e}^{z_j}-z_c .

The second form, a log-sum-exp minus the true logit, is what software computes (P1.G2). Its gradient with respect to the logits is again prediction minus target, now as vectors, with y\mathbf y the one-hot label:

∂L∂z=p−y.\frac{\partial L}{\partial\mathbf z}=\mathbf p-\mathbf y .

For logits (1, 2, 3)(1,\,2,\,3) with the third class true, the probabilities are (0.0900, 0.2447, 0.6652)(0.0900,\,0.2447,\,0.6652), the loss is 0.40760.4076 and the gradient is (0.0900, 0.2447, −0.3348)(0.0900,\,0.2447,\,-0.3348) (P1.E3). The true class gets a negative entry, so its logit is raised; every other class is lowered in proportion to its probability. With two classes this is the binary case.

Label conventions differ between losses, and mixing them up is a common source of bugs:

  • BCE wants labels 00 and 11 as floating-point numbers with the same shape as the logits.
  • CE wants the class number of the true class (an integer, in PyTorch a 64-bit one), or a full probability vector for soft labels (label smoothing, P4.17).
  • Hinge loss, used by support vector machines (P3.B6), wants labels −1-1 and +1+1 and a score, and has no probability in it.
  • Regression losses want the real number itself, in the same units and shape as the prediction.

Every loss is a guess about noise

Why these three pairs: squared error for numbers, BCE for yes-or-no, CE for many classes? Because each is a negative log-likelihood (P1.D10). Say how the target is spread around the model’s prediction, and the loss is the negative log of the probability the model gave to what really happened, averaged over the data. Minimizing the average is maximum likelihood.

model of the targetloss it gives
number = prediction + Gaussian noise (fixed spread)squared error
number = prediction + Laplace noiseabsolute error
yes-or-no label, Bernoulli with probability ppbinary cross-entropy
one of KK classes, categorical with probabilities p\mathbf pcross-entropy

The Gaussian row is derived in P1.D10: the negative log of e−e2/2σ2\mathrm{e}^{-e^2/2\sigma^2} is e2/2σ2e^2/2\sigma^2 plus a constant that does not depend on the model, so minimizing it is minimizing squared error. The Laplace row is the same steps for a density proportional to e−∣e∣/b\mathrm{e}^{-|e|/b}: with the density 12be−∣e∣/b\frac1{2b}\mathrm{e}^{-|e|/b} the negative log is ∣e∣/b+ln⁡(2b)|e|/b+\ln(2b). For b=1b=1 and e=1.5e=1.5 that is 1.5+0.693=2.1931.5+0.693=2.193. The Laplace distribution has a sharp peak and heavier tails than a Gaussian, which is why it expects some large errors and charges less for them. The constant, and the scale bb or σ\sigma when it is fixed, change nothing about which parameters are best.

So “which loss?” is really “how does my target scatter around the prediction?” Targets with a few wild values suggest a heavier-tailed story, such as absolute error or Huber. A label that is one of KK classes is categorical, and squared error on class scores would be the wrong story.

Losses are not metrics

The number you want and the number you can train on are often different. Accuracy counts correct answers. As the model’s parameters change smoothly, the answers flip all at once, so accuracy is a staircase: flat almost everywhere, with zero gradient (P1.F1). The same is true of the F1 score and of any measure that depends on a threshold (P3.A9). Gradient descent cannot follow a staircase, so we train on a smooth surrogate, such as cross-entropy, and judge the finished model on the metric.

The two can disagree. Take a label of 11 and a model that says p=0.6p=0.6. After more training it says p=0.7p=0.7. The answer is right both times, so accuracy is unchanged, but the loss fell from 0.51080.5108 to 0.35670.3567. Watch the metric, not just the loss.

The loss also treats every example alike unless you say otherwise. For rare classes you can multiply the loss of each class by a class weight, or use the focal loss that scales the cross-entropy of well-classified examples down; both are named in the boxes below and in P3.A10.

Intuition

Think of the loss as a landscape that you design for the model to roll down, and the gradient as its slope under the model’s feet. Squared error is a smooth bowl: the walls get steeper the farther out you go, so a far point gets a loud vote. Absolute error is a V: every point votes with the same strength, from near or far, and the vote does not fade near the bottom. Huber is a bowl with its walls straightened into slopes beyond the window. Cross-entropy on a probability is a wall that rises without limit as the model’s probability for the truth approaches 00: it is built to make confident mistakes painful.

The picture breaks in one place: a loss also ties the model to a story about noise, so changing the shape changes what the model is trying to be (the mean, the median or a probability), not just how fast it learns.

Math

For one example, with error e=y^−ye=\hat y-y, logit zz, probability p=σ(z)p=\sigma(z) and softmax probabilities p\mathbf p:

lossvalue LLgradient
squared errore2e^22e2e with respect to y^\hat y
absolute error∣e∣\lvert e\rvertsign⁡(e)\operatorname{sign}(e)
Huber12e2\tfrac12e^2 or δ(∣e∣−12δ)\delta(\lvert e\rvert-\tfrac12\delta)clip⁡(e,−δ,δ)\operatorname{clip}(e,-\delta,\delta)
binary cross-entropy−[yln⁡p+(1−y)ln⁡(1−p)]-[y\ln p+(1-y)\ln(1-p)]p−yp-y with respect to zz
cross-entropy−ln⁡pc-\ln p_cp−y\mathbf p-\mathbf y with respect to z\mathbf z

The average cost is L=1N∑iLi\mathcal L=\frac1N\sum_iL_i, and its gradient is the average of the per-example gradients. The derivation of p−yp-y is one line of the chain rule: ddz(−ln⁡σ(z))=−1σ⋅σ(1−σ)=σ−1\frac{\mathrm d}{\mathrm dz}(-\ln\sigma(z))=-\frac1\sigma\cdot\sigma(1-\sigma)=\sigma-1 for y=1y=1, and the case y=0y=0 gives σ\sigma. For many classes it is the derivative of the log-sum-exp, which is the softmax (P1.C7).

Code

PyTorch’s loss objects return the average over the batch by default. Here are the errors −1-1, 0.50.5 and 1010 of the table above, one logit for each of three examples, and the logits (1,2,3)(1,2,3) for three classes. Every number comes from a local run with PyTorch 2.9.1. (PyTorch is not available in the in-browser runner, so this block is static.)

import torch
import torch.nn as nn

# Regression: errors -1, 0.5 and 10
pred = torch.tensor([2.0, 4.5, 13.0])
target = torch.tensor([3.0, 4.0, 3.0])
print("MSE  :", nn.MSELoss()(pred, target).item())
print("MAE  :", round(nn.L1Loss()(pred, target).item(), 4))
print("Huber:", nn.HuberLoss(delta=1.0)(pred, target).item())
print("sum  :", nn.MSELoss(reduction="sum")(pred, target).item())

# Binary: one logit per example, float labels 0.0 or 1.0
z = torch.tensor([-5.0, 0.0, 2.0])
y = torch.tensor([1.0, 1.0, 1.0])
per_example = nn.BCEWithLogitsLoss(reduction="none")(z, y)
print("BCE  :", [round(v, 4) for v in per_example.tolist()])

big, zero = torch.tensor([40.0]), torch.tensor([0.0])    # logit 40, label 0
print("stable:", nn.BCEWithLogitsLoss()(big, zero).item())
print("naive :", nn.BCELoss()(torch.sigmoid(big), zero).item())

# Several classes: logits (1, 2, 3), the third class is true
logits = torch.tensor([[1.0, 2.0, 3.0]], requires_grad=True)
loss = nn.CrossEntropyLoss()(logits, torch.tensor([2]))
loss.backward()
print("CE   :", round(loss.item(), 4))
print("grad :", [round(v, 4) for v in logits.grad[0].tolist()])
MSE  : 33.75
MAE  : 3.8333
Huber: 3.375
sum  : 101.25
BCE  : [5.0067, 0.6931, 0.1269]
stable: 40.0
naive : 100.0
CE   : 0.4076
grad : [0.09, 0.2447, -0.3348]

The three means come from the table: (1+0.25+100)/3=33.75(1+0.25+100)/3=33.75, (1+0.5+10)/3=3.833(1+0.5+10)/3=3.833 and (0.5+0.125+9.5)/3=3.375(0.5+0.125+9.5)/3=3.375. The naive line shows what going through a probability costs: BCELoss takes probabilities and, as its documentation states, clamps each logarithm at −100-100, so it reports 100100 where the true loss is 4040. BCEWithLogitsLoss gets 4040. The last two lines are the numbers worked out above, and the gradient is p−y\mathbf p-\mathbf y.

Try it: the table and the outlier fit

Try it: values and gradients

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first cell reproduces the two regression tables and the classification gradient table. Change e to your own errors, or d to try another window.

Try it: one outlier, three losses

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The slopes are the ones in the table above. (The method behind the code, reweighted least squares, refits a weighted squared-error line again and again, giving points far from the line a smaller weight each time; it is one convenient way to fit these losses, not the only one.) Change the last yy to 5.55.5 and all three lines become the clean line. The last two printed lines show the bouncing: the absolute-error step keeps hopping between 2.82.8 and 3.23.2, while the Huber step settles toward 33.

Choosing a loss

  • A number, clean data: squared error. It is the maximum-likelihood loss for Gaussian noise and its gradient brakes by itself.
  • A number, with outliers you cannot remove: Huber loss or absolute error. Pick δ\delta near a typical error. Look at the outliers first.
  • Two classes: binary cross-entropy, computed from the logit with BCEWithLogitsLoss.
  • Several classes: cross-entropy with CrossEntropyLoss on raw logits. The same loss trains a language model, one token at a time (P10.A1).
  • Rare classes: class weights or resampling (P3.A10), or the focal loss below.
Go deeper Huber loss as a noise model, and why it is called robust

Any loss defines a density through e−L(e)\mathrm{e}^{-L(e)} once the area under it is finite. For Huber loss with δ=1\delta=1 the density is proportional to e−L1(e)\mathrm{e}^{-L_1(e)}: bell-shaped near the centre, because L1=12e2L_1=\tfrac12e^2 there, and decaying like a Laplace density in the tails, because L1L_1 grows linearly there. The area under e−L1(e)\mathrm{e}^{-L_1(e)} is about 2.9242.924. So Huber loss is the negative log-likelihood of a noise that is Gaussian in the middle and exponential at the edges. It was introduced in robust statistics: the aim is an estimate that a few bad values cannot move far.

The key to the robustness is in the gradient. An error enters the update only through its clipped value, so the influence of any one example on the update is at most δ\delta in size, however far away it is. Squared error has no such cap: its influence grows with the error.

Go deeper Class weights and the focal loss

A class weight multiplies the loss of every example of a class by a number, often larger for the rare class, so that mistakes on it cost more. It changes what the model optimizes, and it shifts the predicted probabilities, which P3.A10 shows.

The focal loss of Lin and colleagues (2017) was introduced for object detection, where almost all candidate locations are easy background. It scales the cross-entropy of an example by (1−pt)γ(1-p_t)^\gamma, where ptp_t is the probability the model gave to the true class:

FL=−(1−pt)γln⁡pt.\mathrm{FL}=-(1-p_t)^{\gamma}\ln p_t .

With γ=2\gamma=2, the setting that worked best in their experiments, an example at pt=0.9p_t=0.9 has its loss cut from 0.10540.1054 to 0.00110.0011, a factor of 100100, while at pt=0.1p_t=0.1 the loss only falls from 2.30262.3026 to 1.86511.8651. The easy examples stop dominating and the hard ones keep their say. With γ=0\gamma=0 it is ordinary cross-entropy. It is one design among several for imbalance; it does not make the probabilities calibrated.

Check your understanding

  1. A model predicts y^=5\hat y=5 for a target y=8y=8, so e=−3e=-3. What is the Huber loss with δ=1\delta=1?

  2. Which assumption about the noise around the prediction leads to the absolute error as the loss?

  3. The true label is 11 and the model says p=0.01p=0.01. What is the binary cross-entropy, in nats?

  4. The true label is 00 and the model says p=0.8p=0.8. What is the gradient of the binary cross-entropy with respect to the logit?

  5. Why do frameworks offer a loss that takes the logit and applies the sigmoid inside it, instead of a sigmoid followed by a separate loss?

Exercises

  1. For Huber loss with δ=2\delta=2, find the loss and gradient at e=5e=5 and at e=1e=1.
    Show answerAt e=5e=5 the loss is 2×(5−1)=82\times(5-1)=8 and the gradient is clipped to 22. At e=1e=1 the loss is 12×1=0.5\tfrac12\times1=0.5 and the gradient is 11.
  2. The targets 11, 22, 33, 44, 100100 are to be predicted by one constant. Which constant minimizes the squared error, and which minimizes the absolute error?
    Show answerThe mean, 2222, for squared error, and the median, 33, for absolute error. The single large target drags the mean but not the median.
  3. Using the table, find the mean squared error, mean absolute error and mean Huber loss (δ=1\delta=1) over the three errors −1-1, 0.50.5 and 1010. Then change the reduction to sum for MSE.
    Show answer(1+0.25+100)/3=33.75(1+0.25+100)/3=33.75, (1+0.5+10)/3=3.833(1+0.5+10)/3=3.833 and (0.5+0.125+9.5)/3=3.375(0.5+0.125+9.5)/3=3.375. The sum for MSE is 101.25101.25, three times the mean.
  4. A model gives p=0.2p=0.2 for an example. Find the binary cross-entropy and its gradient with respect to the logit when the label is 00 and when it is 11.
    Show answerFor y=0y=0: −ln⁡0.8=0.2231-\ln0.8=0.2231 and p−y=0.2p-y=0.2. For y=1y=1: −ln⁡0.2=1.6094-\ln0.2=1.6094 and p−y=−0.8p-y=-0.8. The same prediction is cheap for one label and expensive for the other.
  5. Three classes, all logits 00, and the first class is true. What are the loss and the gradient?
    Show answerAll probabilities are 13\tfrac13, so the loss is ln⁡3=1.0986\ln3=1.0986 and the gradient is p−y=(−23, 13, 13)\mathbf p-\mathbf y=(-\tfrac23,\ \tfrac13,\ \tfrac13).
  6. A classifier improves its probability for a true label of 11 from 0.60.6 to 0.70.7, with a 0.50.5 threshold. By how much do the accuracy and the cross-entropy change?
    Show answerThe accuracy does not change, because the answer was right before and after. The cross-entropy falls from −ln⁡0.6=0.5108-\ln0.6=0.5108 to −ln⁡0.7=0.3567-\ln0.7=0.3567.
  7. In the second code cell, change the last yy to 33. How do the three slopes change compared with y=1y=1, and why?
    Show answerSquared error gives 0.5430.543, up from 0.2570.257: it feels the size of the error. The absolute-error slope stays 0.8750.875 and the Huber slope stays 0.60.6. Absolute error’s pull depends only on which side of the line the point is, and Huber’s is clipped at δ\delta once the error is outside the window, so neither changes until the point enters that regime (for Huber, until its error is within δ\delta; for absolute error, until it crosses the line).

Next: P4.7 explains backpropagation in pictures, and P4.8 follows the numbers through a network step by step, starting from the gradient of the loss that this lesson defined.

Key takeaways

  • A loss scores one prediction against its target: small is good. Training minimizes the average of the per-example losses over a batch (P4.8). With reduction “mean” the gradient does not grow with the batch size; with “sum” it grows in proportion to it. Define the error as e=y^−ye=\hat y-y.
  • Squared error e2e^2 has gradient 2e2e: smooth, braking near zero, and dominated by the largest errors. Absolute error ∣e∣|e| has gradient ±1\pm1 everywhere except 00: it costs a big error only in proportion and its best constant is the median. Huber loss is 12e2\tfrac12e^2 inside ∣e∣≤δ|e|\le\delta and δ(∣e∣−12δ)\delta(|e|-\tfrac12\delta) outside, so its gradient is the error clipped to [−δ,δ][-\delta,\delta].
  • On the six points of P3.A2 with the last one moved from 5.55.5 down to 11, the squared-error line has slope 0.2570.257, the absolute-error line 0.8750.875 and the Huber line (δ=1\delta=1) 0.60.6. The clean line has slope 0.90.9. Robust losses reduce the pull of an outlier; they do not ignore it, and the outlier may be real data.
  • Binary cross-entropy is −[yln⁡p+(1−y)ln⁡(1−p)]-[y\ln p+(1-y)\ln(1-p)], the surprise of what happened. For a label of 11 and p=0.01p=0.01 it is 4.6054.605, while the squared error is below 11. Its gradient with respect to the logit is p−yp-y: for a label of 11 and a logit of −5-5 it is −0.9933-0.9933, against −0.0132-0.0132 for squared error on the same sigmoid.
  • Cross-entropy for KK classes is −ln⁡pc-\ln p_c with a softmax, and its gradient with respect to the logits is p−y\mathbf p-\mathbf y. Frameworks compute both cross-entropies from the logits (log-sum-exp or softplus), so give BCEWithLogitsLoss and CrossEntropyLoss raw scores, not probabilities.
  • Each loss is a negative log-likelihood: squared error for Gaussian noise, absolute error for Laplace noise, binary cross-entropy for a Bernoulli label, cross-entropy for a categorical label. Choosing a loss is choosing a story about how the target scatters around the prediction.
  • A loss is not a metric. Accuracy and F1 are flat almost everywhere, so training uses a smooth surrogate such as cross-entropy and judges the result on the metric afterwards. A lower loss can come with the same accuracy.
Found a mistake? Tell us