Differentiate the Gaussian negative log-likelihood with respect to mean and log sigma

Why it matters Heteroscedastic regression, VAEs and probabilistic forecasters predict a mean and log sigma and train on exactly this loss and gradient.

Models that predict uncertainty often output a mean and a log standard deviation. Training them needs the gradient of the Gaussian negative log-likelihood.

Write gaussian_nll_grad(x, mu, log_sigma). x is a 1D array of observations; mu and log_sigma are scalars. With sigma = exp(log_sigma), the mean NLL is mean(0.5 log(2 pi) + log_sigma + (x - mu)^2 / (2 sigma^2)). Return (nll, d_mu, d_log_sigma) as floats, the loss and its exact partial derivatives.

Signaturedef gaussian_nll_grad(x, mu, log_sigma)

Example

x [1, 2, 3], mu 2, log_sigma 0 gives (1.252272, 0.0, 0.333333).

Understand the idea

A Gaussian likelihood scores how well a predicted mean and spread explain data. The negative log-likelihood (NLL) per point is 0.5 log(2 pi) + log sigma + (x - mu)^2 / (2 sigma^2). The last term punishes errors, scaled by the spread; the log sigma term stops the model from claiming infinite uncertainty.

We use log sigma as the parameter because it can be any real number while sigma stays positive. The chain rule then gives clean gradients.

Worked example: x = 1, 2, 3, mu = 2, log sigma = 0 (sigma = 1). Residuals are -1, 0, 1. NLL = 0.919 + 0 + mean(0.5, 0, 0.5) = 0.919 + 0.333 = 1.252. d_mu = mean(1, 0, -1) = 0, since mu is already centred. d_log_sigma = mean(1 - 1, 1 - 0, 1 - 1) = 0.333, positive, so the loss wants a smaller sigma (the true spread is a bit under 1).

Rule: d_mu = mean(-(x - mu) / sigma^2), d_log_sigma = mean(1 - (x - mu)^2 / sigma^2).

This loss trains regressors that output error bars and the decoder of many VAEs.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplegaussian_nll_grad([1, 2, 3], 2.0, 0.0)
  • Sample 2: wide sigmagaussian_nll_grad([0.5, -1.0, 2.0, 0.0], 0.3, 0.7)
  • Test 3: narrow sigmagaussian_nll_grad([10, 10.5, 9.8], 10.2, -1.2)
  • Test 4: randomgaussian_nll_grad(_x, -0.4, 0.25)