Deriving Cross-Entropy Loss From Likelihood
Build binary and multiclass cross-entropy from the probability of the data, compute gradients by hand and avoid numeric traps.
Key takeaways
- Maximizing the likelihood of independent labels is the same as minimizing the sum of negative log probabilities of those labels.
- Binary cross-entropy comes from the Bernoulli distribution, and the multiclass form from the categorical distribution.
- With sigmoid or softmax outputs, the gradient with respect to the scores is the predicted probability minus the target.
- Cross-entropy equals the entropy of the labels plus the KL divergence from the true distribution to the model.
- Libraries compute the loss from raw scores because taking the logarithm of a rounded probability can fail.
Cross-entropy loss is the negative logarithm of the probability your model gave to what actually happened, averaged over examples. It is not an arbitrary choice. If you treat a classifier's output as a probability and ask which parameters make the observed labels most probable, this loss is what you end up minimizing.
The derivation takes a few lines, and it explains the loss's behavior: why confident mistakes are punished heavily, why the gradient is so simple and why the numbers must be computed with care.
Start with the probability of one label
Let y be 0 or 1, and let the model output p, its probability that y = 1 given the input x. That is a Bernoulli model, and both cases fit in one expression.
P(y | x) = pʸ (1 − p)^(1 − y)
y = 1 gives p
y = 0 gives 1 − p The likelihood is the probability of the observed data viewed as a function of the model's parameters. If the labels are independent given their inputs, the likelihood of n of them is the product of n such terms.
From product to sum
A product of thousands of numbers below 1 underflows to zero in floating point, and its derivative is awkward. The logarithm turns it into a sum, and because the logarithm is increasing, it does not move the best parameters. Flip the sign so that smaller is better, and divide by n.
L = −(1/n) ∑ [ yᵢ ln pᵢ + (1 − yᵢ) ln(1 − pᵢ) ] That is binary cross-entropy, also called log loss, here with the natural logarithm. Its unit is the nat. With base 2 logarithms the unit is the bit, and every value is divided by ln 2.
A three-example calculation
| Label y | Predicted p | Probability given to the truth | Loss, −ln of it |
|---|---|---|---|
| 1 | 0.9 | 0.9 | 0.105 |
| 0 | 0.2 | 0.8 | 0.223 |
| 1 | 0.6 | 0.6 | 0.511 |
The likelihood is 0.9 × 0.8 × 0.6 = 0.432, and −ln 0.432 ≈ 0.839, which matches the sum of the last column. The mean loss is about 0.280.
Why confidence costs so much when wrong
The penalty −ln p is zero when the true label received probability 1, about 0.693 at 0.5, about 4.6 at 0.01 and about 13.8 at one in a million. It grows without bound.
That reflects the likelihood. A model that calls an observed event impossible assigns the whole dataset probability zero, whatever it did elsewhere. It also means a few mislabeled examples that the model confidently disagrees with can dominate the average.
Several classes
With K classes, the model outputs probabilities p₁ to p_K that sum to 1. Under a categorical distribution, the probability of the observed label is simply the entry for the true class. Writing the label as a one-hot vector t, with a 1 in the true position and 0 elsewhere:
loss for one example = −∑ₖ tₖ ln pₖ = −ln p_true Only the true class appears explicitly. The others matter because the probabilities share a fixed total: raising the true one forces the rest down. Models usually produce unrestricted scores z, called logits, and convert them with softmax, pₖ = exp(zₖ) / ∑ⱼ exp(zⱼ).
The gradient is prediction minus target
Substitute softmax into the loss.
loss = −z_true + ln ∑ⱼ exp(zⱼ)
∂ loss / ∂zₖ = −tₖ + exp(zₖ) / ∑ⱼ exp(zⱼ)
= pₖ − tₖ Take logits (2, 1, 0) with the first class true.
p ≈ (0.665, 0.245, 0.090)
loss = −ln 0.665 ≈ 0.408
gradient ≈ (−0.335, 0.245, 0.090) sums to zero A gradient step raises the true score and lowers the others in proportion to how much probability each one wrongly holds. The binary case with p = σ(z), the sigmoid, gives the same form, p − y. For a linear model the weight gradient is that error times the input, as in logistic regression.
Why not squared error?
You could minimize (p − y)² instead. Consider a confidently wrong case: z = −5 and y = 1, so p ≈ 0.0067.
| Loss | Derivative with respect to z | Value here |
|---|---|---|
| Cross-entropy | p − y | about −0.993 |
| Squared error | 2(p − y) p(1 − p) | about −0.013 |
The squared error gradient carries the factor p(1 − p), which nearly vanishes when the sigmoid saturates. The model is badly wrong and receives only a faint signal. Cross-entropy cancels that factor.
Squared error on probabilities, known as the Brier score, remains a sound evaluation measure. Both are proper scoring rules: in expectation they are minimized by reporting the true probability.
The information theory view
For a true distribution q over labels and a model distribution p, the cross-entropy is H(q, p) = −∑ q ln p. It splits in two.
H(q, p) = H(q) + KL(q ‖ p) H(q) is the entropy of the true labels, which no model can change. The second term is the KL divergence, which is zero only when p matches q. So the loss has a floor, and if labels are inherently uncertain that floor is above zero.
It also gives you baselines. Predicting the same probability for K balanced classes yields ln K, about 2.303 for ten classes. For a binary problem with 10% positives, always predicting 0.1 gives about 0.325. A trained model should beat the matching figure. If a new network's initial loss is far above it, inspect the initialization or the data.
Computing it safely
Evaluate the formula from logits with the log-sum-exp trick: subtract the largest score before exponentiating, which leaves the result unchanged and prevents overflow.
import numpy as np
def cross_entropy(Z, y): # Z: (n, K) logits, y: (n,) class ids
S = Z - Z.max(axis=1, keepdims=True)
logp = S - np.log(np.exp(S).sum(axis=1, keepdims=True))
n = len(y)
loss = -logp[np.arange(n), y].mean()
G = np.exp(logp) # (n, K) probabilities
G[np.arange(n), y] -= 1.0
return loss, G / n # gradient with respect to Z
print(cross_entropy(np.array([[2.0, 1.0, 0.0]]), np.array([0])))
print(cross_entropy(np.array([[1000.0, 0.0]]), np.array([1]))[0]) # 1000.0 Deep learning libraries provide fused losses of this kind. A frequent bug is applying softmax yourself and then passing the result to a function that expects logits, which trains slowly and to a worse loss without raising an error. Softmax stability goes further.
Variations and what they change
- Soft targets. Replace the one-hot vector with any distribution, and the gradient is still p − t. Distillation uses a teacher's probabilities this way.
- Label smoothing. Move a little target mass to other classes to discourage extreme logits, as described in label smoothing.
- Class weights. Weighting rare classes changes which errors the optimizer cares about. The outputs then no longer estimate the original class frequencies without a correction.
- Sequences. A language model applies the loss at each position, predicting the next token. The exponential of the mean loss in nats is the perplexity.
- Several labels at once. Use an independent binary loss per label, not softmax.
What the best prediction looks like
Suppose that among all cases with one particular input, a fraction r are positive. A model must give them all the same p. What value minimizes the expected loss?
expected loss(p) = −[ r ln p + (1 − r) ln(1 − p) ]
derivative = −r/p + (1 − r)/(1 − p)
set to zero → p = r The minimum sits at the true frequency, which is what it means for the loss to be proper. With r = 0.7, predicting 0.7 costs about 0.611 nats on average. Predicting a bolder 0.9 costs about 0.765, and predicting 0.5 costs about 0.693. Overconfidence here is worse than admitting complete ignorance.
This is an argument about the ideal. A real model shares parameters across inputs, sees finitely many cases and may stop training early or overtrain, so its p can sit well away from r.
Reading a loss curve
A loss value is easier to interpret when converted back to a probability. Exponentiating the negative mean loss gives the geometric mean of the probabilities assigned to the true labels. A mean loss of 0.105 corresponds to about 0.90, and 2.303 corresponds to 0.10.
Because it is an average, one number can hide very different behavior. A loss of 0.3 might mean every example gets about 0.74, or most get 0.95 while a few get nearly zero. Plot the distribution of per-example losses and read the worst ones. They often reveal mislabeled data, an unhandled input format or a subgroup the model has not learned.
Compare training and validation losses computed the same way. Label smoothing, class weights, dropout and an added weight penalty can all make the reported training number differ from the plain cross-entropy on held-out data.
What the derivation does not promise
Maximum likelihood finds the most probable parameters within your model family for your training sample. It does not guarantee good probabilities on new data. A flexible network can keep lowering training loss by growing more confident, while held-out loss rises even as accuracy holds steady.
The derivation also assumed that the labels are independent and that the data you train on resemble the data you will meet. Duplicated rows, repeated users or a shifted population break those assumptions without changing the formula.
Watch held-out loss alongside accuracy, and test calibration before using the outputs as probabilities in a decision.