A model predicts for a house whose true value is . Another model says there is a 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 for a perfect prediction and grows as the prediction gets worse. For one example it is written . Over a data set the model is trained on the average, the cost of P4.8:
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 , prediction minus target, as in P4.8. (P3.A2 wrote the residual the other way round, ; 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 and . Their squared errors are and .
- Mean (the default in PyTorch, P2.7): . The gradient with respect to is the average of and , which is .
- Sum: , and the gradient is . Every extra example adds to the gradient, so a batch of can push up to times as hard as a single example, and the best learning rate shifts with the batch size (P4.15).
- None: the list , 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).
It is the loss of P4.8 and P3.A2, and written for a batch it is , the squared L2 norm of the error vector divided by (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 costs , a hundred times an error of , so a single far-off point can dominate the average. (Some books write so that the gradient is ; that only rescales everything by . 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).
An error of costs , only ten times an error of , so an outlier has far less say. The best constant is the median (P1.D12). Written for a batch it is times the L1 norm of the error vector (P1.B4). There are two prices. The gradient has size 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 , where the slope is not defined; software picks 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”) and the second outside it:
At both pieces equal and both have slope , so they join without a step or a kink. The gradient is the error clipped to the window:
Inside the window it behaves like squared error and brakes near the answer; outside, a big error pushes with the fixed strength and no more. The number is in the units of the target, so pick it near the size of an ordinary error: with prices in thousands of dollars, is a different loss than it would be in dollars. For a huge it becomes half the squared error, and for a tiny it looks like 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 for a target of . Each cell shows the loss, with the gradient in brackets. Huber uses .
| MSE | MAE | Huber | |
|---|---|---|---|
| () | () | () | |
| () | () | () | |
| () | () | () | |
| () | () | () |
Read the last row down the columns. At squared error pushes 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
Things to try in the Regression tab:
- P4.8’s mistake. The widget opens with MSE at : loss , gradient . Slide the error to and the gradient becomes ; at it is . Switch to MAE: at the loss is and the gradient is still .
- Huber’s window. Choose Huber with and move the error from outward. The gradient follows the error until , then stays flat at . At the loss is . Raise to and the loss at is , half of MSE’s .
- The outlier. The last point starts at instead of its natural . Compare the three fitted slopes with the numbers below, then drag the point back up to and watch the lines come together.
One outlier, three lines
P3.A2’s widget has six points near a line, , , , , and . With squared error the best line is . Now move the last target from to , as the “Last one moved” preset of that widget does. The three losses give three lines (Huber with ; the last column is each line’s prediction at ):
| fit | at | ||
|---|---|---|---|
| clean, MSE | |||
| moved, MSE | |||
| moved, MAE | |||
| moved, Huber |
Squared error is pulled hard: the slope falls from to , and the line misses the five good points by up to about . 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 .
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 from with steps of gradient, the prediction hops to , overshoots to , 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 . 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 (the logit) and turns it into a probability of the class “1” with the sigmoid, (P3.A7). The label is . The loss is the surprise of what actually happened (P1.E1, P1.E3):
For this is , and for it is . Only the probability given to the true answer matters, and the loss falls toward as that probability rises toward . It is measured in nats because it uses the natural logarithm, as in P1.E3.
A confident mistake. Take . The table shows BCE and the squared error on the probability itself.
| predicted | BCE | squared error |
|---|---|---|
When the model gives the true class only , BCE charges and keeps growing as approaches . Squared error on a probability can never exceed . 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 cancels the one in the loss, leaving
The push is just “prediction minus target”: the same form as the squared-error gradient 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 . For :
| logit | BCE gradient | squared-error gradient | |
|---|---|---|---|
The top row is the case that matters. The model is sure and wrong (), and BCE pushes with almost its largest possible strength, . Squared error pushes with , 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 row.) Open the Classification tab of the widget: put the label at , switch the axis to the logit, and drag to .
Two facts follow from . The size of the push is always below 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 only when exactly. For a hard label the loss never quite reaches , 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 and a label of , the sigmoid rounds to exactly , the formula takes , and the true loss is . The remedy (P3.A7, P1.G2) is to work from the logit: the loss is for a label of and for a label of , with 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 classes the model outputs logits , a softmax turns them into probabilities (P3.A8), and the loss is the surprise of the true class :
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 the one-hot label:
For logits with the third class true, the probabilities are , the loss is and the gradient is (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 and 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 and 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 target | loss it gives |
|---|---|
| number = prediction + Gaussian noise (fixed spread) | squared error |
| number = prediction + Laplace noise | absolute error |
| yes-or-no label, Bernoulli with probability | binary cross-entropy |
| one of classes, categorical with probabilities | cross-entropy |
The Gaussian row is derived in P1.D10: the negative log of is 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 : with the density the negative log is . For and that is . 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 or 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 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 and a model that says . After more training it says . The answer is right both times, so accuracy is unchanged, but the loss fell from to . 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 : 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 , logit , probability and softmax probabilities :
| loss | value | gradient |
|---|---|---|
| squared error | with respect to | |
| absolute error | ||
| Huber | or | |
| binary cross-entropy | with respect to | |
| cross-entropy | with respect to |
The average cost is , and its gradient is the average of the per-example gradients. The derivation of is one line of the chain rule: for , and the case gives . 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 , and of the table above, one logit for each of three examples, and the logits 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: , and . The naive line shows what going through a probability costs: BCELoss takes probabilities and, as its documentation states, clamps each logarithm at , so it reports where the true loss is . BCEWithLogitsLoss gets . The last two lines are the numbers worked out above, and the gradient is .
Try it: the table and the outlier fit
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.
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 to and all three lines become the clean line. The last two printed lines show the bouncing: the absolute-error step keeps hopping between and , while the Huber step settles toward .
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 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
CrossEntropyLosson 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 once the area under it is finite. For Huber loss with the density is proportional to : bell-shaped near the centre, because there, and decaying like a Laplace density in the tails, because grows linearly there. The area under is about . 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 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 , where is the probability the model gave to the true class:
With , the setting that worked best in their experiments, an example at has its loss cut from to , a factor of , while at the loss only falls from to . The easy examples stop dominating and the hard ones keep their say. With it is ordinary cross-entropy. It is one design among several for imbalance; it does not make the probabilities calibrated.
Check your understanding
A model predicts for a target , so . What is the Huber loss with ?
The error is outside the window , so the loss is . The value is half the squared error, which would apply only if were at least . The value is the absolute error, which forgets the offset that makes the pieces meet. The value is the squared error.
Which assumption about the noise around the prediction leads to the absolute error as the loss?
The negative log of the Laplace density is , which is the absolute error up to constants. Gaussian noise gives the squared error. The Bernoulli and categorical models give binary and multi-class cross-entropy, which are for labels, not numbers.
The true label is and the model says . What is the binary cross-entropy, in nats?
The loss is . The value is , the loss for a model that gave to the truth. The value is the probability itself. The value near is the squared error , which can never exceed .
The true label is and the model says . What is the gradient of the binary cross-entropy with respect to the logit?
The gradient is . It is positive, so gradient descent lowers the logit, which is right because the label is . The values are and mix up the two classes. A negative would raise the logit and make the mistake worse.
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?
With a logit of and a label of the sigmoid rounds to exactly and the naive loss is , though the true value is . The combined form uses the softplus of the logit and stays finite. Summing to is the softmax, not the sigmoid. The gradient stays , not the squared-error one. The label convention is unchanged: still and .
Exercises
- For Huber loss with , find the loss and gradient at and at .
Show answer
At the loss is and the gradient is clipped to . At the loss is and the gradient is . - The targets , , , , are to be predicted by one constant. Which constant minimizes the squared error, and which minimizes the absolute error?
Show answer
The mean, , for squared error, and the median, , for absolute error. The single large target drags the mean but not the median. - Using the table, find the mean squared error, mean absolute error and mean Huber loss () over the three errors , and . Then change the reduction to sum for MSE.
Show answer
, and . The sum for MSE is , three times the mean. - A model gives for an example. Find the binary cross-entropy and its gradient with respect to the logit when the label is and when it is .
Show answer
For : and . For : and . The same prediction is cheap for one label and expensive for the other. - Three classes, all logits , and the first class is true. What are the loss and the gradient?
Show answer
All probabilities are , so the loss is and the gradient is . - A classifier improves its probability for a true label of from to , with a threshold. By how much do the accuracy and the cross-entropy change?
Show answer
The accuracy does not change, because the answer was right before and after. The cross-entropy falls from to . - In the second code cell, change the last to . How do the three slopes change compared with , and why?
Show answer
Squared error gives , up from : it feels the size of the error. The absolute-error slope stays and the Huber slope stays . Absolute error’s pull depends only on which side of the line the point is, and Huber’s is clipped at once the error is outside the window, so neither changes until the point enters that regime (for Huber, until its error is within ; 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.