BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Probability and statistics2 of 24 in topic

53. VAE loss: KL divergence between the encoder's Gaussian and the prior

EasyProbability and statistics

You are training a variational autoencoder (VAE) on product images. For each image the encoder outputs a mean and a standard deviation per latent dimension. The loss has two parts: how well the decoder rebuilds the image, and a KL term that keeps the encoder's distribution close to a simple prior, usually N(0, 1) in every dimension. If the KL term is wrong, the latent space either collapses or never organises, and nothing crashes to tell you.

Write kl_diag_gauss(mu1, sigma1, mu2, sigma2) that returns KL(N1 || N2) as a Python float, where both are Gaussians with independent dimensions (diagonal covariance). Sum over the d dimensions. Per dimension:

log(sigma2 / sigma1) + (sigma1^2 + (mu1 - mu2)^2) / (2 * sigma2^2) - 0.5

Watch out for:
- sigma1 and sigma2 are standard deviations, not variances. Mixing them up is the most common VAE bug.
- Order matters: KL(N1 || N2) is not KL(N2 || N1).
- It is a sum over dimensions, not a mean.
- Arguments can be lists, NumPy arrays, or plain numbers for a 1-D Gaussian. Convert with np.asarray(x, dtype=float).
- A very confident encoder (sigma1 = 0.001) must give a large finite number, not inf or nan.

Functiondef kl_diag_gauss(mu1, sigma1, mu2, sigma2)
Play with it

KL divergence between two Gaussians

KL(N1 || N2) = log(σ2/σ1) + (σ1² + (μ1 − μ2)²) / (2σ2²) − 1/2, computed live. A diagonal Gaussian sums this over dimensions.

00.20.4-6-4-20246xdensity
KL(N1 || N2)
0.3499
KL(N2 || N1)
0.7195
KL is not symmetric: swap the two and the number changes.

Example 1

Input: mu1 = [0], sigma1 = [1], mu2 = [1], sigma2 = [1]

Output: 0.5

Explanation: Shifting the mean by one standard deviation costs half a nat.

Example 2

Input: mu1 = [1.0, 2.0], sigma1 = [0.5, 3.0], mu2 = [1.0, 2.0], sigma2 = [0.5, 3.0]

Output: 0.0

Example 3

Input: mu1 = [0.0, 1.0], sigma1 = [2.0, 0.5], mu2 = [0.5, 0.0], sigma2 = [1.0, 1.5]

Output: 1.808243

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 9 tests to be accepted.
Hint 1

Vectorise the per-dimension formula and sum.

Hint 2

Watch whether you are holding a standard deviation or a variance.

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.

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.

Topics
Probability and statistics
Similar questions
  • Track mean and variance of a stream in one passEasy
  • Compare two token distributions with Jensen-Shannon divergenceEasy
  • Sample categories from fixed uniforms with the inverse CDFEasy
  • Compute the mean and variance of a discrete random variable and of aX + bEasy
All Probability and statistics problems
Report
53 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def kl_diag_gauss(mu1, sigma1, mu2, sigma2):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 9 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS