Skip to the content

fatehi.devx2Learning

Deep learning

Cross-entropy

The loss of a model that gives probabilities: minus the log of the probability it gave the right answer, averaged.

Scoring a probability

A model that ends in a softmax does not give one answer; it gives a probability to each possible answer. To train it, a loss must say how good those probabilities were, given the answer that was right. The cross-entropy loss looks only at one number, the probability p the model gave the right answer, and takes minus its logarithm.

L=−1T∑t=1Tlnpt(yt)

yt is the right token at position t and pt(yt) the probability the model gave it; the loss is averaged over the T positions of the batch.

Certain and right, p = 1, costs −ln 1 = 0. p = 0.5 costs 0.69, p = 0.1 costs 2.3, and the cost grows without limit as p nears 0: the loss measures surprise, and a confident mistake is punished hard.

Writing a sentence word by word: the model’s probabilities, the right word marked, and its loss read off the curve −ln p.

Why this loss

Minimising it is the same as making the training data as probable as possible under the model (maximum likelihood): the product of the probabilities of the right answers becomes, after the logarithm, a sum. It is the cross-entropy between the target distribution, all weight on the right answer, and the model’s. Together with the softmax its gradient with respect to the scores is very simple: the model’s probabilities minus the target, so every wrong option is pushed down by as much as it was given and the right one pulled up. Its average, raised as eL, is the perplexity: as if the model were choosing evenly among that many options at each step.

Test yourself

  1. What is the loss when the model gives the right word probability 0.5? And 0.01?

    −ln 0.5 = 0.69 and −ln 0.01 = 4.6.

  2. Does the cross-entropy loss look at the probabilities of the wrong words?

    Not directly, only at the right word’s probability; but since the softmax’s probabilities add up to 1, raising it lowers the others, and the gradient pushes each wrong word down by its probability.

  3. A perplexity of 4.92 means what, roughly?

    On average the model is as uncertain as if it chose evenly among about five tokens at each step.

Where it leads

Kept in this browser only, never sent.

Paths through it