Foundations to Frontier
Tests
E. Deep Learning › E2 Loss Functions (one page each)

Negative log-likelihood

The negative log-likelihood (NLL) is the general recipe behind most losses: choose a probability model for the target, let the network output its parameters, and minimise −log p(y | x). Gaussian NLL gives MSE (plus a variance term), Laplace gives MAE, Bernoulli gives binary cross-entropy, categorical gives cross-entropy, and Poisson gives the count loss. This page covers the principle, the common distributions, learning a variance (heteroscedastic regression), its pitfalls and fixes, and PyTorch's nll_loss. In the exercises you derive the optimal variance and scale and implement several NLLs, then show that learning the variance gives prediction intervals with correct coverage where MSE's single variance over-covers quiet regions and under-covers noisy ones.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

One principle behind many losses

Instead of inventing a loss, describe what you believe about the data. “The target is the prediction plus Gaussian noise” or “the target is a count drawn from a Poisson distribution with this rate”. The network outputs the parameters of that distribution, and the loss is how surprised the model is by the real target: −log of the probability it assigned. Squared error, absolute error and cross-entropy all fall out of this one idea, and it also lets a network say how uncertain it is.

Learning the noise: Gaussian NLL versus MSE
95% band coverage on fresh points, left third / right third: MSE with one variance 1.00 / 0.81 · NLL with learned variance 0.91 / 0.96
Grey dashed band: mean ± 1.96σ with one shared σ from least squares. Orange band: the NLL model's mean ± 1.96σ(x), with σ learned as a function of x. When the noise differs across x, the shared band is too wide where the data are quiet (coverage near 1) and too narrow where they are noisy (coverage well below 0.95); the learned band tracks the noise and covers about 95% everywhere. Set both noise levels equal and the two bands agree.
Why engineers care

A navigation filter, a planner or a safety monitor needs to know not just a prediction but how far to trust it. Training with a Gaussian NLL and a learned variance gives each prediction its own error bar, wide in turbulence and narrow in calm air, for instance. The same principle gives the right loss for counts (detections, failures per hour), durations and directions.

📝 Quick check (Level 0)
0/3 answered
  1. 1. NLL measures…
  2. 2. Gaussian NLL with fixed variance reduces to…
  3. 3. Learning the variance lets the model…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Common NLLs by hand

model network outputs NLL per example
Gaussian mean μ, variance σ² ½ log(2πσ²) + (y − μ)²/(2σ²)
Laplace location μ, scale b log(2b) + |y − μ|/b
Bernoulli logit z BCE (E2-3)
categorical logits z cross-entropy (E2-4)
Poisson log-rate z (rate λ = eᶻ) λ − k·z + log k!
  • Gaussian with σ² = 1: NLL = ½(y − μ)² + ½ log 2π, which is MSE/2 plus a constant.
  • Examples:
    • Gaussian at y = 2, μ = 0, σ² = 4: ½ log 8π + ½ ≈ 2.112.
    • Poisson with λ = 1 and k = 3: 1 + log 6 ≈ 2.79.
  • Optimal variance: for fixed residuals rᵢ, the Gaussian NLL is minimised at σ² = mean(rᵢ²). The Laplace NLL is minimised at b = mean(|rᵢ|).
  • Parameterise positive outputs through log σ² or softplus (E1-7), never directly.
📝 Quick check (Level 1)
0/3 answered
  1. 1. The Poisson NLL uses the network output as…
  2. 2. For fixed residuals, the best Gaussian variance is…
  3. 3. The Laplace NLL corresponds to…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

NLLs in code

Exercise 1.

  • With fixed variance, a change in the Gaussian NLL equals half the change in MSE.
  • A grid search confirms the NLL-optimal Gaussian variance is the mean squared residual, and the Laplace scale the mean absolute residual.
  • The Poisson NLL matches −log(e^(−λ)λᵏ/k!).
  • PyTorch’s nll_loss picks −log p of the true class from log-probabilities.

Learning a variance in practice.

  • Output log σ² and clamp it. An unbounded log-variance lets the model drive σ² → 0 on points it fits exactly, and the NLL → −∞.
  • Warm up. Train the mean with MSE first, or start the variance large.
  • Watch the weighting. The NLL weights each point’s squared error by 1/σ², so points the model declares noisy contribute less to the mean. That is efficient when the variance is right, but it can let the model “give up” on hard regions. β-NLL (Seitzer et al., 2022) multiplies each term by a stop-gradient σ^(2β) to counter this.
  • Evaluate with test NLL and interval coverage, not only RMSE.
nn.GaussianNLLLoss(); nn.PoissonNLLLoss(log_input=True); F.nll_loss(log_probs, y)
🐍 Exercise 1: a family of NLLs
Implement Gaussian, Laplace and Poisson NLLs and the classification NLL from log-probabilities, and find the optimal Gaussian variance and Laplace scale.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why clamp the predicted log-variance?
  2. 2. In the Gaussian NLL, a point's squared error is weighted by…
  3. 3. β-NLL modifies the loss by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Maximum likelihood. For independent examples, the likelihood is ∏ p(yᵢ | xᵢ; θ), and minimising the average NLL maximises it. Under standard conditions the maximum-likelihood estimator is consistent and asymptotically efficient: it attains the Cramér–Rao bound. The choice of noise model encodes prior knowledge, and choosing it badly costs efficiency (E2-1).

NLL and KL divergence. The expected NLL under the data distribution is H(p_data) + KL(p_data ‖ p_model). Minimising NLL minimises the KL divergence from the data to the model, so NLL is a proper scoring rule for full predictive distributions, not just point predictions.

Heteroscedastic regression. Predicting both μ(x) and σ²(x) models noise that varies with x (Nix and Weigend, 1994). The mean’s gradient (μ − y)/σ² is the weighted least-squares gradient, which is optimal when σ² is the true noise variance. The variance’s gradient ½(1 − r²/σ²) pushes σ² toward the squared residual. The known failure mode is that, early in training, large residuals in hard regions are explained away by a large σ² instead of by improving μ, and those regions then learn slowly. Exercise 2 tests whether this happens on a simple problem.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Minimising expected NLL is equivalent to minimising…
  2. 2. Maximum-likelihood estimators are asymptotically…
  3. 3. Heteroscedastic regression was introduced for networks by…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Does learning the variance help or hurt?

History.

  • R. A. Fisher (1912, 1922) developed maximum likelihood.
  • D. Nix and A. Weigend (1994) trained networks to predict mean and variance.
  • A. Kendall and Y. Gal (2017) popularised learned aleatoric uncertainty in deep vision.
  • M. Seitzer et al. (2022) analysed the pitfalls of heteroscedastic NLL training and proposed β-NLL.

Exercise 2. A one-hidden-layer network (width 32) predicts a mean and a log-variance for y = sin(3x) + noise, whose standard deviation grows from 0.05 to 0.6 across x ∈ [−1, 1]. It is trained on 400 points by Adam for 1200 steps. There are three methods:

  • MSE, with one variance from the residuals afterwards;
  • Gaussian NLL;
  • β-NLL with β = 0.5.

The table gives values on 4000 test points, per seed.

metric MSE + one variance NLL β-NLL
RMSE of the mean, low-noise half 0.024, 0.041, 0.015 0.023, 0.040, 0.013 0.020, 0.041, 0.022
RMSE of the mean, high-noise half 0.052, 0.088, 0.079 0.031, 0.076, 0.066 0.040, 0.088, 0.079
test NLL 0.399, 0.416, 0.427 0.144, 0.147, 0.158 0.144, 0.152, 0.169
95% coverage, x < −0.5 1.000, 1.000, 1.000 0.934, 0.953, 0.956 0.946, 0.956, 0.970
95% coverage, x > 0.5 0.848, 0.856, 0.791 0.959, 0.983, 0.936 0.957, 0.981, 0.937
  • Learning the variance gave honest intervals. NLL’s 95% bands covered 93–98% of points in both regions. MSE’s single variance covered 100% where the data were quiet and only 79–86% where they were noisy.
  • The mean did not suffer. NLL fitted the mean better than MSE in the noisy half in all three seeds, and in three further seeds. Weighting by 1/σ² is efficient weighted least squares when the variance is right.
  • The known pathology did not appear here, so β-NLL brought no gain. That pathology is reported for harder fits and larger networks. Test NLL, coverage and per-region error are the measurements that would reveal it.
🐍 Exercise 2 (research): does learning the variance help or hurt?
Train a mean-and-variance network on heteroscedastic data with MSE (one variance), Gaussian NLL and β-NLL; compare per-region mean error, test NLL and 95% interval coverage.

NLL in AI, robotics and aerospace

  • Learned sensor models: networks predicting a measurement and its variance feed Kalman filters directly, so the filter can weight them properly.
  • Trajectory prediction: pedestrian and vehicle forecasters output Gaussian (or mixture) parameters and are trained with NLL, so planners get uncertainty.
  • Reliability: Poisson or other count NLLs model failure counts; survival-type NLLs model times to failure.

References

  1. R. A. Fisher (1922). “On the mathematical foundations of theoretical statistics.” Philosophical Transactions of the Royal Society A 222.
  2. D. A. Nix, A. S. Weigend (1994). “Estimating the mean and variance of the target probability distribution.” Proc. IEEE ICNN.
  3. A. Kendall, Y. Gal (2017). “What uncertainties do we need in Bayesian deep learning for computer vision?” Advances in NeurIPS 30.
  4. M. Seitzer, A. Tavakoli, D. Antic, G. Martius (2022). “On the pitfalls of heteroscedastic uncertainty estimation with probabilistic neural networks.” Proc. ICLR.