# Chapter 16: Scoring a Classifier

> Softmax and cross-entropy: turning outputs into a loss. Opening question: A network outputs three numbers. How do we say how wrong they are?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/scoring-a-classifier/

The network from [the last chapter](https://thebookofml.com/layers-and-activations/) 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\,]
$$

These raw scores are called logits. 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 softmax. It works in two moves.

1. **Make every score positive** by raising $e$ 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.

$$
p_j = \frac{e^{s_j}}{\sum_k e^{s_k}}
$$

**Example: Softmax by hand**

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

| Class | Score | $e^{\text{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% |

> **Interactive figure: From scores to probabilities.** 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.
> (Use it at https://thebookofml.com/scoring-a-classifier/)

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.

**Note:** With two classes, softmax reduces to the sigmoid from [the logistic regression chapter](https://thebookofml.com/logistic-regression/). Softmax is the same idea for any number of classes.

## 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 cross-entropy.

$$
L = -\log\big(p_{\text{correct}}\big)
$$

| 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.

> **Interactive figure: How much the network is charged.** 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.
> (Use it at https://thebookofml.com/scoring-a-classifier/)

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]$ for T-shirt. That form is called one-hot, 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.

**Example: Same 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 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.

**Check your understanding:** An untrained network with random weights gives three classes about a third each. What is its cross-entropy loss, roughly?

- 0, because it has not made any confident mistakes — The loss is zero only when the correct class gets 100%. Here it gets about 33%.
- About 1.10, which is −log(1/3) **(correct)** — Each correct class gets about a third, and −log(1/3) ≈ 1.10. Seeing this number at the start of training is a good sign the code is working.
- About 0.33 — That is the probability, not the loss. The loss is minus its logarithm.

## 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:

$$
\frac{\partial L}{\partial s_j} = p_j - y_j
$$

Here $y$ is the one-hot truth. Read it class by class. For the correct class, $p - 1$ is negative: raising that score lowers the loss. For every wrong class, $p - 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.

**Example: From scores to gradient, start to finish**

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

1. **Exponentials:** $e^{1} \approx 2.72$, $e^{3} \approx 20.09$ and $e^{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]$.
3. **Loss:** the correct class got 0.11, so the loss is $-\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]$, giving $[-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.

> **Interactive figure: Prediction minus truth.** 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.
> (Use it at https://thebookofml.com/scoring-a-classifier/)

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.

**Check your understanding:** 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?

- [0.7, −0.8, 0.1] **(correct)** — Probability minus one-hot truth: [0.7 − 0, 0.2 − 1, 0.1 − 0]. The correct class is pushed up, the others down.
- [−0.3, 0.2, 0.1] — That subtracts 1 from the first class, as if it were the correct one. The correct class is the second.
- [0.7, 0.2, 0.1] — That is the probabilities themselves. The truth has to be subtracted.

**Common mistake: Applying softmax twice**

In most libraries the loss function for classification applies the softmax itself, for the sake of numerical accuracy, and expects raw scores as its input. If your network already ends in a softmax, the probabilities get squashed a second time. Nothing crashes. The loss simply comes out higher than it should be and the network learns slowly, because a softmax of numbers between 0 and 1 can never be confident. Check what your loss function expects, and give it scores or probabilities accordingly.

## In code

Two new classes join the network. The full file is [ch16_loss.py](https://github.com/kamileren/quickproject/blob/master/code/ch16_loss.py).

```python
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$, 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 $k$ classes should score about $\log k$.

## What you should now be able to do

- 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

### Exercise (by hand)

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

**Hint:**

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

**Solution:**

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

For $[2,\ 0]$ the exponentials are 7.39 and 1, with a total of 8.39. The probabilities are $[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.

### Exercise (by hand)

A network gives the probabilities $[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) \approx 0.36$.

If the first class is correct, the loss is $-\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]$, which is $[-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.

### Exercise (think)

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

**Solution:**

**Adding 5 changes nothing.** Every exponential is multiplied by the same factor, $e^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]$ give the leader 82%. Doubled, $[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.

### Exercise (think)

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/10$. The loss is then $-\ln(0.1) = \ln 10 \approx 2.30$.

A loss of 8 means the correct class is getting a probability of about $e^{-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$ costs nothing and catches both.

### Exercise (with 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 $T$ before softmax changes how sharp the probabilities are. A small $T$ makes the largest score dominate; a large $T$ 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

- H. Kinsley and D. Kukieła, *Neural Networks from Scratch in Python*, chapters 4 and 5, [nnfs.io](https://nnfs.io).
- A. Karpathy and others, *CS231n notes: Linear classification*, [cs231n.github.io/linear-classify](https://cs231n.github.io/linear-classify/).
- S. J. D. Prince, *Understanding Deep Learning*, chapter 5. Free at [udlbook.github.io/udlbook](https://udlbook.github.io/udlbook/).

## Next

The network now knows how wrong it is, and which way each of its output scores should move. The weights that produced those scores are several layers back. The next chapter carries the message backwards to every one of them.
