Simple Algorithm
Deep Learning · Representation · 22 min

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, p−y\mathbf p-\mathbf y, 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 p(y∣x;θ)p(y\mid\mathbf x;\boldsymbol\theta): 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:

L(θ)=−1n∑i=1nlog⁡p(yi∣fθ(xi))\loss(\boldsymbol\theta)=-\frac1n\sum_{i=1}^n\log p\big(y_i\mid f_{\boldsymbol\theta}(\mathbf x_i)\big)
Every loss function in this lesson is this expression for some choice of distribution. Constants that do not depend on θ\boldsymbol\theta drop out.
DerivationRegression: Gaussian and Laplace noise
  1. −log⁡N(y;μ,σ2)=(y−μ)22σ2+12log⁡(2πσ2)-\log\mathcal N(y;\mu,\sigma^2)=\frac{(y-\mu)^2}{2\sigma^2}+\frac12\log(2\pi\sigma^2)

    Suppose y=μ(x)+εy=\mu(\mathbf x)+\varepsilon with ε∼N(0,σ2)\varepsilon\sim\mathcal N(0,\sigma^2) and the network outputs μ\mu. The negative log-density of one example is

  2. With σ\sigma 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.

  3. −log⁡Laplace⁡(y;μ,b)=∣y−μ∣b+log⁡(2b)-\log\operatorname{Laplace}(y;\mu,b)=\frac{\abs{y-\mu}}{b}+\log(2b)

    Laplace noise, with density 12be−∣y−μ∣/b\frac1{2b}e^{-\abs{y-\mu}/b}, has heavier tails. Its negative log-density gives the absolute error, which penalizes a large residual linearly instead of quadratically:

TargetDistributionNetwork outputsLoss per examplePopulation minimizer
real numberGaussian, fixed σ\sigmamean μ\mu12(y−μ)2\tfrac12(y-\mu)^2E[y∣x]\E[y\mid\mathbf x]
real, with outliersLaplace, fixed bblocation μ\mu∣y−μ∣\abs{y-\mu}median of y∣xy\mid\mathbf x
yes / noBernoullilogit zz; p=σ(z)p=\sigma(z)−ylog⁡p−(1−y)log⁡(1−p)-y\log p-(1-y)\log(1-p)P(y=1∣x)P(y=1\mid\mathbf x)
one of KK classescategoricallogits z\mathbf z; p=softmax⁡(z)\mathbf p=\softmax(\mathbf z)−log⁡py-\log p_yP(y=k∣x)P(y=k\mid\mathbf x) for every kk
any subset of KK labelsKK independent BernoullisKK logitssum of KK binary cross-entropieseach label's probability
count 0,1,2,…0,1,2,\dotsPoissonzz; rate λ=ez\lambda=e^zλ−ylog⁡λ\lambda-y\log\lambda (plus log⁡y!\log y!)E[y∣x]\E[y\mid\mathbf x]
The last column is what a perfectly flexible model trained on unlimited data would output: the loss decides which summary of p(y∣x)p(y\mid\mathbf x) the network learns. The categorical row is the cross-entropy with a one-hot target.
Check your understanding

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?

  1. Gaussian noise, giving squared error
  2. Laplace noise, giving absolute error
  3. Bernoulli noise, giving cross-entropy
  4. 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 KK classes the network outputs logits z∈RK\mathbf z\in\R^K, the softmax turns them into probabilities, and the loss for true class yy is

ℓ(z,y)=−log⁡ezy∑jezj=−zy+log⁡∑j=1Kezj\ell(\mathbf z,y)=-\log\frac{e^{z_y}}{\sum_je^{z_j}}=-z_y+\log\sum_{j=1}^Ke^{z_j}
DerivationThe gradient is prediction minus target
  1. ∂ℓ∂zk=−1[k=y]+ezk∑jezj=pk−yk⟹∇zℓ=p−y\frac{\partial\ell}{\partial z_k}=-\mathbf 1[k=y]+\frac{e^{z_k}}{\sum_je^{z_j}}=p_k-y_k\qquad\Longrightarrow\qquad\nabla_{\mathbf z}\ell=\mathbf p-\mathbf y

    Differentiate each term with respect to logit zkz_k. The first gives −1-1 if k=yk=y and 00 otherwise; the second is the softmax itself:

  2. ∂ℓ∂z=σ(z)−y\frac{\partial\ell}{\partial z}=\sigma(z)-y

    With one logit and a sigmoid, the binary cross-entropy simplifies to ℓ=log⁡(1+ez)−yz\ell=\log(1+e^z)-yz, and the same structure appears:

  3. The error signal is predicted probability minus observed outcome, bounded in [−1,1][-1,1], and it vanishes only when the prediction is both right and confident. Squared error on a linear output and the Poisson loss with λ=ez\lambda=e^z give μ−y\mu-y and λ−y\lambda-y 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, ℓ=12(σ(z)−y)2\ell=\tfrac12(\sigma(z)-y)^2. The chain rule adds a factor σ′(z)=σ(1−σ)\sigma'(z)=\sigma(1-\sigma):

∂∂z 12(σ(z)−y)2=(σ(z)−y) σ(z)(1−σ(z))\frac{\partial}{\partial z}\,\tfrac12\big(\sigma(z)-y\big)^2=\big(\sigma(z)-y\big)\,\sigma(z)\big(1-\sigma(z)\big)
When the network is confidently wrong, say y=1y=1 and σ(z)≈0\sigma(z)\approx0, the factor σ(1−σ)\sigma(1-\sigma) is nearly zero: the worst mistakes produce the weakest gradients. Cross-entropy's logarithm cancels exactly this factor.
Predict before you look

A binary classifier outputs logit z=−4z=-4 for an example with y=1y=1. How many times larger is the cross-entropy gradient ∣σ(z)−y∣\abs{\sigma(z)-y} than the squared-error gradient ∣(σ(z)−y) σ(z)(1−σ(z))∣\abs{(\sigma(z)-y)\,\sigma(z)(1-\sigma(z))}?

Show the answer

57 ×

The ratio is 1/(σ(z)(1−σ(z)))1/\big(\sigma(z)(1-\sigma(z))\big). With σ(−4)≈0.018\sigma(-4)\approx0.018 it is 1/(0.018×0.982)≈571/(0.018\times0.982)\approx57. At z=−5z=-5 it is about 150150: the more confidently wrong, the more squared error stalls.

What cross-entropy measures

For distributions pp (the truth) and qq (the model) over the same outcomes, the cross-entropy splits into two familiar pieces:

H(p,q)=Ey∼p[−log⁡q(y)]=−∑yp(y)log⁡p(y)⏟H(p)+∑yp(y)log⁡p(y)q(y)⏟DKL(p ∥ q) ≥ H(p)H(p,q)=\E_{y\sim p}\big[-\log q(y)\big]=\underbrace{-\sum_yp(y)\log p(y)}_{H(p)}+\underbrace{\sum_yp(y)\log\frac{p(y)}{q(y)}}_{\KL(p\,\|\,q)}\ \ge\ H(p)
DKL(p ∥ q)\KL(p\,\|\,q) is non-negative and zero only when q=pq=p (Gibbs' inequality). So minimizing cross-entropy over qq is minimizing the KL divergence from the truth, and the best achievable value is the entropy of the labels themselves.

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 Ex H(p(y∣x))\E_{\mathbf x}\,H\big(p(y\mid\mathbf x)\big). 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 ln⁡2\ln2 for bits. Language models report exp⁡(loss)\exp(\text{loss}), the perplexity (Transformer Language Models).

Predict before you look

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 0.80.8 (it cannot predict the flips), and its expected loss is the entropy H(0.8)=−0.8ln⁡0.8−0.2ln⁡0.2≈0.179+0.322=0.500H(0.8)=-0.8\ln0.8-0.2\ln0.2\approx0.179+0.322=0.500 nats. With 10% noise the floor is 0.3250.325; with no noise it is 00.

Computing it stably

Computed naively, softmax and then logarithm fails in floating point. With logits (1000,0)(1000,0), e1000e^{1000} overflows and the softmax returns NaN. With logits (0,−200)(0,-200), e−200≈1.4×10−87e^{-200}\approx1.4\times10^{-87} underflows to 00 in single precision, and the log-probability of the second class becomes −∞-\infty instead of −200-200.

The fix is the log-sum-exp identity: subtract the largest logit m=max⁡jzjm=\max_jz_j before exponentiating. Every exponent is then at most 00, one term equals 11, and nothing overflows or takes the logarithm of zero:

log⁡∑jezj=m+log⁡∑jezj−m,log⁡py=zy−m−log⁡∑jezj−m.\log\sum_je^{z_j}=m+\log\sum_je^{z_j-m},\qquad \log p_y=z_y-m-\log\sum_je^{z_j-m}.

The binary loss uses the same trick: ℓ=max⁡(z,0)−yz+log⁡(1+e−∣z∣)\ell=\max(z,0)-yz+\log\big(1+e^{-\abs z}\big).

python
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 pp and the model reports qq. The expected log loss −plog⁡q−(1−p)log⁡(1−q)-p\log q-(1-p)\log(1-q) is minimized only at q=pq=p: log loss is a strictly proper scoring rule, and so is the Brier score (q−y)2(q-y)^2 (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 0.510.51 or 0.990.99 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 TT 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, ∇zℓ=p−y\nabla_{\mathbf z}\ell=\mathbf p-\mathbf y; squared error on a sigmoid multiplies this by σ(1−σ)\sigma(1-\sigma), 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.

Question 1

You assume y∣x∼Laplace⁡(μ(x),b)y\mid\mathbf x\sim\operatorname{Laplace}(\mu(\mathbf x),b) with fixed bb. Maximum likelihood then minimizes which loss, and what does the trained μ\mu estimate?

  1. Squared error; the conditional mean
  2. Absolute error; the conditional mean
  3. Squared error; the conditional median
  4. Absolute error; the conditional median
Show the answer

D. Absolute error; the conditional median

−log⁡Laplace⁡(y;μ,b)=∣y−μ∣/b+const-\log\operatorname{Laplace}(y;\mu,b)=\abs{y-\mu}/b+\text{const}, and the minimizer of expected absolute error is the median.

Question 2

A classifier's softmax output is p=(0.7,0.2,0.1)\mathbf p=(0.7,0.2,0.1) and the true class is the second one. What is the gradient of the cross-entropy with respect to the logits?

  1. (−0.3, 0.2, 0.1)(-0.3,\ 0.2,\ 0.1)
  2. (0.7, −0.8, 0.1)(0.7,\ -0.8,\ 0.1)
  3. (0.7, 0.2, 0.1)(0.7,\ 0.2,\ 0.1)
  4. (0, −0.8, 0)(0,\ -0.8,\ 0)
Show the answer

B. (0.7, −0.8, 0.1)(0.7,\ -0.8,\ 0.1)

∇zℓ=p−y\nabla_{\mathbf z}\ell=\mathbf p-\mathbf y with y=(0,1,0)\mathbf y=(0,1,0). Gradient descent then lowers the first and third logits and raises the second.

Question 3

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?

  1. 00
  2. 0.10.1 nats
  3. ln⁡2≈0.693\ln2\approx0.693 nats
  4. H(0.1)≈0.325H(0.1)\approx0.325 nats
Show the answer

D. H(0.1)≈0.325H(0.1)\approx0.325 nats

Cross-entropy is entropy plus KL. The KL term can reach zero, but the labels' own entropy, H(0.1)=−0.1ln⁡0.1−0.9ln⁡0.9≈0.325H(0.1)=-0.1\ln0.1-0.9\ln0.9\approx0.325 nats, cannot be removed.

Question 4

Which PyTorch expression computes multiclass cross-entropy correctly and stably from a model's raw outputs logits?

  1. F.cross_entropy(logits, y)
  2. F.cross_entropy(F.softmax(logits, dim=1), y)
  3. F.nll_loss(logits, y)
  4. -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.

Question 5

Why does maximizing accuracy give no pressure toward calibrated probabilities, while minimizing log loss does?

  1. 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
  2. Accuracy is measured on the test set and log loss on the training set
  3. Log loss is bounded and accuracy is not
  4. 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

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).