Chapter 16 // Neural Networks

Scoring a Classifier.

A network outputs three numbers. How do we say how wrong they are?

Reading time
14 min

The network from takes an input, passes it through its layers, and produces one number per class. Its weights are random, so the numbers are nonsense. Before we can improve them we need a precise way to say how bad they are. That takes two steps: turn the numbers into probabilities, then score the probabilities against the truth.

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:

[ 2.0,  1.0,  0.1 ][\,2.0,\ \ 1.0,\ \ 0.1\,]

These raw scores are called . Bigger means “more likely this class”, so the network’s answer here is the first class, T-shirt.

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 . It works in two moves.

  1. Make every score positive by raising ee to its power. Larger scores become much larger, and negative scores become small positive numbers.
  2. Divide each by the total, so that they add up to 1.
pj=esj∑keskp_j = \frac{e^{s_j}}{\sum_k e^{s_k}}

probability of class j = e to its score, divided by the sum of e to every score

ExampleSoftmax by hand

For the scores [2.0, 1.0, 0.1][2.0,\ 1.0,\ 0.1]:

ClassScoreescoree^{\text{score}}Divided by the total, 11.21
T-shirt2.07.3965.9%
Trouser1.02.7224.2%
Sneaker0.11.119.9%
Figure

From scores to probabilities

ClassRaw scoreProbability
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
Each row is one class. The bar shows the probability softmax assigns to it. Try it: raise one score and watch the other two probabilities fall, although their scores did not change. Then add 3 to all three scores and see what happens.

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 .

L=−log⁡(pcorrect)L = -\log\big(p_{\text{correct}}\big)

loss = minus the log of the probability given to the correct class

Probability given to the correct class100%66%33%10%1%
Loss00.421.102.304.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.

Figure

How much the network is charged

ClassRaw scoreProbability
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)
The orange bar is the correct class. The loss depends only on the length of that bar. Try it: choose which class is correct and read the loss. Then drag the scores until the network is confidently wrong, and watch the loss climb.

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 [1,0,0][1, 0, 0] for T-shirt. That form is called , and it will be convenient in a moment.

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.

ExampleSame accuracy, different loss

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 1Image 2Image 3AccuracyMean loss
Network A90%80%40%2 of 30.415
Network B55%50%30%2 of 30.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.

Checkpoint

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:

∂L∂sj=pj−yj\frac{\partial L}{\partial s_j} = p_j - y_j

slope for each score = its probability minus the truth (1 for the correct class, 0 for the others)

Here yy is the one-hot truth. Read it class by class. For the correct class, p−1p - 1 is negative: raising that score lowers the loss. For every wrong class, p−0p - 0 is positive: lowering that score lowers the loss. The size of each push is how far the probability is from where it should be.

ExampleFrom scores to gradient, start to finish

A network gives one example the scores [1, 3, 0.5][1,\ 3,\ 0.5]. The correct class is the first.

  1. Exponentials: e1≈2.72e^{1} \approx 2.72, e3≈20.09e^{3} \approx 20.09 and e0.5≈1.65e^{0.5} \approx 1.65. They add up to 24.45.
  2. Probabilities: divide each by the total, giving [0.11, 0.82, 0.07][0.11,\ 0.82,\ 0.07].
  3. Loss: the correct class got 0.11, so the loss is −ln⁡(0.11)≈2.20-\ln(0.11) \approx 2.20. That is high, because the network put most of its belief on the wrong class.
  4. Gradient: subtract the truth [1, 0, 0][1,\ 0,\ 0], giving [−0.89, 0.82, 0.07][-0.89,\ 0.82,\ 0.07].

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.

Figure

Prediction minus truth

ClassRaw scoreProbabilityProb − 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)
The last column is the slope of the loss for each score. Positive means the score should come down. Try it: make the network confidently right and watch all three numbers shrink toward zero. Then make it confidently wrong and see which score gets the biggest push.

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.

Checkpoint

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 log⁡3\log 3, 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 kk classes should score about log⁡k\log k.
You can now
  • 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.

Exerciseby hand

Apply softmax to the scores [0, 0, 0][0,\ 0,\ 0]. Then apply it to [2, 0][2,\ 0] and compare the first probability with the sigmoid of 2.

Hint

Take ee to the power of each score, then divide each by their total.

Solution

For [0, 0, 0][0,\ 0,\ 0] every exponential is 1 and the total is 3, so each probability is 1/31/3. Equal scores mean equal probabilities.

For [2, 0][2,\ 0] the exponentials are 7.39 and 1, with a total of 8.39. The probabilities are [0.88, 0.12][0.88,\ 0.12].

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.

Exerciseby hand

A network gives the probabilities [0.1, 0.7, 0.2][0.1,\ 0.7,\ 0.2]. 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 −ln⁡(0.7)≈0.36-\ln(0.7) \approx 0.36.

If the first class is correct, the loss is −ln⁡(0.1)≈2.30-\ln(0.1) \approx 2.30, more than six times as much.

The gradient in that case is the probabilities minus the truth [1, 0, 0][1,\ 0,\ 0], which is [−0.9, 0.7, 0.2][-0.9,\ 0.7,\ 0.2]. The first score should go up a lot, the second should come down a lot, and the third should come down a little.

Exercisethink

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 es+5=es×e5e^{s + 5} = e^{s} \times e^{5} and see what cancels.

Solution

Adding 5 changes nothing. Every exponential is multiplied by the same factor, e5e^5, 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 [1, 3, 0.5][1,\ 3,\ 0.5] give the leader 82%. Doubled, [2, 6, 1][2,\ 6,\ 1] 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.

Exercisethink

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, 1/101/10. The loss is then −ln⁡(0.1)=ln⁡10≈2.30-\ln(0.1) = \ln 10 \approx 2.30.

A loss of 8 means the correct class is getting a probability of about e−8e^{-8}, 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 ln⁡k\ln k costs nothing and catches both.

Exercisewith the figure

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 TT before softmax changes how sharp the probabilities are. A small TT makes the largest score dominate; a large TT 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

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 16.1Three raw scores
  3. 16.2Softmax: scores into probabilities
  4. 16.3Cross-entropy: scoring the probabilities
  5. 16.4Loss is not accuracy
  6. 16.5Which way should the scores move?
  7. 16.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in