Evaluate a multivariate Gaussian log-density stably with a Cholesky factor

Gaussian log-likelihoods power anomaly detection on embeddings, Gaussian processes and mixture models. In a few hundred dimensions the determinant of the covariance easily overflows or underflows, and explicit inverses lose accuracy. A Cholesky factor fixes both.

Write mvn_logpdf(X, mu, cov). X has shape (n, d), mu shape (d,), cov is a symmetric positive definite (d, d) array. Return shape (n,): the log-density of each row under N(mu, cov):
log p(x) = -0.5 * (d log(2 pi) + log det(cov) + (x - mu)^T cov^{-1} (x - mu)).
Requirements: compute L = cholesky(cov). Get log det(cov) as 2 * sum(log(diag(L))). Get the quadratic term as the squared norm of z where L z = x - mu. Never call np.linalg.det or np.linalg.inv; the tests use d = 150 where det(cov) is far outside float range.

Signaturedef mvn_logpdf(X, mu, cov)

Example

X = [[0, 0]], mu = [0, 0], cov = I gives [-1.83787707] (that is -log(2 pi)).

Understand the idea

The log density of a multivariate Gaussian needs log det(cov) and the quadratic term (x - mu)^T cov^-1 (x - mu). In high dimensions the determinant itself overflows or underflows, and explicit inverses lose accuracy. The Cholesky factor L, with cov = L L^T, fixes both: log det = 2 x sum(log diag(L)), and the quadratic term is |z|^2 where L z = x - mu is solved by triangular substitution. Worked example: cov = [[4, 2], [2, 2]], so L = [[2, 0], [1, 1]] (check: L L^T = [[4, 2], [2, 2]]). log det = 2 (ln 2 + ln 1) = 1.386, matching det = 4. For x - mu = [2, 2]: z0 = 2 / 2 = 1, z1 = (2 - 1 x 1) / 1 = 1, so the quadratic term is 2. log p = -0.5 (2 x 1.838 + 1.386 + 2) = -3.531. Rule: log p = -0.5 (d log(2 pi) + 2 sum log diag L + |L^-1 (x - mu)|^2), never calling det or inv. Anomaly detection on embeddings and Gaussian processes use this.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplemvn_logpdf([[0.0, 0.0]], [0.0, 0.0], np.eye(2))
  • Sample 2: correlated 3Dmvn_logpdf(_X, _mu, _C)