AI from scratch · Chapter 5

Probability and loss

So far our networks said "blue or red". Real ones choose among many answers: which digit, which animal, which of 100,000 words comes next. They don't output an answer; they output how much they believe in each one. This chapter is about those beliefs: how scores become probabilities, how to measure a wrong belief, and why a chatbot's reply can change every time you ask.

1. Scores become probabilities: softmax

The last layer of a network gives one raw score per answer, called a logit: any number, positive or negative. To turn scores into probabilities that are positive and add up to 1, we use softmax: raise e to each score, then divide by the total.

p(i) = escore(i) / T / Σ escore(j) / T

Drag the scores. Only the differences between them matter: add the same amount to all three and nothing changes. A score 2 higher means about 7 times more likely (e² ≈ 7.4). The temperature divides every score first: low temperature exaggerates the differences until the top answer takes everything; high temperature flattens them toward a coin flip.

The math, step by step

\[ p_i = \operatorname{softmax}(s)_i = \frac{e^{s_i / T}}{\sum_j e^{s_j / T}} \]

Worked example with the starting scores (2, 1, −0.5) and \(T = 1\): \(e^2 = 7.389\), \(e^1 = 2.718\), \(e^{-0.5} = 0.607\). They add up to 10.714, so the probabilities are \(7.389 / 10.714 = 0.690\), then 0.254 and 0.057. Every one positive, total exactly 1.

Why only differences matter. Add the same \(c\) to every score: each \(e^{s_i + c} = e^c \cdot e^{s_i}\), and the \(e^c\) appears on top and in every term of the bottom, so it cancels. Programs use this to stay safe: \(e^{1000}\) overflows to infinity, so they subtract the largest score first, which changes nothing mathematically and keeps every exponent ≤ 0.

The ratio rule. \(p_i / p_j = e^{(s_i - s_j)/T}\). A score 1 higher means \(e \approx 2.7\) times likelier; 2 higher, 7.4 times. As \(T \to 0\) the ratio explodes and the top score takes all; as \(T \to \infty\) every ratio goes to 1, a uniform guess.

Softmax turns scores into probabilities in which only differences count: each extra point of score multiplies the odds by \(e\), and temperature stretches or flattens the differences.

Why raise \(e\) to the scores, instead of just dividing by their total?
  1. Scores can be negative, and probabilities can't. Dividing each score by the total would give negative "probabilities", or divide by zero when they cancel. We need something that turns any number into a positive one, keeps the order, and turns differences into ratios.
  2. \(b^{s}\) for any base \(b > 1\) does all of that: \(b^{s_i} / b^{s_j} = b^{s_i - s_j}\), so a fixed score gap is a fixed odds ratio.
  3. Every base is the same machine with rescaled scores: \(b^{s} = e^{s \ln b}\). Choosing a base is choosing a temperature, and the network can learn any scale it likes. So the base doesn't matter for what the model can say.
  4. It matters for the slope. \(e\) is the base whose slope is itself (calculus 1), and that's what makes the gradient come out as the clean \(p - y\) in section 4. With any other base, a factor \(\ln b\) would tag along.

Two answers with scores \(0\) and \(\ln 3 \approx 1.099\), at \(T = 1\). What probability does the second one get?

\(e^0 = 1\) and \(e^{\ln 3} = 3\), so \(p_2 = 3 / (1 + 3) = 0.75\). A score gap of \(\ln 3\) means "3 times as likely".

You add 5 to all three scores. What happens to the probabilities?

Softmax only sees differences between scores. Try it with the sliders: drag all three the same amount.

2. Loss as surprise: cross-entropy

To train, we need a number for "how wrong was that belief?". The standard answer: look only at the probability the model gave to the right answer, p, and take −log p. That's the cross-entropy loss, also called surprise: 100% sure and right means zero surprise; 1% on the truth means a lot.

The curve shoots up near zero. That's on purpose: a model that's confidently wrong gets a huge loss, so its gradient is big and it changes a lot, while a model that's unsure gets a gentle push. It's the same log loss our single neuron used in chapter 3, now for any number of answers.

The math, step by step

For one example whose right answer is \(y\):

\[ L = -\ln p_y \qquad \text{(averaged over the whole training set)} \]

Why a logarithm? Training data has many examples, and the probability of getting all of them right is a product \(p_1 p_2 p_3 \cdots\), a number that underflows to zero after a few hundred. The log turns the product into a sum, \(\ln(p_1 p_2 \cdots) = \ln p_1 + \ln p_2 + \cdots\), and the minus sign turns "maximize the probability of the data" into "minimize a loss". Minimizing cross-entropy is maximum likelihood.

Units. With \(\log_2\) it's measured in bits: \(p = 1/2\) costs 1 bit, \(p = 1/4\) costs 2. A model guessing uniformly among \(V\) words has loss \(\ln V\) per word. Language models report perplexity \(= e^{L}\): "as unsure as choosing uniformly among this many words". A perplexity of 20 over a 50,000-word vocabulary means the model has narrowed the next word down enormously.

Cross-entropy charges \(-\ln\) of the probability given to the truth: nothing for confident and right, no upper limit for confident and wrong.

The model gives the right answer probability 0.25. How many bits of surprise is that?

\(-\log_2 0.25 = \log_2 4 = 2\). As surprising as calling two coin flips in a row.

An untrained language model spreads probability evenly over 50,000 words. What's its cross-entropy per word, in natural-log units (\(\ln\))? (Two decimals.)

\(-\ln(1/50{,}000) = \ln 50{,}000 \approx 10.82\). That's where training curves of language models start; good ones end around 2 to 3.

3. Why a model "guesses": sampling

A language model is this exact machine with one answer per word in its vocabulary. Given "The cat sat on the", it gives every word a probability. Then it has to pick one. Always picking the top word is called greedy; it's predictable and tends to repeat itself. Instead, models usually sample: roll a weighted die. Try it, and try the temperature.

The cat sat on the …

That's why the same question can get different answers, and why "temperature" is a setting in every chatbot API: near 0 it's careful and repetitive, higher it's creative and occasionally unhinged. The model doesn't "know" the next word; it knows a distribution, and the reply is one roll of the dice.

The math: how a computer rolls a weighted die

Lay the probabilities end to end on a line from 0 to 1: "mat" takes the first 0.45, "floor" the next 0.18, and so on. Draw a uniform random number \(u\) between 0 and 1, and pick the word whose stretch it lands in. Each word wins with exactly its probability, because that's the length of its stretch. (This is "inverse CDF sampling"; the running total is the cumulative distribution.)

Two common tweaks: top-k keeps only the \(k\) likeliest words, and top-p (nucleus) keeps the smallest set whose probabilities add up to \(p\), say 0.9. Both cut off the long tail of unlikely words before rolling, then renormalize so what's left adds up to 1.

Why does greedy decoding (always the top word) tend to get stuck repeating itself?

Repeating text raises the probability of repeating it again (the model has just seen it), and greedy has no randomness to escape the loop.

A model knows a distribution, not an answer. Sampling rolls the dice; temperature decides how loaded they are.

Where it breaks: probabilities that aren't beliefs

4. The gradient is "what you said minus what was true"

Here's the beautiful part. Put softmax and cross-entropy together and do the backprop from chapter 4, and the gradient for each score comes out as simply

∂loss / ∂score(i) = p(i) − (1 if i is the right answer, else 0)

The right answer's score gets pushed up by how much probability it was missing; every wrong answer gets pushed down by how much it took. Pick the right answer and train.

The math: where "p − y" comes from

Write the loss with the softmax spelled out (and \(T = 1\)):

\[ L = -\ln \frac{e^{s_y}}{\sum_j e^{s_j}} = -s_y + \ln \sum_j e^{s_j} \]

Differentiate with respect to one score \(s_i\). The first term gives \(-1\) if \(i\) is the right answer, else 0. The second is the log of a sum: its slope is (slope of the sum) / (the sum) \(= e^{s_i} / \sum_j e^{s_j}\), which is exactly \(p_i\). Together:

\[ \frac{\partial L}{\partial s_i} = p_i - y_i, \qquad y_i = \begin{cases} 1 & i \text{ is right} \\ 0 & \text{otherwise} \end{cases} \]

Those numbers always add up to zero (the probabilities add to 1, and so does \(y\)): whatever the right answer gains, the wrong ones lose. Chapter 3's neuron was the two-answer case of this same formula.

Probabilities for (cat, dog, bird) are (0.7, 0.2, 0.1), and the right answer is dog. What's the gradient for the three scores?

\(p - y = (0.7 - 0,\ 0.2 - 1,\ 0.1 - 0)\). Stepping against it lowers cat's score most, raises dog's, and lowers bird's a little. Note it adds to zero.

Every classifier and every language model is trained with exactly this push, on billions of examples. Later on the path we'll give networks eyes: convolutions, filters that slide over images.

All chapters: AI from scratch.

Last updated