Type at least 2 letters. Enter opens the first result, Esc closes.

    Information Theory · Lesson 6 · Continuous variables and mutual information

    Continuous variables: differential entropy, Gaussians and forward vs reverse KL

    Intermediate 75 min 5 interactive figures 4 videos Colab notebook

    Before this lesson: lesson 01 (entropy), lesson 03 (KL divergence, Gibbs' inequality) and lesson 04 (cross-entropy, maximum likelihood is forward KL). Densities and the multivariate Gaussian from probability lesson 05; densities under a change of variables from calculus lesson 10; the determinant as a volume from linear algebra lesson 03 and covariance matrices from linear algebra lesson 07. Time: about 75 minutes, plus the notebook. This lesson is long; take a break after section 3.4.


    Why this matters #

    • VAEs and variational inference. The encoder of a VAE outputs a Gaussian, and the loss contains the KL between two Gaussians, in closed form (section 3.6). VI minimizes the reverse KL to the posterior; this explains why VI posteriors are often too narrow (section 3.7).
    • Maximum likelihood and distillation. Training by log-loss minimizes the forward KL from the data to the model (lesson 04). It covers all the data, even at the price of putting mass where there is no data.
    • Normalizing flows. A flow maps a simple density through an invertible network. Its log-density contains log⁡∣det⁡J∣\log|\det J|, the same term as in the change of variables for hh (section 3.3).
    • Gaussian uncertainty in science. The entropy of a Gaussian posterior, 12log⁡det⁡(2πeΣ)\frac12\log\det(2\pi e\Sigma), measures the remaining uncertainty in Bayesian experimental design and data assimilation. It is meaningful only in fixed units, or as a difference.
    • Mutual information. Differential entropy changes with the units, but differences of differential entropies such as the mutual information do not (lesson 07).

    In this track log⁡\log is the natural logarithm and gives nats; log⁡2\log_2 gives bits. For densities we work in nats, as NumPy, SciPy and PyTorch do.

    1. Predict first #

    2. The picture #

    2.1 From bins to densities #

    Let XX have a density p(x)p(x). Cut the real line into bins of width Δ\Delta and record only the bin that XX falls in. This gives a discrete variable XΔX_\Delta, and discrete variables have an entropy H(XΔ)H(X_\Delta) (lesson 01). What happens when the bins get smaller?

    1. A small bin ii around a point xix_i has probability Pi≈p(xi) ΔP_i \approx p(x_i)\,\Delta (height times width).
    2. So H(XΔ)=−∑iPilog⁡Pi≈−∑ip(xi)Δ log⁡(p(xi)Δ)H(X_\Delta) = -\sum_i P_i \log P_i \approx -\sum_i p(x_i)\Delta\,\log\big(p(x_i)\Delta\big).
    3. Split the log of the product: log⁡(p(xi)Δ)=log⁡p(xi)+log⁡Δ\log(p(x_i)\Delta) = \log p(x_i) + \log\Delta. This gives two sums:
    H(XΔ)≈−∑ip(xi)log⁡p(xi) Δ  −  log⁡Δ∑ip(xi)Δ.H(X_\Delta) \approx -\sum_i p(x_i)\log p(x_i)\,\Delta \;-\; \log\Delta \sum_i p(x_i)\Delta .
    1. The first sum is a Riemann sum for −∫p(x)log⁡p(x) dx-\int p(x)\log p(x)\,dx. In the second sum, ∑ip(xi)Δ≈1\sum_i p(x_i)\Delta \approx 1 (the total probability). So
    H(XΔ)≈h(X)+log⁡1Δ,h(X)=−∫p(x)log⁡p(x) dx.H(X_\Delta) \approx h(X) + \log\frac{1}{\Delta}, \qquad h(X) = -\int p(x)\log p(x)\,dx .

    The number h(X)h(X) is the differential entropy. The term log⁡(1/Δ)\log(1/\Delta) grows without bound: each halving of Δ\Delta adds one more yes/no question (1 bit) to locate XX. An exact real number needs infinitely many bits. The differential entropy is what remains after we remove this infinite part. It is not the limit of H(XΔ)H(X_\Delta); that limit is +∞+\infty.

    Interactive figure: loading…

    Make the bins smaller with the Δ\Delta slider. Top: the density p(x)p(x) (blue) and the histogram of XΔX_\Delta (yellow, bin probability divided by Δ\Delta). Bottom: H(XΔ)H(X_\Delta) grows by about 1 bit per halving of Δ\Delta, while H(XΔ)−log⁡(1/Δ)H(X_\Delta) - \log(1/\Delta) (grey, dashed) settles at h(X)h(X); the aqua gap is log⁡(1/Δ)\log(1/\Delta). Then press "σ = 0.2" and notice that the density goes above the dashed line at 1 and h(X)h(X) becomes negative.

    Why hh can be negative. A density is not a probability. It can be larger than 1, as long as the area under it is 1. The uniform density on [0,12][0, \frac12] equals 2 on its interval, so −log⁡p(x)=−log⁡2<0-\log p(x) = -\log 2 < 0 everywhere, and h=−log⁡2=−1h = -\log 2 = -1 bit. A discrete entropy is never negative, because every probability is at most 1.

    Why hh depends on the units. The bin width Δ\Delta has units. One millimetre is 11000\frac{1}{1000} of a metre, so the same physical bins give log⁡(1/Δ)\log(1/\Delta) values that differ by log⁡1000\log 1000. The remainder hh changes by the same amount (section 3.3).

    Quick check

    XX is uniform on [0,12][0, \frac12]. What is its differential entropy in bits?

    2.2 Two ways to fit one Gaussian #

    The second picture is about fitting. A target density pp has two bumps. We want the single Gaussian q=N(μ,σ2)q = \mathcal{N}(\mu, \sigma^2) that is "closest" to pp. KL is not symmetric (lesson 03), so there are two different questions.

    • Forward KL, KL(p ∥ q)=Ex∼p[log⁡p(x)−log⁡q(x)]\mathrm{KL}(p\,\|\,q) = \mathbb{E}_{x \sim p}\big[\log p(x) - \log q(x)\big]. The average is over pp. Where pp has mass and qq is tiny, −log⁡q(x)-\log q(x) is huge. So qq must put mass everywhere pp has mass. The fit is wide and covers both bumps: mode covering.
    • Reverse KL, KL(q ∥ p)=Ex∼q[log⁡q(x)−log⁡p(x)]\mathrm{KL}(q\,\|\,p) = \mathbb{E}_{x \sim q}\big[\log q(x) - \log p(x)\big]. The average is over qq. Where qq has mass and pp is tiny, −log⁡p(x)-\log p(x) is huge. So qq must avoid every region where pp is small, including the gap between the bumps. The fit sits on one bump: mode seeking.
    Interactive figure: loading…

    Press "Fit forward KL", then "Fit reverse KL". The blue target is p=0.25 N(−3,1)+0.75 N(3,1)p = 0.25\,\mathcal{N}(-3, 1) + 0.75\,\mathcal{N}(3, 1); the orange curve is the Gaussian qq. Drag its peak to choose a start (left and right move μ\mu, up and down change σ\sigma), or use the "Start" buttons. Notice: the forward fit always ends at the same wide Gaussian. The reverse fit ends on the bump nearest to the start, and the two KL values show that each fit is good only for its own objective.

    Quick check

    You fit one Gaussian to a target with two well-separated bumps. Which fit puts a lot of mass in the gap between the bumps, where the target is almost zero?

    3. Definitions and main results #

    3.1 Differential entropy #

    Let XX be a continuous random variable with density pp on Rd\mathbb{R}^d. Its differential entropy is

    h(X)=−∫p(x)log⁡p(x) dx=E[−log⁡p(X)],h(X) = -\int p(x)\log p(x)\,dx = \mathbb{E}\big[-\log p(X)\big],

    with 0log⁡0=00\log 0 = 0, when the integral exists. We write lower-case hh to separate it from the discrete HH. Two examples, step by step:

    • Uniform on [0,a][0, a]. p(x)=1/ap(x) = 1/a on the interval, so −log⁡p(x)=log⁡a-\log p(x) = \log a for every xx that can occur. The average of a constant is the constant: h=log⁡ah = \log a. It is negative for a<1a < 1.
    • Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2). The density is p(x)=12πσ2exp⁡(−(x−μ)22σ2)p(x) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\big(-\frac{(x - \mu)^2}{2\sigma^2}\big), so
    −log⁡p(x)=12log⁡(2πσ2)+(x−μ)22σ2.-\log p(x) = \tfrac12\log(2\pi\sigma^2) + \frac{(x - \mu)^2}{2\sigma^2}.

    Take the mean. E[(X−μ)2]=σ2\mathbb{E}[(X - \mu)^2] = \sigma^2, so the second term has mean 12\frac12. With 12=12log⁡e\frac12 = \frac12\log e:

    h=12log⁡(2πσ2)+12=12log⁡(2πe σ2).h = \tfrac12\log(2\pi\sigma^2) + \tfrac12 = \tfrac12\log(2\pi e\,\sigma^2).

    The mean μ\mu does not appear: shifting a density does not change its shape. For σ=1\sigma = 1, h=1.419h = 1.419 nats =2.047= 2.047 bits. h<0h < 0 exactly when 2πeσ2<12\pi e\sigma^2 < 1, that is, σ<1/2πe≈0.242\sigma < 1/\sqrt{2\pi e} \approx 0.242.

    Theorem 1 (quantization). Let pp be continuous and let plog⁡pp\log p be Riemann integrable. Let XΔX_\Delta be XX quantized into bins of width Δ\Delta. Then H(XΔ)−log⁡(1/Δ)→h(X)H(X_\Delta) - \log(1/\Delta) \to h(X) as Δ→0\Delta \to 0.

    Proof of Theorem 1 (Cover and Thomas, Theorem 8.3.1)
    1. By the mean value theorem, each bin [iΔ,(i+1)Δ)[i\Delta, (i + 1)\Delta) contains a point xix_i with Pi=∫bin ip(x) dx=p(xi) ΔP_i = \int_{\text{bin } i} p(x)\,dx = p(x_i)\,\Delta exactly.
    2. Then H(XΔ)=−∑ip(xi)Δlog⁡(p(xi)Δ)=−∑ip(xi)Δlog⁡p(xi)−log⁡Δ∑ip(xi)ΔH(X_\Delta) = -\sum_i p(x_i)\Delta\log\big(p(x_i)\Delta\big) = -\sum_i p(x_i)\Delta\log p(x_i) - \log\Delta\sum_i p(x_i)\Delta.
    3. ∑ip(xi)Δ=∑iPi=1\sum_i p(x_i)\Delta = \sum_i P_i = 1, so H(XΔ)+log⁡Δ=−∑ip(xi)log⁡p(xi) ΔH(X_\Delta) + \log\Delta = -\sum_i p(x_i)\log p(x_i)\,\Delta.
    4. The right side is a Riemann sum of −plog⁡p-p\log p, and it tends to h(X)h(X) as Δ→0\Delta \to 0. ■\blacksquare

    In dd dimensions, cubes of side Δ\Delta give H(XΔ)≈h(X)+dlog⁡(1/Δ)H(X_\Delta) \approx h(X) + d\log(1/\Delta).

    3.2 The multivariate Gaussian: entropy is a log-volume #

    Let X∼N(μ,Σ)X \sim \mathcal{N}(\mu, \Sigma) in dd dimensions, with Σ\Sigma positive definite. Its density is p(x)=((2π)ddet⁡Σ)−1/2exp⁡(−12(x−μ)⊤Σ−1(x−μ))p(x) = \big((2\pi)^d\det\Sigma\big)^{-1/2}\exp\big(-\frac12(x - \mu)^\top\Sigma^{-1}(x - \mu)\big), so

    −log⁡p(x)=d2log⁡(2π)+12log⁡det⁡Σ+12(x−μ)⊤Σ−1(x−μ).-\log p(x) = \tfrac{d}{2}\log(2\pi) + \tfrac12\log\det\Sigma + \tfrac12(x - \mu)^\top\Sigma^{-1}(x - \mu).

    The quadratic term has mean dd. (Proof: E[(X−μ)⊤Σ−1(X−μ)]=E[tr⁡(Σ−1(X−μ)(X−μ)⊤)]=tr⁡(Σ−1Σ)=tr⁡(Id)=d\mathbb{E}[(X - \mu)^\top\Sigma^{-1}(X - \mu)] = \mathbb{E}[\operatorname{tr}(\Sigma^{-1}(X - \mu)(X - \mu)^\top)] = \operatorname{tr}(\Sigma^{-1}\Sigma) = \operatorname{tr}(I_d) = d.) So

    h(X)=d2log⁡(2π)+12log⁡det⁡Σ+d2=12log⁡((2πe)ddet⁡Σ).h(X) = \tfrac{d}{2}\log(2\pi) + \tfrac12\log\det\Sigma + \tfrac{d}{2} = \tfrac12\log\big((2\pi e)^d\det\Sigma\big).

    Only det⁡Σ\det\Sigma enters. The ellipse (in dd dimensions, the ellipsoid) {x:(x−μ)⊤Σ−1(x−μ)≤1}\{x : (x - \mu)^\top\Sigma^{-1}(x - \mu) \le 1\} has volume proportional to det⁡Σ\sqrt{\det\Sigma} (linear algebra lesson 03: the determinant scales volume). So the entropy of a Gaussian is the log of the volume of its 1σ1\sigma ellipsoid, plus a constant. When two coordinates become almost perfectly correlated, the ellipse flattens to a line, det⁡Σ→0\det\Sigma \to 0, and h→−∞h \to -\infty.

    Interactive figure: loading…

    Change σ1\sigma_1, σ2\sigma_2 and the correlation ρ\rho. The blue ellipse is the 1σ1\sigma ellipse of XX; its area is πdet⁡Σ\pi\sqrt{\det\Sigma} and the readout gives h(X)=12log⁡((2πe)2det⁡Σ)h(X) = \frac12\log((2\pi e)^2\det\Sigma). Push ρ\rho towards ±1\pm 1: the ellipse flattens and h→−∞h \to -\infty. Then move a1a_1 or a2a_2: the yellow dashed ellipse is Y=AXY = AX with A=diag⁡(a1,a2)A = \operatorname{diag}(a_1, a_2), a change of units, and hh shifts by log⁡∣det⁡A∣\log|\det A|.

    3.3 Change of variables: the units trap #

    Theorem 2 (affine maps). Let Y=AX+bY = AX + b, where AA is an invertible d×dd \times d matrix and bb a vector. Then

    h(Y)=h(X)+log⁡∣det⁡A∣.h(Y) = h(X) + \log|\det A| .

    Proof.

    1. Change of variables (calculus lesson 10): the density of YY is pY(y)=pX(A−1(y−b))/∣det⁡A∣p_Y(y) = p_X\big(A^{-1}(y - b)\big)/|\det A|. A box of volume VV maps to a box of volume ∣det⁡A∣ V|\det A|\,V with the same probability, so the density divides by ∣det⁡A∣|\det A|.
    2. At y=Ax+by = Ax + b this reads −log⁡pY(y)=−log⁡pX(x)+log⁡∣det⁡A∣-\log p_Y(y) = -\log p_X(x) + \log|\det A|.
    3. Take the mean over XX. The shift bb has disappeared: moving a density does not change its shape. ■\blacksquare

    Check with Gaussians. ΣY=AΣA⊤\Sigma_Y = A\Sigma A^\top and det⁡(AΣA⊤)=(det⁡A)2det⁡Σ\det(A\Sigma A^\top) = (\det A)^2\det\Sigma, so 12log⁡det⁡ΣY=12log⁡det⁡Σ+log⁡∣det⁡A∣\frac12\log\det\Sigma_Y = \frac12\log\det\Sigma + \log|\det A|. ✓

    The units trap. A change of units is a map Y=cXY = cX. Metres to millimetres is c=1000c = 1000, so hh grows by log⁡1000=6.908\log 1000 = 6.908 nats =9.966= 9.966 bits per coordinate, for the same physical uncertainty. So a differential entropy alone has no absolute meaning. Compare entropies only in the same units, or use quantities that do not depend on the units: KL divergence and mutual information.

    Nonlinear maps and normalizing flows

    For a smooth invertible map gg with Jacobian matrix JgJ_g, the same three steps give pY(g(x))=pX(x)/∣det⁡Jg(x)∣p_Y(g(x)) = p_X(x)/|\det J_g(x)| and

    h(g(X))=h(X)+E[log⁡∣det⁡Jg(X)∣].h(g(X)) = h(X) + \mathbb{E}\big[\log|\det J_g(X)|\big].

    A normalizing flow uses the first identity in log form: log⁡pY(y)=log⁡pX(x)−log⁡∣det⁡Jg(x)∣\log p_Y(y) = \log p_X(x) - \log|\det J_g(x)| with x=g−1(y)x = g^{-1}(y). Flow architectures are designed so that log⁡∣det⁡Jg∣\log|\det J_g| is cheap (triangular Jacobians). Example: X∼N(0,1)X \sim \mathcal{N}(0, 1) and g(x)=x3g(x) = x^3: h(X3)=h(X)+E[log⁡3X2]=1.419+1.099−1.270=1.247h(X^3) = h(X) + \mathbb{E}[\log 3X^2] = 1.419 + 1.099 - 1.270 = 1.247 nats, where E[log⁡X2]=−(γ+log⁡2)=−1.270\mathbb{E}[\log X^2] = -(\gamma + \log 2) = -1.270 (γ=0.5772\gamma = 0.5772 is Euler's constant). If AA is singular, Y=AXY = AX lives on a lower-dimensional subspace and has no density on Rd\mathbb{R}^d; its differential entropy is −∞-\infty in the limit.

    3.4 KL divergence for densities: no units problem #

    For densities pp and qq on Rd\mathbb{R}^d, the KL divergence is

    KL(p ∥ q)=∫p(x)log⁡p(x)q(x) dx=Ep[log⁡p(X)q(X)].\mathrm{KL}(p\,\|\,q) = \int p(x)\log\frac{p(x)}{q(x)}\,dx = \mathbb{E}_{p}\Big[\log\frac{p(X)}{q(X)}\Big].

    It is finite only if q(x)>0q(x) > 0 wherever p(x)>0p(x) > 0 (up to sets of zero probability). Gibbs' inequality still holds: KL(p ∥ q)≥0\mathrm{KL}(p\,\|\,q) \ge 0, with equality only when p=qp = q (almost everywhere). The proof of lesson 03 works with integrals in place of sums. Under mild conditions the KL of the quantized versions converges to it: KL(pΔ ∥ qΔ)→KL(p ∥ q)\mathrm{KL}(p_\Delta\,\|\,q_\Delta) \to \mathrm{KL}(p\,\|\,q), because the two log⁡(1/Δ)\log(1/\Delta) terms cancel.

    Theorem 3 (KL does not depend on the coordinates). Let gg be a smooth invertible map, and let pYp_Y, qYq_Y be the densities of g(X)g(X) when X∼pX \sim p and when X∼qX \sim q. Then KL(pY ∥ qY)=KL(p ∥ q)\mathrm{KL}(p_Y\,\|\,q_Y) = \mathrm{KL}(p\,\|\,q).

    Proof.

    1. Both densities pick up the same Jacobian factor: pY(g(x))=p(x)/∣det⁡Jg(x)∣p_Y(g(x)) = p(x)/|\det J_g(x)| and qY(g(x))=q(x)/∣det⁡Jg(x)∣q_Y(g(x)) = q(x)/|\det J_g(x)|.
    2. In the ratio the factor cancels: pY(g(x))qY(g(x))=p(x)q(x)\frac{p_Y(g(x))}{q_Y(g(x))} = \frac{p(x)}{q(x)}.
    3. The KL is the mean of the log of this ratio under pp, so it does not change. ■\blacksquare

    So measuring in millimetres instead of metres changes every hh, but no KL divergence and no mutual information. This is why ML objectives use KL and mutual information, not hh alone.

    Quick check

    Two forecast distributions pp and qq for a temperature are given in kelvin. You convert both to °F (y=1.8x+cy = 1.8x + c). What changes?

    3.5 The Gaussian has maximum entropy #

    Theorem 4 (maximum entropy). Among all densities on Rd\mathbb{R}^d with mean μ\mu and covariance Σ\Sigma (Σ\Sigma positive definite), the Gaussian g=N(μ,Σ)g = \mathcal{N}(\mu, \Sigma) has the largest differential entropy, h(g)=12log⁡((2πe)ddet⁡Σ)h(g) = \frac12\log((2\pi e)^d\det\Sigma), and it is the only one.

    Why this is true (idea). log⁡g(x)\log g(x) is a quadratic function of xx. The average of a quadratic function depends only on the mean and the covariance. So every density with the same mean and covariance has the same "cross-entropy with gg". Gibbs' inequality then does the rest.

    Proof.

    1. Let pp have mean μ\mu and covariance Σ\Sigma. By Gibbs, 0≤KL(p ∥ g)=Ep[log⁡p]−Ep[log⁡g]=−h(p)−Ep[log⁡g(X)]0 \le \mathrm{KL}(p\,\|\,g) = \mathbb{E}_p[\log p] - \mathbb{E}_p[\log g] = -h(p) - \mathbb{E}_p[\log g(X)].
    2. log⁡g(x)=−12log⁡((2π)ddet⁡Σ)−12(x−μ)⊤Σ−1(x−μ)\log g(x) = -\frac12\log((2\pi)^d\det\Sigma) - \frac12(x - \mu)^\top\Sigma^{-1}(x - \mu).
    3. The quadratic term has mean tr⁡(Σ−1Σ)=d\operatorname{tr}(\Sigma^{-1}\Sigma) = d under pp, exactly as under gg (section 3.2). So Ep[log⁡g(X)]=Eg[log⁡g(X)]=−h(g)\mathbb{E}_p[\log g(X)] = \mathbb{E}_g[\log g(X)] = -h(g).
    4. Step 1 becomes 0≤−h(p)+h(g)0 \le -h(p) + h(g), so h(p)≤h(g)h(p) \le h(g). Equality holds only if KL(p ∥ g)=0\mathrm{KL}(p\,\|\,g) = 0, that is, p=gp = g. ■\blacksquare

    Step 4 says more: for every pp with the same mean and covariance, h(g)−h(p)=KL(p ∥ g)h(g) - h(p) = \mathrm{KL}(p\,\|\,g). The entropy gap to the Gaussian is a KL divergence.

    Interactive figure: loading…

    Guess the order first, then switch the compared shape. All four densities have variance σ2\sigma^2. The Gaussian has the largest hh; the compared shape is yellow, and the aqua gap is KL(p ∥ Gaussian)\mathrm{KL}(p\,\|\,\text{Gaussian}). Move σ\sigma: every hh shifts by log⁡σ\log\sigma, but the gaps stay the same.

    At unit variance: the two bumps of the figure have h=1.1659h = 1.1659 nats; uniform on [−3,3][-\sqrt3, \sqrt3] has h=log⁡12=1.2425h = \log\sqrt{12} = 1.2425 nats; Laplace with scale b=1/2b = 1/\sqrt2 has h=1+log⁡(2b)=1.3466h = 1 + \log(2b) = 1.3466 nats; the Gaussian has 1.41891.4189 nats. The maximum-entropy principle reads this backwards: if you know only the mean and the covariance of some data, the Gaussian is the model that assumes nothing else. Other constraints give other families: a fixed interval gives the uniform, a fixed mean of ∣x∣|x| gives the Laplace.

    3.6 KL between two Gaussians #

    Theorem 5 (Gaussian KL). For p0=N(μ0,Σ0)p_0 = \mathcal{N}(\mu_0, \Sigma_0) and p1=N(μ1,Σ1)p_1 = \mathcal{N}(\mu_1, \Sigma_1) on Rd\mathbb{R}^d,

    KL(p0 ∥ p1)=12[tr⁡(Σ1−1Σ0)+(μ1−μ0)⊤Σ1−1(μ1−μ0)−d+log⁡det⁡Σ1det⁡Σ0].\mathrm{KL}(p_0\,\|\,p_1) = \frac12\Big[\operatorname{tr}(\Sigma_1^{-1}\Sigma_0) + (\mu_1 - \mu_0)^\top\Sigma_1^{-1}(\mu_1 - \mu_0) - d + \log\frac{\det\Sigma_1}{\det\Sigma_0}\Big].

    In one dimension it becomes

    KL(N(μ0,σ02) ∥ N(μ1,σ12))=log⁡σ1σ0+σ02+(μ0−μ1)22σ12−12.\mathrm{KL}\big(\mathcal{N}(\mu_0, \sigma_0^2)\,\|\,\mathcal{N}(\mu_1, \sigma_1^2)\big) = \log\frac{\sigma_1}{\sigma_0} + \frac{\sigma_0^2 + (\mu_0 - \mu_1)^2}{2\sigma_1^2} - \frac12 .

    Each term has a meaning: the trace compares the spreads, the quadratic term (the Mahalanobis distance of the means, measured in units of Σ1\Sigma_1) compares the means, and the log-det compares the volumes. Two cases to know by heart:

    • Same variance 1: KL(N(μ,1) ∥ N(0,1))=μ2/2\mathrm{KL}(\mathcal{N}(\mu, 1)\,\|\,\mathcal{N}(0, 1)) = \mu^2/2. KL behaves like half a squared distance.
    • The VAE term: KL(N(μ,diag⁡(σ2)) ∥ N(0,I))=12∑j(σj2+μj2−1−log⁡σj2)\mathrm{KL}\big(\mathcal{N}(\mu, \operatorname{diag}(\sigma^2))\,\|\,\mathcal{N}(0, I)\big) = \frac12\sum_j\big(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2\big).
    Proof of Theorem 5
    1. KL=E0[log⁡p0(X)−log⁡p1(X)]\mathrm{KL} = \mathbb{E}_0[\log p_0(X) - \log p_1(X)], where E0\mathbb{E}_0 is the mean under p0p_0 and log⁡pi(x)=−d2log⁡2π−12log⁡det⁡Σi−12(x−μi)⊤Σi−1(x−μi)\log p_i(x) = -\frac d2\log 2\pi - \frac12\log\det\Sigma_i - \frac12(x - \mu_i)^\top\Sigma_i^{-1}(x - \mu_i).
    2. One identity does all the work. If ZZ has mean mm and covariance CC, then E[Z⊤MZ]=E[tr⁡(MZZ⊤)]=tr⁡(M(C+mm⊤))=tr⁡(MC)+m⊤Mm\mathbb{E}[Z^\top MZ] = \mathbb{E}[\operatorname{tr}(MZZ^\top)] = \operatorname{tr}\big(M(C + mm^\top)\big) = \operatorname{tr}(MC) + m^\top Mm.
    3. Under p0p_0, X−μ0X - \mu_0 has mean 0 and covariance Σ0\Sigma_0, so E0[(X−μ0)⊤Σ0−1(X−μ0)]=tr⁡(Id)=d\mathbb{E}_0[(X - \mu_0)^\top\Sigma_0^{-1}(X - \mu_0)] = \operatorname{tr}(I_d) = d.
    4. X−μ1X - \mu_1 has mean μ0−μ1\mu_0 - \mu_1 and covariance Σ0\Sigma_0, so E0[(X−μ1)⊤Σ1−1(X−μ1)]=tr⁡(Σ1−1Σ0)+(μ0−μ1)⊤Σ1−1(μ0−μ1)\mathbb{E}_0[(X - \mu_1)^\top\Sigma_1^{-1}(X - \mu_1)] = \operatorname{tr}(\Sigma_1^{-1}\Sigma_0) + (\mu_0 - \mu_1)^\top\Sigma_1^{-1}(\mu_0 - \mu_1).
    5. Subtract the two logs. The d2log⁡2π\frac d2\log 2\pi terms cancel. The log-dets give 12log⁡(det⁡Σ1/det⁡Σ0)\frac12\log(\det\Sigma_1/\det\Sigma_0). The quadratic terms give 12(step 4−step 3)\frac12(\text{step 4} - \text{step 3}). ■\blacksquare

    Example. KL(N(0,1) ∥ N(1,22))=log⁡2+1+18−12=0.693+0.25−0.5=0.443\mathrm{KL}(\mathcal{N}(0, 1)\,\|\,\mathcal{N}(1, 2^2)) = \log 2 + \frac{1 + 1}{8} - \frac12 = 0.693 + 0.25 - 0.5 = 0.443 nats. The other direction is log⁡12+4+12−12=1.307\log\frac12 + \frac{4 + 1}{2} - \frac12 = 1.307 nats: not symmetric.

    Quick check

    What is KL(N(2,1) ∥ N(0,1))\mathrm{KL}\big(\mathcal{N}(2, 1)\,\|\,\mathcal{N}(0, 1)\big)?

    3.7 Forward and reverse KL #

    Fix a target pp and a family of models qθq_\theta (for example, all Gaussians). Section 2.2 showed the two fits in a picture. Now the precise statements.

    Forward KL, min⁡θKL(p ∥ qθ)\min_\theta \mathrm{KL}(p\,\|\,q_\theta). Write KL(p ∥ qθ)=−h(p)−Ep[log⁡qθ(X)]\mathrm{KL}(p\,\|\,q_\theta) = -h(p) - \mathbb{E}_p[\log q_\theta(X)]. The first term does not depend on θ\theta. So minimizing the forward KL is maximizing Ep[log⁡qθ(X)]\mathbb{E}_p[\log q_\theta(X)]: maximum likelihood (lesson 04). You need samples of pp (the data), not its density.

    Theorem 6 (forward KL to a Gaussian is moment matching). Let pp have mean mm and covariance CC (positive definite), and let g=N(m,C)g = \mathcal{N}(m, C). For every Gaussian qq,

    KL(p ∥ q)=KL(p ∥ g)+KL(g ∥ q).\mathrm{KL}(p\,\|\,q) = \mathrm{KL}(p\,\|\,g) + \mathrm{KL}(g\,\|\,q).

    So the best Gaussian is q=gq = g: match the mean and the covariance, and there is only one optimum.

    Proof.

    1. log⁡q\log q is a quadratic function of xx, so Ep[log⁡q]=Eg[log⁡q]\mathbb{E}_p[\log q] = \mathbb{E}_g[\log q] (step 3 of Theorem 4).
    2. KL(p ∥ q)=−h(p)−Eg[log⁡q]=[h(g)−h(p)]+[−h(g)−Eg[log⁡q]]\mathrm{KL}(p\,\|\,q) = -h(p) - \mathbb{E}_g[\log q] = \big[h(g) - h(p)\big] + \big[-h(g) - \mathbb{E}_g[\log q]\big].
    3. The second bracket is KL(g ∥ q)\mathrm{KL}(g\,\|\,q). The first is KL(p ∥ g)\mathrm{KL}(p\,\|\,g) (end of Theorem 4). The first does not depend on qq; the second is ≥0\ge 0, with equality only for q=gq = g. ■\blacksquare

    For the two-bump target p=0.25 N(−3,1)+0.75 N(3,1)p = 0.25\,\mathcal{N}(-3, 1) + 0.75\,\mathcal{N}(3, 1): the mean is m=0.25⋅(−3)+0.75⋅3=1.5m = 0.25 \cdot (-3) + 0.75 \cdot 3 = 1.5, and E[X2]=1+9=10\mathbb{E}[X^2] = 1 + 9 = 10 (each bump has E[X2]=1+32\mathbb{E}[X^2] = 1 + 3^2), so the variance is 10−1.52=7.7510 - 1.5^2 = 7.75. The forward fit is q=N(1.5,7.75)q = \mathcal{N}(1.5, 7.75), a standard deviation of 2.782.78. It covers both bumps and puts its peak at x=1.5x = 1.5, where pp is small.

    Reverse KL, min⁡θKL(qθ ∥ p)\min_\theta \mathrm{KL}(q_\theta\,\|\,p). Now KL(qθ ∥ p)=Eqθ[log⁡qθ(X)−log⁡p(X)]\mathrm{KL}(q_\theta\,\|\,p) = \mathbb{E}_{q_\theta}[\log q_\theta(X) - \log p(X)]. Two consequences:

    • Mode seeking and local optima. A qθq_\theta on one bump avoids the gap, so it is a local optimum. There is one local optimum near each bump, and the start decides which one gradient descent finds. Why is the value close to −log⁡wk-\log w_k, where wkw_k is the weight of the bump? Where qθq_\theta has mass, p(x)≈wk N(x;μk,1)p(x) \approx w_k\,\mathcal{N}(x; \mu_k, 1), because the other bump is far away. If qθq_\theta equals that component, log⁡qθp≈log⁡1wk\log\frac{q_\theta}{p} \approx \log\frac{1}{w_k} everywhere on its mass. For the example, −log⁡0.75=0.288-\log 0.75 = 0.288 and −log⁡0.25=1.386-\log 0.25 = 1.386 nats; the exact optima are 0.2850.285 and 1.3781.378.
    • pp is needed only up to a constant. Suppose p=p~/Zp = \tilde p/Z, where p~\tilde p is known and the normalizing constant ZZ is not. Then KL(q ∥ p)=Eq[log⁡q−log⁡p~]+log⁡Z\mathrm{KL}(q\,\|\,p) = \mathbb{E}_q[\log q - \log\tilde p] + \log Z, and log⁡Z\log Z does not depend on θ\theta. You need samples of qq (you choose qq, so this is easy) and the unnormalized p~\tilde p. A Bayesian posterior p(z∣x)=p(x,z)/p(x)p(z \mid x) = p(x, z)/p(x) is exactly this case: p(x,z)p(x, z) is known, p(x)p(x) is not. This is why variational inference uses the reverse KL. The quantity log⁡Z−KL(q ∥ p)\log Z - \mathrm{KL}(q\,\|\,p) is the ELBO (lesson 09).
    Quick check

    Variational inference fits qϕ(z)q_\phi(z) to a posterior p(z∣x)p(z \mid x) by minimizing KL(qϕ ∥ p(⋅∣x))\mathrm{KL}(q_\phi\,\|\,p(\cdot \mid x)). Why this direction?

    Mean-field fits are too narrow. A mean-field (factorized) family assumes independent coordinates: q(z)=∏iqi(zi)q(z) = \prod_i q_i(z_i). Take a correlated Gaussian target and a factorized Gaussian qq.

    Theorem 7 (factorized Gaussian fits). Let p=N(0,Σ)p = \mathcal{N}(0, \Sigma) and q=N(0,diag⁡(s12,…,sd2))q = \mathcal{N}(0, \operatorname{diag}(s_1^2, \dots, s_d^2)).

    • The forward KL is smallest for si2=Σiis_i^2 = \Sigma_{ii}: the marginal variances.
    • The reverse KL is smallest for si2=1/(Σ−1)iis_i^2 = 1/(\Sigma^{-1})_{ii}, which is never larger than Σii\Sigma_{ii}.

    Proof. Use Theorem 5 with D=diag⁡(s12,…,sd2)D = \operatorname{diag}(s_1^2, \dots, s_d^2) and zero means.

    1. Forward: KL(p ∥ q)=12[∑iΣii/si2−d+∑ilog⁡si2−log⁡det⁡Σ]\mathrm{KL}(p\,\|\,q) = \frac12\big[\sum_i \Sigma_{ii}/s_i^2 - d + \sum_i\log s_i^2 - \log\det\Sigma\big]. The derivative with respect to si2s_i^2 is 12[−Σii/si4+1/si2]\frac12\big[-\Sigma_{ii}/s_i^4 + 1/s_i^2\big]. It is zero at si2=Σiis_i^2 = \Sigma_{ii}.
    2. Reverse: KL(q ∥ p)=12[∑i(Σ−1)ii si2−d+log⁡det⁡Σ−∑ilog⁡si2]\mathrm{KL}(q\,\|\,p) = \frac12\big[\sum_i (\Sigma^{-1})_{ii}\,s_i^2 - d + \log\det\Sigma - \sum_i\log s_i^2\big]. The derivative with respect to si2s_i^2 is 12[(Σ−1)ii−1/si2]\frac12\big[(\Sigma^{-1})_{ii} - 1/s_i^2\big]. It is zero at si2=1/(Σ−1)iis_i^2 = 1/(\Sigma^{-1})_{ii}.
    3. Each term has the form cu−log⁡ucu - \log u with c>0c > 0: in step 1 with u=1/si2u = 1/s_i^2, in step 2 with u=si2u = s_i^2. This function is convex in u>0u > 0, so the stationary points are the minima.
    4. 1/(Σ−1)ii1/(\Sigma^{-1})_{ii} is the conditional variance Var⁡(Xi∣Xrest)\operatorname{Var}(X_i \mid X_{\text{rest}}) of a Gaussian, and conditioning never increases a Gaussian variance. So 1/(Σ−1)ii≤Σii1/(\Sigma^{-1})_{ii} \le \Sigma_{ii}, with equality only when XiX_i is uncorrelated with the other coordinates. ■\blacksquare

    For Σ=(10.90.91)\Sigma = \begin{pmatrix} 1 & 0.9 \\ 0.9 & 1 \end{pmatrix}, the forward fit has variances 1 and the reverse fit has variances 1−0.92=0.191 - 0.9^2 = 0.19: a standard deviation of 0.440.44 instead of 1. The reverse fit sits inside the narrow ellipse and reports far too little uncertainty. Mean-field VI does this in general (Bishop, PRML §10.1.2).

    Interactive figure: loading…

    Press "Forward fit" and "Reverse fit". Blue: the 1σ1\sigma and 2σ2\sigma ellipses of the correlated target pp. Orange: the factorized qq. The forward fit matches the marginal variances and spills into the empty corners; the reverse fit shrinks to the conditional variances 1−ρ21 - \rho^2 and stays inside pp. Move ρ\rho to 0: both fits agree.

    forward KL(p∥q)\mathrm{KL}(p \Vert q) reverse KL(q∥p)\mathrm{KL}(q \Vert p)
    large penalty where p>0p > 0 and q≈0q \approx 0 q>0q > 0 and p≈0p \approx 0
    behaviour mode covering, often too wide mode seeking, often too narrow
    needs samples of pp samples of qq; pp up to a constant
    Gaussian qq moment matching, one optimum for a multimodal pp: one local optimum per mode
    used in maximum likelihood, cross-entropy training, distillation variational inference, ELBO, VAEs

    Answers to section 1. (1) h=log⁡ah = \log a, which is negative when a<1a < 1 m. In millimetres, Xmm=1000XX_{\text{mm}} = 1000X, so hh grows by log⁡1000=6.91\log 1000 = 6.91 nats (9.979.97 bits) for the same physical uncertainty. (2) The forward KL gives the wide q=N(1.5,2.782)q = \mathcal{N}(1.5, 2.78^2) that covers both bumps. The reverse KL gives a qq close to N(3,1)\mathcal{N}(3, 1) or N(−3,1)\mathcal{N}(-3, 1), depending on the start. (3) Too small. A factorized qq fitted by reverse KL has variances 1/(Σ−1)ii1/(\Sigma^{-1})_{ii}, the conditional variances, which are smaller than the marginal variances Σii\Sigma_{ii}.

    4. Worked example #

    (a) Units. XX is uniform on [0,0.5][0, 0.5] m.

    • In metres: h=log⁡0.5=−0.693h = \log 0.5 = -0.693 nats =−1= -1 bit.
    • In millimetres, XX is uniform on [0,500][0, 500]: h=log⁡500=6.215h = \log 500 = 6.215 nats.
    • The difference is 6.215−(−0.693)=6.908=log⁡10006.215 - (-0.693) = 6.908 = \log 1000, as Theorem 2 says with A=1000A = 1000.

    (b) A 2-D Gaussian and a change of units. X∼N(0,Σ)X \sim \mathcal{N}(0, \Sigma) with Σ=(10.80.81)\Sigma = \begin{pmatrix} 1 & 0.8 \\ 0.8 & 1 \end{pmatrix}.

    • det⁡Σ=1⋅1−0.82=0.36\det\Sigma = 1 \cdot 1 - 0.8^2 = 0.36.
    • h(X)=12log⁡((2πe)2⋅0.36)=log⁡(2πe)+12log⁡0.36=2.838−0.511=2.327h(X) = \frac12\log\big((2\pi e)^2 \cdot 0.36\big) = \log(2\pi e) + \frac12\log 0.36 = 2.838 - 0.511 = 2.327 nats.
    • Y=10XY = 10X: A=10IA = 10I, det⁡A=100\det A = 100, so h(Y)=2.327+log⁡100=2.327+4.605=6.932h(Y) = 2.327 + \log 100 = 2.327 + 4.605 = 6.932 nats.
    • A 1-D N(0,0.22)\mathcal{N}(0, 0.2^2): h=12log⁡(2πe)+log⁡0.2=1.419−1.609=−0.190h = \frac12\log(2\pi e) + \log 0.2 = 1.419 - 1.609 = -0.190 nats. Negative, because 0.2<0.2420.2 < 0.242.

    (c) Gaussian KL in 2-D. p0=N(0,I)p_0 = \mathcal{N}(0, I) and p1=N((1,0),diag⁡(2,0.5))p_1 = \mathcal{N}\big((1, 0), \operatorname{diag}(2, 0.5)\big).

    • Σ1−1=diag⁡(0.5,2)\Sigma_1^{-1} = \operatorname{diag}(0.5, 2), so the trace term is tr⁡(Σ1−1I)=0.5+2=2.5\operatorname{tr}(\Sigma_1^{-1}I) = 0.5 + 2 = 2.5.
    • Mean term: (1,0) Σ1−1 (1,0)⊤=0.5(1, 0)\,\Sigma_1^{-1}\,(1, 0)^\top = 0.5.
    • Log-det term: log⁡det⁡Σ1det⁡Σ0=log⁡11=0\log\frac{\det\Sigma_1}{\det\Sigma_0} = \log\frac{1}{1} = 0.
    • KL(p0 ∥ p1)=12(2.5+0.5−2+0)=0.5\mathrm{KL}(p_0\,\|\,p_1) = \frac12(2.5 + 0.5 - 2 + 0) = 0.5 nats.
    • The other direction: the trace term is tr⁡(Σ1)=2.5\operatorname{tr}(\Sigma_1) = 2.5, the mean term is 12⋅1=11^2 \cdot 1 = 1, the log-det term is log⁡11=0\log\frac{1}{1} = 0, so KL(p1 ∥ p0)=12(2.5+1−2)=0.75\mathrm{KL}(p_1\,\|\,p_0) = \frac12(2.5 + 1 - 2) = 0.75 nats. The asymmetry comes from the mean term: the same shift is measured in units of Σ1\Sigma_1 in one direction and of Σ0\Sigma_0 in the other.

    (d) Forward vs reverse on the two bumps p=0.25 N(−3,1)+0.75 N(3,1)p = 0.25\,\mathcal{N}(-3, 1) + 0.75\,\mathcal{N}(3, 1), by numerical integration (section 5):

    qq KL(p∥q)\mathrm{KL}(p \Vert q) KL(q∥p)\mathrm{KL}(q \Vert p)
    N(1.5,2.782)\mathcal{N}(1.5, 2.78^2), the forward fit 0.465 0.935
    N(3,1)\mathcal{N}(3, 1) 3.941 0.286
    N(−3,1)\mathcal{N}(-3, 1) 12.941 1.379

    Each fit wins its own objective by a wide margin. Theorem 6 checks out: KL(p ∥ N(3,1))=0.465+KL(N(1.5,7.75) ∥ N(3,1))\mathrm{KL}(p\,\|\,\mathcal{N}(3, 1)) = 0.465 + \mathrm{KL}(\mathcal{N}(1.5, 7.75)\,\|\,\mathcal{N}(3, 1)), and the 1-D formula gives log⁡12.784+7.75+2.252−12=−1.024+5−0.5=3.476\log\frac{1}{2.784} + \frac{7.75 + 2.25}{2} - \frac12 = -1.024 + 5 - 0.5 = 3.476; 0.465+3.476=3.9410.465 + 3.476 = 3.941 ✓.

    (e) Mean-field. Σ=(10.90.91)\Sigma = \begin{pmatrix} 1 & 0.9 \\ 0.9 & 1 \end{pmatrix}, det⁡Σ=0.19\det\Sigma = 0.19, Σ−1=10.19(1−0.9−0.91)\Sigma^{-1} = \frac{1}{0.19}\begin{pmatrix} 1 & -0.9 \\ -0.9 & 1 \end{pmatrix}.

    • (Σ−1)11=1/0.19=5.263(\Sigma^{-1})_{11} = 1/0.19 = 5.263, so the reverse fit has s12=s22=0.19s_1^2 = s_2^2 = 0.19.
    • The forward fit has s12=s22=Σ11=1s_1^2 = s_2^2 = \Sigma_{11} = 1.
    • The forward KL of the forward fit is 12[2−2+log⁡1−log⁡0.19]=0.830\frac12[2 - 2 + \log 1 - \log 0.19] = 0.830 nats; the reverse KL of the reverse fit is 12[2−2+log⁡0.19−log⁡0.192]=0.830\frac12[2 - 2 + \log 0.19 - \log 0.19^2] = 0.830 nats. (In this symmetric 2-D case the two numbers agree; in general they do not.)

    5. In code #

    SciPy has the entropies of standard distributions built in (.entropy(), in nats), and scipy.integrate.quad computes KL integrals in one dimension.

    import numpy as np
    from scipy.stats import norm, multivariate_normal, uniform, laplace, entropy
    from scipy.integrate import quad
    
    # (a) Differential entropy (nats): negative values and units
    print(uniform(scale=0.5).entropy(), uniform(scale=500).entropy())   # -0.6931 6.2146
    print(norm(scale=0.2).entropy())                                     # -0.1905
    
    # (b) Quantize N(0, 0.2^2) into bins of width d: H(X_d) - log(1/d) -> h(X)
    for d in [0.1, 0.01, 0.001]:
        P = np.diff(norm(scale=0.2).cdf(np.arange(-2, 2 + d / 2, d)))
        print(d, entropy(P), entropy(P) + np.log(d))
    # 0.1 2.1224 -0.1802 | 0.01 4.4148 -0.1904 | 0.001 6.7173 -0.1905
    
    # (c) A 2-D Gaussian and a change of units Y = 10 X
    S = np.array([[1.0, 0.8], [0.8, 1.0]])
    print(multivariate_normal(cov=S).entropy(), multivariate_normal(cov=100 * S).entropy())  # 2.3271 6.9322
    
    # (d) Maximum entropy at unit variance: uniform < Laplace < Gaussian
    print(uniform(scale=np.sqrt(12)).entropy(), laplace(scale=1 / np.sqrt(2)).entropy(), norm.entropy())
    # 1.2425 1.3466 1.4189
    
    # (e) KL between Gaussians: closed form vs numerical integration
    def gauss_kl(m0, S0, m1, S1):
        d, S1i, dm = len(m0), np.linalg.inv(S1), m1 - m0
        return 0.5 * (np.trace(S1i @ S0) + dm @ S1i @ dm - d + np.log(np.linalg.det(S1) / np.linalg.det(S0)))
    print(gauss_kl(np.zeros(1), np.eye(1), np.ones(1), 4 * np.eye(1)),
          quad(lambda x: norm.pdf(x) * (norm.logpdf(x) - norm.logpdf(x, 1, 2)), -20, 20)[0])   # 0.4431 0.4431
    
    # (f) Forward vs reverse KL on p = 0.25 N(-3, 1) + 0.75 N(3, 1)
    p = lambda x: 0.25 * norm.pdf(x, -3, 1) + 0.75 * norm.pdf(x, 3, 1)
    for mu, s in [(1.5, np.sqrt(7.75)), (3.0, 1.0), (-3.0, 1.0)]:
        fwd = quad(lambda x: p(x) * np.log(p(x) / norm.pdf(x, mu, s)), -30, 30, limit=400)[0]
        rev = quad(lambda x: norm.pdf(x, mu, s) * (norm.logpdf(x, mu, s) - np.log(p(x))), -30, 30, limit=400)[0]
        print(mu, round(fwd, 3), round(rev, 3))
    # 1.5 0.465 0.935 | 3.0 3.941 0.286 | -3.0 12.941 1.379
    
    # (g) Mean-field fits: forward keeps Sigma_ii, reverse uses 1/(Sigma^-1)_ii
    S = np.array([[1.0, 0.9], [0.9, 1.0]])
    print(np.diag(S), 1 / np.diag(np.linalg.inv(S)))   # [1. 1.] [0.19 0.19]
    

    Numerics: in the tails a density underflows to 0 and np.log(0) gives -inf. Work with log-densities (norm.logpdf, scipy.special.logsumexp for mixtures) whenever a KL integrand reaches far into the tails.

    6. Where it shows up #

    • VAEs. The encoder outputs qϕ(z∣x)=N(μ,diag⁡(σ2))q_\phi(z \mid x) = \mathcal{N}(\mu, \operatorname{diag}(\sigma^2)), and the KL to the prior N(0,I)\mathcal{N}(0, I) is the closed form of section 3.6. The whole objective is a reverse-KL fit to the posterior (lesson 09).
    • Variational inference in science. Mean-field VI for Bayesian neural networks, inverse problems and data assimilation is fast, but its variances are often too small (Theorem 7). Check the spread against MCMC or an ensemble before you trust an uncertainty band.
    • Maximum likelihood and distillation. Fitting by log-loss and distilling a teacher on soft labels minimize forward KLs: the student must cover everything the teacher allows. The KL penalty of RLHF, KL(πθ ∥ πref)\mathrm{KL}(\pi_\theta\,\|\,\pi_{\text{ref}}), is a reverse KL, estimated on samples of the policy.
    • Normalizing flows. The training loss of a flow is −log⁡pX(g−1(y))−log⁡∣det⁡Jg−1(y)∣-\log p_X(g^{-1}(y)) - \log|\det J_{g^{-1}}(y)|, the change of variables of section 3.3 applied to every data point.
    • Bayesian experimental design. For a Gaussian posterior, the information gained by an experiment is h(prior)−h(posterior)=12log⁡det⁡Σpriordet⁡Σposth(\text{prior}) - h(\text{posterior}) = \frac12\log\frac{\det\Sigma_{\text{prior}}}{\det\Sigma_{\text{post}}}, a difference of entropies, so the units cancel. This is the D-optimal design criterion.
    • Scientific data and units. A Gaussian fit to a forecast ensemble has entropy 12log⁡det⁡(2πeΣ)\frac12\log\det(2\pi e\Sigma). Precipitation in mm and in m differ by log⁡1000\log 1000 per dimension. Report differences, KL divergences or mutual information instead.

    7. Common mistakes #

    • Treating hh like HH. hh can be negative and changes with the units: h(cX)=h(X)+log⁡∣c∣h(cX) = h(X) + \log|c|. A discrete HH is ≥0\ge 0 and does not change under relabelling.
    • Reading hh as the limit of HH. H(XΔ)→∞H(X_\Delta) \to \infty as Δ→0\Delta \to 0. hh is the finite part after removing log⁡(1/Δ)\log(1/\Delta).
    • "A negative log-likelihood below 0 is a bug." For densities it is not: a density can exceed 1. Only a discrete (or dequantized) likelihood bounds a code length (lesson 04).
    • Swapping the directions. Forward KL(p ∥ q)\mathrm{KL}(p\,\|\,q): average under the data, mode covering, maximum likelihood. Reverse KL(q ∥ p)\mathrm{KL}(q\,\|\,p): average under the model, mode seeking, VI.
    • Gaussian KL slips. Mixing σ\sigma and σ2\sigma^2, forgetting the 12\frac12 or the −d-d, or putting Σ0−1\Sigma_0^{-1} instead of Σ1−1\Sigma_1^{-1} in the trace.
    • Trusting mean-field variances. A factorized reverse-KL fit gives conditional variances, which are too small when the target has correlations.

    8. Check yourself #

    1. Give the differential entropy of the uniform density on [0,18][0, \frac18] in bits. X∼N(0,σ2)X \sim \mathcal{N}(0, \sigma^2) and Y=3X−5Y = 3X - 5: what is h(Y)−h(X)h(Y) - h(X)?
      Answerlog⁡218=−3\log_2\frac18 = -3 bits. h(Y)−h(X)=log⁡3=1.099h(Y) - h(X) = \log 3 = 1.099 nats; the shift −5-5 does not matter.
    2. A normalizing flow on images scaled to [0,1)[0, 1) reports a log-density of +8000+8000 nats per image. Is a positive log-density (negative NLL) a bug?
      AnswerNo. A density on [0,1)D[0, 1)^D can be much larger than 1, so log⁡p\log p can be positive. To compare with a code length, convert to bits per dimension on the 8-bit scale ([lesson 04](/information-theory/04-cross-entropy-loss/)).
    3. A VAE encoder outputs μ=(1,0)\mu = (1, 0) and σ=(0.5,0.5)\sigma = (0.5, 0.5). Compute the KL to N(0,I)\mathcal{N}(0, I).
      Answer12∑j(σj2+μj2−1−log⁡σj2)=12[(0.25+1−1+1.386)+(0.25+0−1+1.386)]=12(1.636+0.636)=1.136\frac12\sum_j(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2) = \frac12\big[(0.25 + 1 - 1 + 1.386) + (0.25 + 0 - 1 + 1.386)\big] = \frac12(1.636 + 0.636) = 1.136 nats.
    4. The target is p=0.5 N(−5,1)+0.5 N(5,1)p = 0.5\,\mathcal{N}(-5, 1) + 0.5\,\mathcal{N}(5, 1). Give the forward-KL Gaussian fit, and the approximate value of the reverse KL at a reverse-KL local optimum.
      AnswerForward: mean 0 and variance 1+25−0=261 + 25 - 0 = 26, so q=N(0,26)q = \mathcal{N}(0, 26). Reverse: q≈N(±5,1)q \approx \mathcal{N}(\pm 5, 1) with KL(q ∥ p)≈−log⁡0.5=log⁡2=0.693\mathrm{KL}(q\,\|\,p) \approx -\log 0.5 = \log 2 = 0.693 nats (numerically 0.69310.6931).
    5. A posterior is N(0,Σ)\mathcal{N}(0, \Sigma) with unit variances and correlation 0.60.6. Mean-field VI fits q=N(0,diag⁡(s12,s22))q = \mathcal{N}(0, \operatorname{diag}(s_1^2, s_2^2)). What variances does it find?
      Answersi2=1/(Σ−1)ii=1−0.62=0.64s_i^2 = 1/(\Sigma^{-1})_{ii} = 1 - 0.6^2 = 0.64, a standard deviation of 0.80.8 instead of 1.
    6. Why does the Gaussian have the largest entropy among densities with a given covariance, in one sentence?
      AnswerFor any pp with the same mean and covariance, h(g)−h(p)=KL(p ∥ g)≥0h(g) - h(p) = \mathrm{KL}(p\,\|\,g) \ge 0, because log⁡g\log g is quadratic and so its mean under pp equals its mean under gg.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Define the differential entropy of a continuous random variable with density pp.

    2. What is the differential entropy of N(μ,σ2)\mathcal{N}(\mu, \sigma^2), and when is it negative?

    3. What is the entropy of a dd-dimensional Gaussian N(μ,Σ)\mathcal{N}(\mu, \Sigma)?

    4. How does hh change under Y=AX+bY = AX + b with AA invertible?

    5. Relate the entropy of XX quantized into bins of width Δ\Delta to h(X)h(X).

    6. Why does the KL divergence between densities not depend on the units?

    7. Which density has the largest differential entropy for a given mean and covariance?

    8. Give KL(N(μ0,σ02) ∥ N(μ1,σ12))\mathrm{KL}(\mathcal{N}(\mu_0, \sigma_0^2)\,\|\,\mathcal{N}(\mu_1, \sigma_1^2)).

    9. What Gaussian minimizes the forward KL KL(p ∥ q)\mathrm{KL}(p\,\|\,q) to a target pp, and why is it often too wide?

    10. Why does variational inference minimize the reverse KL, and what is the side effect?

    Open the review →

    9. Interview angle #

    • "Entropy of a dd-dimensional Gaussian? Why can it be negative?" 12log⁡((2πe)ddet⁡Σ)\frac12\log((2\pi e)^d\det\Sigma). A density can be larger than 1 when det⁡Σ\det\Sigma is small, so −log⁡p-\log p can be negative on average.
    • "What happens to differential entropy if you rescale the data?" It shifts by log⁡∣det⁡A∣\log|\det A|; so units matter. KL and mutual information do not change.
    • "Derive the KL between two Gaussians." Use E[Z⊤MZ]=tr⁡(MC)+m⊤Mm\mathbb{E}[Z^\top MZ] = \operatorname{tr}(MC) + m^\top Mm for both log-densities (Theorem 5). Know the 1-D formula and the VAE term 12∑j(σj2+μj2−1−log⁡σj2)\frac12\sum_j(\sigma_j^2 + \mu_j^2 - 1 - \log\sigma_j^2).
    • "Forward vs reverse KL?" Forward: mode covering, needs data samples, equals maximum likelihood, moment matching for Gaussians. Reverse: mode seeking, needs the target only up to a constant, used by VI; underestimates variance.
    • "Why do VAEs or mean-field VI give overconfident posteriors?" Reverse KL avoids regions where the posterior is small; a factorized qq on a correlated posterior gets the conditional variances.

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. gaussian_entropy(cov) from the log-determinant, checked against scipy.stats.multivariate_normal(...).entropy() and against h(AX)=h(X)+log⁡∣det⁡A∣h(AX) = h(X) + \log|\det A|.
    2. The quantization experiment: quantized_entropy(sigma, delta) and the limit H(XΔ)−log⁡(1/Δ)→hH(X_\Delta) - \log(1/\Delta) \to h.
    3. gaussian_kl(mu0, cov0, mu1, cov1) from Theorem 5, checked against a Monte Carlo estimate.
    4. Forward fit (moment matching) and reverse fit (a local optimizer from two starts) of one Gaussian to the two-bump target.
    5. Mean-field reverse-KL fit of a correlated Gaussian by coordinate ascent; compare its variances with Σii\Sigma_{ii}.

    11. Watch and read #

    A short animation of the two fits of section 2.2.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Forward and reverse KL, and how to estimate KL from samples when there is no closed form.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Why differential entropy can be negative and depends on the coordinates, with Gaussian examples.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A careful lecture proof of the maximum-entropy results of section 3.5.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play