MoonSay /Tutorials/Machine Learning Interview #7
Contents
  1. 01Introduction
  2. 02What a loss function does
  3. 03Squared error
  4. 04Absolute error and Huber loss
  5. 05Cross-entropy
  6. 06Why not squared error for classification?
  7. 07Hinge loss
  8. 08Choosing a loss
  9. 09Interview questions and model answers
  10. 10Summary
  11. References
Loss Functions/Chapter 05 of 10

05Cross-entropy: the loss for probabilities

5.1Binary cross-entropy from the Bernoulli likelihood

For a yes-or-no label y\in\{0,1\} (spam or not, click or not), the model outputs a logit z and a probability p=\sigma(z) that y=1. The Bernoulli likelihood of the observed label is p^y(1-p)^{1-y}, and its negative log (2) is the binary cross-entropy, also called the log loss:

\ell_{\text{CE}}(y,p)=-\bigl[\,y\log p+(1-y)\log(1-p)\,\bigr]. \tag{7}

Only one term survives: the loss is -\log of the probability the model gave to what actually happened. Table 1 shows how it behaves. Confident and right costs almost nothing; unsure costs 0.69; confident and wrong costs a lot, and the loss goes to infinity as the probability of the true answer goes to zero.

Probability given to the true answer0.990.90.50.10.01
Cross-entropy -\log p0.0100.1050.6932.3034.605
Table 1. The cost of a prediction under cross-entropy. Computed for this tutorial.

5.2The gradient is p-y

Differentiate (7) with respect to the logit z using d\sigma/dz=\sigma(1-\sigma):

\frac{\partial\ell_{\text{CE}}}{\partial z}=\underbrace{\Bigl(-\frac yp+\frac{1-y}{1-p}\Bigr)}_{\partial\ell/\partial p\;=\;\frac{p-y}{p(1-p)}}\;\underbrace{p(1-p)}_{\partial p/\partial z}=p-y . \tag{8}

The factor p(1-p) cancels: the log in the loss undoes the exponential in the sigmoid (Goodfellow et al., 2016, §6.2.2.2). The pull is simply the error in probability, between -1 and 1. It is largest when the model is confidently wrong and vanishes only when the prediction is right. For logistic regression, z=w^\top x, the gradient of the total loss is \sum_n(p_n-y_n)x_n and the loss is convex in w (Murphy, 2022, §10.2.3).

5.3Many classes: softmax and categorical cross-entropy

For C classes (cat, dog, fox; or every word in a vocabulary) the model outputs logits z_1,\dots,z_C and the softmax turns them into probabilities:

p_k=\frac{e^{z_k}}{\sum_{j=1}^Ce^{z_j}},\qquad k=1,\dots,C . \tag{9}

With the label c written as a one-hot vector y (y_c=1, all other entries 0), the categorical cross-entropy is

\ell_{\text{CE}}=-\sum_{k=1}^Cy_k\log p_k=-\log p_c=-z_c+\log\sum_{j=1}^Ce^{z_j}. \tag{10}

The last form makes the gradient a one-line computation: \partial(-z_c)/\partial z_k is -1 if k=c and 0 otherwise, and \partial\log\sum_je^{z_j}/\partial z_k=e^{z_k}/\sum_je^{z_j}=p_k. Hence

\frac{\partial\ell_{\text{CE}}}{\partial z_k}=p_k-y_k,\qquad\text{in vector form}\quad\nabla_z\ell_{\text{CE}}=p-y, \tag{11}

the same formula as in the binary case (Murphy, 2022, §10.3.2). The true class’s logit is pushed up by 1-p_c, every other logit is pushed down by its probability.

Worked example 3 (A photo: cat, dog or fox?). A classifier outputs logits z=(2.0,\,1.0,\,0.1) for (cat, dog, fox), and the photo is a cat. The exponentials are 7.389, 2.718 and 1.105, with sum 11.21, so p=(0.659,\,0.242,\,0.099). The loss is -\log 0.659=0.417, and the gradient is p-y=(-0.341,\,0.242,\,0.099): raise the cat logit, lower the other two in proportion to how much probability they took.

In practice the loss is computed directly from the logits with (10), subtracting \max_jz_j inside the log-sum-exp so that no exponential overflows. This is why deep learning libraries ask for logits rather than probabilities (Murphy, 2022, §10.3.3).

5.4Large language models: cross-entropy on the next word

A large language model is a classifier whose classes are the words (more precisely, tokens) of its vocabulary. Given the text so far, it outputs a logit for every token, a softmax (9) turns the logits into a probability distribution over the next token, and training minimizes the cross-entropy of the token that actually comes next, summed over every position of every training text:

\mathcal L(\theta)=-\sum_{t}\log p_\theta\bigl(w_t\mid w_1,\dots,w_{t-1}\bigr). \tag{12}

This is exactly (10), applied once per word. The GPT model of Radford et al. (2018) maximizes the same log-likelihood (their eq. 1) with a softmax output over a vocabulary built from 40{,}000 byte-pair merges, trained on over 7{,}000 books. Later, larger models changed the data and the size, not the loss. For “The cat sat on the …”, a model that gives the true next word “mat” probability 0.56 pays -\log0.56=0.58 for that position (an illustrative number).

Language models are usually reported by their perplexity, the exponential of the average cross-entropy per token, \exp(\mathcal L/T) for T tokens. A perplexity of K means the model is, on average, as uncertain as if it were choosing uniformly among K words; a perfect model has perplexity 1 (Murphy, 2022, §6.1.5).

5.5Honest probabilities: a proper scoring rule

Why -\log p and not some other function of the probability? Suppose the true probability of rain tomorrow is p and a forecaster announces q. The expected cross-entropy is

\E_{y\sim p}\bigl[-\log q_y\bigr]=-\sum_kp_k\log q_k=\underbrace{-\sum_kp_k\log p_k}_{H(p)}+\underbrace{\sum_kp_k\log\frac{p_k}{q_k}}_{D_{\mathrm{KL}}(p\,\|\,q)\;\ge\;0}, \tag{13}

which is smallest exactly when q=p, because the Kullback–Leibler divergence is zero only then. A loss with this property is a proper scoring rule: the forecaster does best by reporting what they truly believe (Murphy, 2022, §5.1.6). With p=0.7, forecasting 0.7 costs 0.611 on average, while the more “confident” 0.9 costs 0.765 and the timid 0.5 costs 0.693. The Brier (1950) score, the squared error (q-y)^2 between a probability and the outcome, is also proper: its expected value p(1-q)^2+(1-p)q^2 has derivative -2p(1-q)+2(1-p)q=2(q-p), zero at q=p. It is still used to verify weather forecasts. Cross-entropy punishes confident mistakes far more than the Brier score does, which is why it gives much stronger gradients (next section).

(a) Cross-entropy as a function of the probability given to the true answer. (b) The size of the gradient with respect to the logit for a sigmoid output when the true label is 1: cross-entropy |p-y| against squared error |2(p-y)\,p(1-p)| (log scale). At z=-5 the model is confidently wrong, and squared error pushes about 75 times more weakly. Computed for this tutorial.
Figure 4. (a) Cross-entropy as a function of the probability given to the true answer. (b) The size of the gradient with respect to the logit for a sigmoid output when the true label is 1: cross-entropy |p-y| against squared error |2(p-y)\,p(1-p)| (log scale). At z=-5 the model is confidently wrong, and squared error pushes about 75 times more weakly. Computed for this tutorial.
Try itHow hard does each loss push?

A sigmoid classifier, true label y=1. Move the logit z. The gradient with respect to z is p-y for cross-entropy, equation (8), and 2(p-y)\,p(1-p) for squared error, equation (14).

Pause and think. A classifier predicts probability 0 for the true class of one training example. What is its cross-entropy, and what does a library do about it?

Show the answer

-\log 0=\infty: one such example makes the average loss infinite. Libraries never form \log p from a rounded probability; they compute -z_c+\log\sum_je^{z_j} from the logits (10), which is finite for any finite logits.