Loss: One Number for How Wrong the Model Is

A classifier answers by giving every class a score, and training has to improve those scores without anyone looking at each answer. For that it needs one number that measures how wrong the model is and that moves whenever the model gets a little better or a little worse. That number is the loss. For a classifier, the usual one comes from turning the scores into probabilities and then asking how much probability went to the correct answer.

A loss: one number for how wrong

A loss function compares a model's prediction for one example with the correct answer and gives back a number: small when the prediction is good, large when it is bad. A perfect prediction scores 0, and lower is always better. The loss is not a percentage and has no upper limit: a prediction can be wrong by a little or by a lot, and the loss says which.

One example says little about a model, so the loss is measured on many examples and averaged. If three examples have losses of 0.11, 0.69 and 2.30, the model's loss on them is their average:

ExampleThe predictionLoss
1confident and right0.11
2unsure0.69
3mostly wrong2.30
all threethe average1.03

Training is the search for parameters that make this average as small as possible. Everything else in this page is about how a classifier's loss is worked out, and why it, and not the share of right answers, is the number training follows.

True or false?

A loss of 0.5 means the model is wrong on half of the examples.

False. A loss is not a share of examples. It is an average of how wrong each prediction is, 0 for perfect and with no upper limit, so 0.5 says nothing directly about how many answers are right.

Logits: the raw scores

A classifier's last step produces one score per class, a weighted sum of the input plus a bias. These raw scores are called logits. They can be any number: large, small, zero or negative. They are not probabilities: they do not have to lie between 0 and 1, and the scores of one example do not add up to anything in particular.

Take a classifier with three classes, cat, dog and fox, that gives one picture the scores 2.0, 1.0 and -1.0. The highest score, cat, is its answer. The scores also say that the model prefers cat to dog and dog to fox, but not how sure it is: is 2.0 against 1.0 a strong preference or a weak one? A score of -1.0 is not an error either; it only means fox scored lowest. To read the scores as confidence, they first have to become probabilities.

True or false?

The logits of one example must add up to 1.

False. Logits are raw scores and can be any numbers. Only after the softmax do the values of one example add up to 1.

Softmax: from scores to probabilities

The softmax function turns the scores of one example into probabilities in two steps. First it makes every score positive by raising the number \( e \) (about 2.718) to the power of that score. A larger score always gives a larger result, and a negative score gives a small positive fraction: \( e^{2} \) is 2.718 times 2.718, about 7.389, while \( e^{-1} \) is 1 divided by 2.718, about 0.368. Then it divides each of these results by their total, so that together they add up to 1.

Softmax of the scores 2.0, 1.0 and -1.0
ClassScore (logit)e to the scoreProbability
cat2.07.3890.705
dog1.02.7180.259
fox-1.00.3680.035
total10.4751.000

Each probability is its row's value divided by the total 10.475: 7.389 divided by 10.475 is about 0.705. Written as a formula, for the scores \( s_1, s_2, \ldots \) of one example:

$$p_i = \frac{e^{s_i}}{e^{s_1} + e^{s_2} + \cdots + e^{s_k}}$$

softmax k is the number of classes

Three things follow from the way it is built. Every probability is positive, because \( e \) to any power is positive, even for a negative score. The probabilities of one example add up to 1, because each is a share of the same total. And the order is kept: the highest score gets the highest probability, so the predicted class is the same before and after the softmax. What the softmax adds is how sure the model is. Here the model gives cat 70.5%, which a bare score of 2.0 could not say.

When a model scores many examples at once, the scores sit in a table with one row per example and one column per class. The softmax must work along each row, so that every example gets its own probabilities adding up to 1. In PyTorch that is the dimension argument: scores.softmax(dim=1) for scores of shape (examples, classes).

True or false?

For the scores 1, 2 and 3, the softmax gives 1/6, 2/6 and 3/6.

False. The softmax divides e to each score by the total of those powers, not the scores by their sum. The result is about 0.09, 0.24 and 0.67.

Adding 10 to every score of one example leaves its softmax probabilities unchanged.

True. Adding 10 multiplies every power of e by the same number, e to the 10, and that factor cancels when each is divided by the total. Only the differences between scores matter.

The softmax can make a class with a lower score more probable than one with a higher score.

False. A higher score always gives a larger power of e, and every power is divided by the same total, so the order of the classes never changes.

Cross-entropy: the loss of a classifier

Once a model's scores are probabilities, a natural measure of how wrong it is follows: look at the probability it gave to the correct class. Near 1 means right and sure, so the loss should be near 0. Near 0 means the model all but ruled out the right answer, so the loss should be large. The cross-entropy loss does exactly this. It is minus the natural logarithm of that probability:

$$\text{loss} = -\ln(p_{\text{correct}})$$

cross-entropy for one example

The natural logarithm \( \ln \) undoes the power of \( e \): \( \ln(p) \) is the power you raise \( e \) to in order to get \( p \). For example, \( e^{-1} \) is about 0.368, so \( \ln(0.368) \) is about -1. For any probability below 1 that power is negative, and the minus sign in front turns it into a positive loss. A few values show its shape:

Probability of the correct classLoss
0.990.010
0.90.105
0.50.693
0.12.303
0.014.605

loss against probability of the correct class

  • cross-entropy

The loss is 0 only when the correct class gets probability 1, and it grows without limit as that probability falls towards 0. The curve is steepest at the bad end, so a confident wrong answer costs far more than an unsure one.

In the cat, dog and fox example, if the picture really is a cat, the loss is \( -\ln(0.705) \), about 0.349. If it is really a fox, the loss is \( -\ln(0.035) \), about 3.349.

There is a shortcut that skips the division. Take the total of the powers of \( e \), 10.475 here, and its natural logarithm, about 2.349. The loss is that number minus the score of the correct class. So cat gives \( 2.349 - 2.0 = 0.349 \), dog \( 2.349 - 1.0 = 1.349 \) and fox \( 2.349 - (-1.0) = 3.349 \).

The shortcut also shows that the wrong classes count. Their scores are part of the total, so lowering the score of a wrong class lowers the loss too, even though only the correct class's probability appears in the formula.

One value is worth knowing. A model that cannot tell ten classes apart and gives each of them the same score gives each a probability of 0.1, and its loss is \( -\ln(0.1) \), about 2.303. A classifier with ten classes whose scores are all close together starts near this value, and any useful model has to get below it.

True or false?

Raising the probability of the correct class from 0.01 to 0.1 lowers the loss by more than raising it from 0.9 to 0.99.

True. The first change lowers the loss from about 4.605 to 2.303, the second only from about 0.105 to 0.010. The loss punishes the confident wrong answers most.

Because the formula uses only the probability of the correct class, the scores of the wrong classes do not affect the loss.

False. The wrong classes' scores are part of the total that every probability is divided by. A higher wrong score shrinks the correct class's share and raises the loss.

Why training follows the loss, not the accuracy

The number people usually care about is accuracy, the share of examples where the highest score belongs to the correct class. It seems natural to train on it directly. The trouble is that training improves a model by changing its weights in small steps, and accuracy hardly ever notices a small step.

Take one picture of a cat and a model with two classes, cat and dog. The dog score is fixed at 1.0, and the cat score equals one weight. While that weight is below 1.0, dog wins and the answer is wrong; above 1.0, cat wins and the answer is right. Now nudge the weight and watch both numbers:

One cat picture, as one weight changes

value against weight (the cat score)

  • accuracy (0 or 1)
  • cross-entropy loss

Moving the weight from 0 to 0.5 leaves the answer wrong, so the accuracy stays at 0. Yet the model did improve: the probability of cat rose, and the loss fell from about 1.313 to 0.974. Moving it from 1.5 to 2.0 leaves the answer right and the accuracy at 1, while the loss falls from about 0.474 to 0.313 as the model grows surer. Accuracy changes only at the one point where two scores swap places; everywhere else it is flat.

Over many examples, accuracy becomes a staircase: it jumps only when some example's answer flips. A small change to one weight usually flips none, so accuracy cannot say whether that change helped or hurt.

The loss is built from the sizes of all the scores through the softmax, so it moves with every change, however small, and its direction says whether the change was an improvement. That is the signal a training rule needs to decide which way to move each weight. Accuracy stays the number you report; the loss is the number you train on, and the two usually improve together.

True or false?

Two models with the same accuracy on the same examples can have different losses.

True. Accuracy only counts which answers are right. The loss also sees how much probability each answer got, so a model that is right and sure has a lower loss than one that is right by a narrow margin.

If a small change to a weight leaves the accuracy the same, the change made no difference to the model.

False. The scores and probabilities still changed, and the loss shows by how much and in which direction. Accuracy only reacts when an answer flips.

Give the library the raw scores

In PyTorch, the cross-entropy loss is nn.CrossEntropyLoss. It takes two inputs: the raw scores first, and the correct classes second. Each correct class is given as its class number, a whole number stored with the torch.long type. The loss applies the softmax itself before taking the logarithm. Its documentation says the input should be the unnormalized logits, which do not need to be positive or sum to 1.

import torch
from torch import nn

logits = torch.tensor([[2.0, 1.0, -1.0]])  # one example, three classes
target = torch.tensor([0])                 # the correct class is class 0, cat

loss_fn = nn.CrossEntropyLoss()
print(loss_fn(logits, target))             # about 0.349

probs = logits.softmax(dim=1)
print(probs)                               # about 0.705, 0.259, 0.035
print(loss_fn(probs, target))              # about 0.766: wrong, softmax applied twice

The first call gives the loss worked out by hand above, about 0.349. The last call is a common mistake: the model's output is turned into probabilities first and then handed to the loss, which applies its own softmax on top. The probabilities 0.705, 0.259 and 0.035 are treated as scores, squashed again into much flatter probabilities, and the loss comes out near 0.766, a number that no longer measures the model.

There is also a practical reason the library wants the raw scores. Powers of \( e \) grow very fast: a score of 100 gives a number with 44 digits, too large for the 32-bit floating-point numbers a model usually computes with. A separate softmax followed by a logarithm can overflow on such numbers, or round a tiny probability down to 0. Because the library does the softmax and the logarithm together, it can use the shortcut from above after first subtracting the largest score from every score. That leaves the probabilities unchanged, just as adding 10 to every score did in the check above, and it makes the largest power of \( e \) exactly \( e^{0} \), which is 1. So nothing can overflow, the total is never rounded to 0, and the result stays accurate. So the model returns logits, the loss is given logits, and the softmax is applied by hand only when you want to read the probabilities.

Given a batch of examples, with scores of shape (examples, classes) and one class number per example, nn.CrossEntropyLoss() returns a single number: by default (reduction='mean') the average of the examples' losses. reduction='none' returns one loss per example instead.

True or false?

With its default settings, `nn.CrossEntropyLoss` returns the average loss over the examples of a batch.

True. The default `reduction='mean'` averages the per-example losses into one number; `reduction='none'` keeps them separate.

Applying the softmax to the scores before `nn.CrossEntropyLoss` gives the same loss, only computed more safely.

False. The loss applies its own softmax, so it would run twice and give a wrong number, about 0.766 instead of 0.349 in the example.