Loss Functions & Maximum Likelihood
Squared error, cross-entropy and a recipe for choosing the right loss.
Why squared error for regression and cross-entropy for classification? Not convention: both fall out of one recipe. Decide what distribution the target follows given the input, let the network output that distribution's parameters, and maximize the likelihood of the data. The same recipe handles counts, multi-label outputs and outliers, and explains why you should never compute a softmax and then its logarithm.
What you’ll learn
- Derive losses by maximum likelihood: Gaussian → squared error, Laplace → absolute error, Bernoulli → binary cross-entropy, categorical → softmax cross-entropy, Poisson → Poisson loss.
- Derive the gradient of softmax cross-entropy with respect to the logits, , and explain why squared error on a sigmoid output learns slowly from confident mistakes.
- Decompose cross-entropy into entropy plus KL divergence, and compute the smallest achievable loss when labels are noisy.
- Compute losses stably from logits with log-sum-exp, and explain why log loss rewards calibrated probabilities while accuracy does not.
One recipe for every loss
Treat the network's output as the parameters of a conditional distribution : a mean, a probability, a vector of class probabilities, a rate. If the examples are drawn i.i.d., the likelihood of the training set is a product, and maximum likelihood means minimizing the average negative log-likelihood:
Suppose with and the network outputs . The negative log-density of one example is
With fixed, the second term is a constant and the first is a scaled squared error: maximum likelihood under Gaussian noise is least squares, the mean squared error.
Laplace noise, with density , has heavier tails. Its negative log-density gives the absolute error, which penalizes a large residual linearly instead of quadratically:
| Target | Distribution | Network outputs | Loss per example | Population minimizer |
|---|---|---|---|---|
| real number | Gaussian, fixed | mean | ||
| real, with outliers | Laplace, fixed | location | median of | |
| yes / no | Bernoulli | logit ; | ||
| one of classes | categorical | logits ; | for every | |
| any subset of labels | independent Bernoullis | logits | sum of binary cross-entropies | each label's probability |
| count | Poisson | ; rate | (plus ) |
You predict house prices, and the data contain a few extreme mansions that you do not want to dominate the fit. Under which assumed noise distribution does maximum likelihood give the loss least affected by them?
- Gaussian noise, giving squared error
- Laplace noise, giving absolute error
- Bernoulli noise, giving cross-entropy
- Poisson noise, giving the Poisson loss
Show the answer
B. Laplace noise, giving absolute error
The Laplace distribution has heavier tails, so a large residual costs only linearly. The resulting fit targets the conditional median, which a few extreme values barely move.
Cross-entropy and its gradient
For classes the network outputs logits , the softmax turns them into probabilities, and the loss for true class is
Differentiate each term with respect to logit . The first gives if and otherwise; the second is the softmax itself:
With one logit and a sigmoid, the binary cross-entropy simplifies to , and the same structure appears:
The error signal is predicted probability minus observed outcome, bounded in , and it vanishes only when the prediction is both right and confident. Squared error on a linear output and the Poisson loss with give and in the same way: each distribution paired with its natural ("canonical") link function has this property.
Now try squared error on a sigmoid output instead, . The chain rule adds a factor :
A binary classifier outputs logit for an example with . How many times larger is the cross-entropy gradient than the squared-error gradient ?
Show the answer
57 ×
The ratio is . With it is . At it is about : the more confidently wrong, the more squared error stalls.
What cross-entropy measures
For distributions (the truth) and (the model) over the same outcomes, the cross-entropy splits into two familiar pieces:
The minimum is therefore not zero unless the label is a deterministic function of the input. In the population the best possible loss is the conditional entropy . If a training loss falls far below that on noisy data, the network is memorizing the noise. Units: with natural logarithms the loss is in nats; divide by for bits. Language models report , the perplexity (Transformer Language Models).
In a binary task the clean label is a deterministic function of the input, but each recorded label is flipped at random with probability 0.2, independently of the input. What is the smallest expected binary cross-entropy any model can reach, in nats?
Show the answer
0.5
The best model gives the clean label probability (it cannot predict the flips), and its expected loss is the entropy nats. With 10% noise the floor is ; with no noise it is .
Computing it stably
Computed naively, softmax and then logarithm fails in floating point. With logits , overflows and the softmax returns NaN. With logits , underflows to in single precision, and the log-probability of the second class becomes instead of .
The fix is the log-sum-exp identity: subtract the largest logit before exponentiating. Every exponent is then at most , one term equals , and nothing overflows or takes the logarithm of zero:
The binary loss uses the same trick: .
import torch
import torch.nn.functional as F
logits = model(x) # (B, K) raw scores, no softmax
loss = F.cross_entropy(logits, y) # y: (B,) class indices; log-softmax + NLL, stable
# binary or multi-label: one logit per label
loss_bin = F.binary_cross_entropy_with_logits(logit, target.float())
# the same quantity by hand, stably
log_p = logits - torch.logsumexp(logits, dim=1, keepdim=True)
loss_manual = -log_p.gather(1, y.unsqueeze(1)).mean()
# wrong: unstable, and a softmax layer before F.cross_entropy applies softmax twice
bad = -torch.log(F.softmax(logits, dim=1)).gather(1, y.unsqueeze(1)).mean()Frameworks take logits so that they can fuse the logarithm and the softmax. Putting a softmax at the end of the model and then calling F.cross_entropy is a classic silent bug: the loss still decreases, but the probabilities it sees are squashed and the gradients are wrong (Diagnosing Training Failures).
Proper scores and calibration
Why train on log loss rather than on accuracy, apart from differentiability? Suppose the true probability of class 1 for some input is and the model reports . The expected log loss is minimized only at : log loss is a strictly proper scoring rule, and so is the Brier score (Gneiting & Raftery, 2007). It pays to report honest probabilities.
Accuracy is not strictly proper. It checks only which class gets the largest probability, so reporting or scores the same. A model chosen for accuracy alone has no reason to be calibrated, meaning that among predictions made with 80% confidence, about 80% are right.
Proper in expectation is not the same as calibrated in practice. A large network can drive its training cross-entropy toward zero, and its test predictions then tend to be overconfident; Guo et al. (2017) found modern networks noticeably worse calibrated than older, smaller ones. A one-parameter fix, temperature scaling, divides all logits by a scalar fitted on held-out data. It cannot change any prediction's argmax, so accuracy is untouched, while the confidences shrink toward the truth.
Key takeaways
- Choose a conditional distribution for the target and minimize its negative log-likelihood: Gaussian → squared error (conditional mean), Laplace → absolute error (median), Bernoulli and categorical → cross-entropy (probabilities), Poisson → Poisson loss (rates).
- For softmax cross-entropy, ; squared error on a sigmoid multiplies this by , which vanishes exactly when the network is confidently wrong.
- Cross-entropy entropy KL divergence, so its minimum is the labels' conditional entropy, not zero: a training loss far below it on noisy data signals memorization.
- Compute losses from logits with log-sum-exp (
F.cross_entropy,F.binary_cross_entropy_with_logits); never take the log of a softmax, and never feed a softmax into a loss that expects logits. - Log loss is a strictly proper scoring rule and accuracy is not; overfit networks are often overconfident, and temperature scaling recalibrates them without changing accuracy.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You assume with fixed . Maximum likelihood then minimizes which loss, and what does the trained estimate?
- Squared error; the conditional mean
- Absolute error; the conditional mean
- Squared error; the conditional median
- Absolute error; the conditional median
Show the answer
D. Absolute error; the conditional median
, and the minimizer of expected absolute error is the median.
A classifier's softmax output is and the true class is the second one. What is the gradient of the cross-entropy with respect to the logits?
Show the answer
B.
with . Gradient descent then lowers the first and third logits and raises the second.
In a binary task the clean label is determined by the input, but recorded labels are flipped with probability 0.1, independently of the input. What is the smallest expected cross-entropy any classifier can achieve?
- nats
- nats
- nats
Show the answer
D. nats
Cross-entropy is entropy plus KL. The KL term can reach zero, but the labels' own entropy, nats, cannot be removed.
Which PyTorch expression computes multiclass cross-entropy correctly and stably from a model's raw outputs logits?
F.cross_entropy(logits, y)F.cross_entropy(F.softmax(logits, dim=1), y)F.nll_loss(logits, y)-torch.log(F.softmax(logits, dim=1))[torch.arange(B), y].mean()
Show the answer
A. F.cross_entropy(logits, y)
F.cross_entropy expects unnormalized logits and applies a fused, stable log-softmax before the negative log-likelihood.
Why does maximizing accuracy give no pressure toward calibrated probabilities, while minimizing log loss does?
- Accuracy depends only on which class has the largest probability, so it is not a strictly proper scoring rule; log loss is uniquely minimized by the true probabilities
- Accuracy is measured on the test set and log loss on the training set
- Log loss is bounded and accuracy is not
- Accuracy can only be computed for two classes
Show the answer
A. Accuracy depends only on which class has the largest probability, so it is not a strictly proper scoring rule; log loss is uniquely minimized by the true probabilities
Strict propriety means the expected score is optimized only by reporting the true distribution. Log loss and the Brier score have it; accuracy, which ignores everything but the argmax, does not.
Go deeper
- Predicting Distributions, Not Points · Heteroscedastic regression, mixture density networks and proper scoring rules.
- Reshaping Cross-Entropy · Label smoothing, focal loss and logit adjustment for imbalanced data.
- Neural Collapse · The symmetric geometry that last-layer features converge to at the end of training.
Further reading
- S. J. D. Prince, Understanding Deep Learning, ch. 5 "Loss functions" (MIT Press, 2023).
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, §6.2 (MIT Press, 2016).
- T. Gneiting & A. E. Raftery, "Strictly proper scoring rules, prediction, and estimation," Journal of the American Statistical Association 102 (2007).
- C. Guo, G. Pleiss, Y. Sun & K. Q. Weinberger, "On calibration of modern neural networks," ICML (2017).