The network from
The running example from here on is a network that looks at a picture of clothing and decides whether it shows a T-shirt, a trouser or a sneaker.
Three raw scores
The output layer has three neurons, one per class. For one image it might produce:
These raw scores are called
But the scores are awkward to work with. They can be any size, positive or negative, and they do not add up to anything in particular. Is 2.0 against 1.0 a confident answer or a hesitant one? To judge the network, and to train it, we want a probability for each class: three numbers between 0 and 1 that add up to 1.
Softmax: scores into probabilities
The function that does this is
- Make every score positive by raising to its power. Larger scores become much larger, and negative scores become small positive numbers.
- Divide each by the total, so that they add up to 1.
probability of class j = e to its score, divided by the sum of e to every score
For the scores :
| Class | Score | Divided by the total, 11.21 | |
|---|---|---|---|
| T-shirt | 2.0 | 7.39 | 65.9% |
| Trouser | 1.0 | 2.72 | 24.2% |
| Sneaker | 0.1 | 1.11 | 9.9% |
From scores to probabilities
| Class | Raw score | Probability |
|---|---|---|
| T-shirt | 2.0 | 65.9% |
| Trouser | 1.0 | 24.2% |
| Sneaker | 0.1 | 9.9% |
- Sum of e^score
- 11.21
- Probabilities add up to
- 100%
- Largest
- T-shirt
Two things are worth noticing. The probabilities compete: raising one score takes probability away from the others, because the total is fixed at 1. And only the gaps between scores matter. Adding the same amount to every score leaves the probabilities unchanged.
Cross-entropy: scoring the probabilities
Now we need a loss. Suppose the image really is a T-shirt. The network gave that class 65.9%. A perfect network would have given it 100%.
The idea from the logistic regression chapter carries over unchanged: look at the probability the network gave to the correct class, and take minus its logarithm. This loss is called
loss = minus the log of the probability given to the correct class
| Probability given to the correct class | 100% | 66% | 33% | 10% | 1% |
|---|---|---|---|---|---|
| Loss | 0 | 0.42 | 1.10 | 2.30 | 4.61 |
The loss is zero only for complete confidence in the right answer. It grows slowly at first and then steeply, so a confident wrong answer is punished far more than a hesitant one. The probabilities given to the wrong classes do not appear in the formula at all. They matter only because softmax makes them eat into the share left for the correct one.
How much the network is charged
| Class | Raw score | Probability |
|---|---|---|
| T-shirt | 2.0 | 65.9% |
| Trouser | 1.0 | 24.2% |
| Sneaker | 0.1 | 9.9% |
- Probability given to the correct class
- 65.9%
- Loss = −log of that
- 0.417
- Network would answer
- T-shirt (right)
For a batch of images the loss is the average over the batch. One number then summarises how the network is doing on all of them.
The correct class is often written as a list with a 1 in its position and 0 elsewhere, such as for T-shirt. That form is called
Loss is not accuracy
It is tempting to skip the loss and count correct answers. Accuracy is easier to understand, but it throws away information the loss keeps.
Two networks each classify three images. Both get the first two right and the third wrong. Here is the probability each gave to the correct class:
| Image 1 | Image 2 | Image 3 | Accuracy | Mean loss | |
|---|---|---|---|---|---|
| Network A | 90% | 80% | 40% | 2 of 3 | 0.415 |
| Network B | 55% | 50% | 30% | 2 of 3 | 0.832 |
Accuracy cannot tell them apart. The loss shows that A is sure when it is right and only narrowly wrong, while B is barely getting by.
There is a second, more practical reason to train on the loss. Nudge a weight slightly and the accuracy usually does not change at all, because no answer flips. It moves in jumps. The loss moves smoothly with every nudge, so it always has a slope to follow. Accuracy is what we report. Loss is what we optimise.
An untrained network with random weights gives three classes about a third each. What is its cross-entropy loss, roughly?
Which way should the scores move?
To improve the network we need the slope of the loss with respect to each raw score. Softmax followed by a logarithm looks as if it should give a messy derivative. It gives one of the tidiest results in machine learning:
slope for each score = its probability minus the truth (1 for the correct class, 0 for the others)
Here is the one-hot truth. Read it class by class. For the correct class, is negative: raising that score lowers the loss. For every wrong class, is positive: lowering that score lowers the loss. The size of each push is how far the probability is from where it should be.
A network gives one example the scores . The correct class is the first.
- Exponentials: , and . They add up to 24.45.
- Probabilities: divide each by the total, giving .
- Loss: the correct class got 0.11, so the loss is . That is high, because the network put most of its belief on the wrong class.
- Gradient: subtract the truth , giving .
The first score should rise, and it gets the biggest push. The second should fall by nearly as much. The third is barely touched, because the network was already giving it almost no probability.
Prediction minus truth
| Class | Raw score | Probability | Prob − truth |
|---|---|---|---|
| T-shirt | 0.5 | 16.3% | -0.837 |
| Trouser | 2.0 | 72.8% | +0.728 |
| Sneaker | 0.1 | 10.9% | +0.109 |
- Probability given to the correct class
- 16.3%
- Loss = −log of that
- 1.817
- Network would answer
- Trouser (wrong)
You have seen “prediction minus truth” twice before, for linear regression and for logistic regression. It appears again here, and it is the starting signal for training a whole network. The next chapter takes these three numbers and passes them backward through every layer, to find out how each weight should change.
For one image the probabilities are [0.7, 0.2, 0.1] and the correct class is the second. What is the gradient with respect to the three scores?
In code
Two new classes join the network. The full file is code/ch16_loss.py (run it in Colab).
import numpy as np
class Activation_Softmax:
def forward(self, inputs):
# Subtracting each row's largest score stops the exponential overflowing.
exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True))
self.output = exp_values / np.sum(exp_values, axis=1, keepdims=True)
class Loss_CategoricalCrossentropy:
def calculate(self, probabilities, y_true):
samples = len(probabilities)
clipped = np.clip(probabilities, 1e-7, 1 - 1e-7) # never take log(0)
correct_confidences = clipped[range(samples), y_true] # each row's correct class
return np.mean(-np.log(correct_confidences))
softmax = Activation_Softmax()
softmax.forward(np.array([[2.0, 1.0, 0.1]]))
print(np.round(softmax.output, 3)) # [[0.659 0.242 0.099]]
loss_function = Loss_CategoricalCrossentropy()
print(round(loss_function.calculate(softmax.output, [0]), 3)) # 0.417
Running the untrained two-layer network from the last chapter on 300 examples with three classes gives a loss of 1.099. That is , exactly what a network that knows nothing should score.
Key Takeaways
- The output layer gives one raw score per class. Softmax turns them into probabilities that add up to 1.
- Cross-entropy is minus the log of the probability given to the correct class.
- Loss changes smoothly with the weights and is what we train on. Accuracy moves in jumps and is what we report.
- The slope of the loss for each score is probability minus truth.
- An untrained network on classes should score about .
- Turn a set of scores into probabilities with softmax, by hand.
- Work out the cross-entropy loss for one example.
- Explain why a network is trained on loss and judged on accuracy.
- Write down the gradient of the loss for each score.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
Apply softmax to the scores . Then apply it to and compare the first probability with the sigmoid of 2.
Hint
Take to the power of each score, then divide each by their total.
Solution
For every exponential is 1 and the total is 3, so each probability is . Equal scores mean equal probabilities.
For the exponentials are 7.39 and 1, with a total of 8.39. The probabilities are .
The sigmoid of 2 is also 0.88. With two classes, softmax depends only on the difference between the two scores and gives exactly what the sigmoid gives for that difference.
A network gives the probabilities . What is the loss if the correct class is the second? What if it is the first? For the second case, write down the gradient for the three scores.
Hint
The loss is minus the logarithm of the probability of the correct class. The gradient is probabilities minus the one-hot truth.
Solution
If the second class is correct, the loss is .
If the first class is correct, the loss is , more than six times as much.
The gradient in that case is the probabilities minus the truth , which is . The first score should go up a lot, the second should come down a lot, and the third should come down a little.
What happens to the softmax probabilities if you add 5 to every score? What happens if you double every score?
Hint
Write out the softmax with and see what cancels.
Solution
Adding 5 changes nothing. Every exponential is multiplied by the same factor, , and so is their total. The factor cancels when you divide. Only the differences between scores matter.
Doubling makes the output sharper. The differences between scores double, so the largest score takes an even bigger share. Scores of give the leader 82%. Doubled, give it about 98%. This is why the size of a network’s weights affects how confident it is, and one reason large weights and overconfidence go together.
You build a network for 10 classes. Before any training, roughly what should its loss be? If the first loss you see is 8, what does that suggest?
Hint
With no training, each of the 10 classes gets about the same probability.
Solution
An untrained network with small random weights gives every class about the same probability, . The loss is then .
A loss of 8 means the correct class is getting a probability of about , roughly 0.0003. The network is confidently wrong before it has learned anything. The usual cause is starting weights that are far too large, which produce huge scores. It can also mean the labels do not line up with the outputs. Checking the first loss against costs nothing and catches both.
In the figure “From scores to probabilities”, note the three probabilities. Add 3 to every score and compare. Then raise only the highest score by 3 and compare again.
Hint
Softmax only sees the gaps between the scores.
Solution
Adding 3 to every score changes nothing. All the gaps between scores are the same as before, and the gaps are all that softmax uses.
Raising only the highest score by 3 widens its gap over the others, and its probability jumps towards 100% while the other two shrink, although their own scores did not move. The probabilities compete for a fixed total of 1.
Going further
Why the exponential?
Softmax needs to turn any number into a positive one while keeping the order, and many functions could do that. The exponential is chosen because it pairs with the logarithm in the loss: the two cancel, which is where the clean “probability minus truth” gradient comes from. With any other choice the derivative would be far messier.
Temperature
Dividing every score by a number before softmax changes how sharp the probabilities are. A small makes the largest score dominate; a large flattens them toward equal shares. Language models use this setting, under the name temperature, to control how adventurous their choice of next word is.
References and further reading
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 4 and 5, nnfs.io.
- A. Karpathy and others, CS231n notes: Linear classification, cs231n.github.io/linear-classify.
- S. J. D. Prince, Understanding Deep Learning, chapter 5. Free at udlbook.github.io/udlbook.