Compute the KL divergence between two diagonal Gaussians

The KL divergence between two Gaussians has a closed form. It is the regulariser in variational autoencoders and a common way to compare two predicted distributions.

Write kl_diag_gauss(mu1, sigma1, mu2, sigma2). Each argument is a 1D array of length d; sigma1 and sigma2 are standard deviations (positive), not variances. Return KL(N1 || N2) as a float, summed over the d independent dimensions. Per dimension it is log(sigma2 / sigma1) + (sigma1^2 + (mu1 - mu2)^2) / (2 sigma2^2) - 0.5.

Signaturedef kl_diag_gauss(mu1, sigma1, mu2, sigma2)

Example

mu1 = [0], sigma1 = [1], mu2 = [1], sigma2 = [1] gives 0.5.

Understand the idea

KL divergence measures how much one probability distribution differs from another; it is zero only when they match, and it is not symmetric. For Gaussians with independent dimensions there is a closed form per dimension, and you sum over dimensions. The inputs are standard deviations, not variances, which is an easy place to slip. Worked example, one dimension: mu1 = 0, sigma1 = 1, mu2 = 0, sigma2 = 2. log(2 / 1) = 0.693. (1^2 + 0^2) / (2 x 2^2) = 1 / 8 = 0.125. KL = 0.693 + 0.125 - 0.5 = 0.318. Another: mu1 = 0, mu2 = 1, both sigmas 1 gives 0 + (1 + 1) / 2 - 0.5 = 0.5. Writing log(sigma2^2 / sigma1^2) would double the log term. Rule: KL(N1 || N2) = sum over d of [log(sigma2 / sigma1) + (sigma1^2 + (mu1 - mu2)^2) / (2 sigma2^2) - 0.5]. This is the regulariser term in variational autoencoders.

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

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

  • Sample 1: examplekl_diag_gauss([0.0], [1.0], [1.0], [1.0])
  • Sample 2: same distribution is 0kl_diag_gauss([1.0, 2.0], [0.5, 3.0], [1.0, 2.0], [0.5, 3.0])
  • Test 3: different widthskl_diag_gauss([0.0, 1.0], [2.0, 0.5], [0.5, 0.0], [1.0, 1.5])
  • Test 4: not symmetrickl_diag_gauss([0.0], [1.0], [0.0], [2.0]) - kl_diag_gauss([0.0], [2.0], [0.0], [1.0])