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.
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∣detJ∣, the same term as in the change of variables for h (section 3.3).
Gaussian uncertainty in science. The entropy of a Gaussian posterior,
21logdet(2πeΣ), 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 is the natural logarithm and gives nats; log2 gives bits. For
densities we work in nats, as NumPy, SciPy and PyTorch do.
Let X have a density p(x). Cut the real line into bins of width Δ and record only
the bin that X falls in. This gives a discrete variable XΔ, and discrete variables have an
entropy H(XΔ) (lesson 01). What happens when
the bins get smaller?
A small bin i around a point xi has probability Pi≈p(xi)Δ (height times width).
So H(XΔ)=−∑iPilogPi≈−∑ip(xi)Δlog(p(xi)Δ).
Split the log of the product: log(p(xi)Δ)=logp(xi)+logΔ. This gives two sums:
H(XΔ)≈−i∑p(xi)logp(xi)Δ−logΔi∑p(xi)Δ.
The first sum is a Riemann sum for −∫p(x)logp(x)dx. In the second sum,
∑ip(xi)Δ≈1 (the total probability). So
H(XΔ)≈h(X)+logΔ1,h(X)=−∫p(x)logp(x)dx.
The number h(X) is the differential entropy. The term log(1/Δ) grows without bound:
each halving of Δ adds one more yes/no question (1 bit) to locate X. 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Δ); that limit is +∞.
Interactive figure: loading…
Make the bins smaller with the Δ slider. Top: the density p(x) (blue)
and the histogram of XΔ (yellow, bin probability divided by Δ).
Bottom: H(XΔ) grows by about 1 bit per halving of Δ, while
H(XΔ)−log(1/Δ) (grey, dashed) settles at h(X); the
aqua gap is log(1/Δ). Then press "σ = 0.2" and notice that the density
goes above the dashed line at 1 and h(X) becomes negative.
Why h 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,21] equals 2 on its interval, so
−logp(x)=−log2<0 everywhere, and h=−log2=−1 bit. A discrete entropy is never
negative, because every probability is at most 1.
Why h depends on the units. The bin width Δ has units. One millimetre is 10001
of a metre, so the same physical bins give log(1/Δ) values that differ by log1000. The
remainder h changes by the same amount (section 3.3).
Quick check
X is uniform on [0,21]. What is its differential entropy in bits?
Why.
The density is p(x)=2 on [0,21], so h=−∫01/22log22dx=−log22=−1 bit. In general, the uniform density on [0,a] has h=loga, which is negative for a<1. Differential entropy can be negative because a density can be larger than 1.
The second picture is about fitting. A target density p has two bumps. We want the single
Gaussian q=N(μ,σ2) that is "closest" to p. KL is not symmetric
(lesson 03), so there are two different questions.
Forward KL, KL(p∥q)=Ex∼p[logp(x)−logq(x)]. The
average is over p. Where p has mass and q is tiny, −logq(x) is huge. So q must put
mass everywhere p has mass. The fit is wide and covers both bumps: mode covering.
Reverse KL, KL(q∥p)=Ex∼q[logq(x)−logp(x)]. The
average is over q. Where q has mass and p is tiny, −logp(x) is huge. So q must avoid
every region where p 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.25N(−3,1)+0.75N(3,1); the orange curve is
the Gaussian q. Drag its peak to choose a start (left and right move μ, up and down change σ),
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?
Why.
The forward KL averages log(p/q) under p, so it punishes q≈0 wherever p has mass. To cover both bumps, the single Gaussian must be wide, and then it also covers the gap. The reverse KL averages under q and punishes mass where p≈0, so it avoids the gap and sits on one bump.
Let X be a continuous random variable with density p on Rd. Its differential
entropy is
h(X)=−∫p(x)logp(x)dx=E[−logp(X)],
with 0log0=0, when the integral exists. We write lower-case h to separate it from the
discrete H. Two examples, step by step:
Uniform on [0,a].p(x)=1/a on the interval, so −logp(x)=loga for every x that
can occur. The average of a constant is the constant: h=loga. It is negative for a<1.
Gaussian N(μ,σ2). The density is
p(x)=2πσ21exp(−2σ2(x−μ)2), so
−logp(x)=21log(2πσ2)+2σ2(x−μ)2.
Take the mean. E[(X−μ)2]=σ2, so the second term has mean 21. With
21=21loge:
h=21log(2πσ2)+21=21log(2πeσ2).
The mean μ does not appear: shifting a density does not change its shape. For σ=1,h=1.419 nats =2.047 bits. h<0 exactly when 2πeσ2<1, that is,
σ<1/2πe≈0.242.
Theorem 1 (quantization). Let p be continuous and let plogp be Riemann integrable. Let
XΔ be X quantized into bins of width Δ. Then H(XΔ)−log(1/Δ)→h(X)
as Δ→0.
Proof of Theorem 1 (Cover and Thomas, Theorem 8.3.1)
By the mean value theorem, each bin [iΔ,(i+1)Δ) contains a point xi with
Pi=∫bin ip(x)dx=p(xi)Δ exactly.
Then H(XΔ)=−∑ip(xi)Δlog(p(xi)Δ)=−∑ip(xi)Δlogp(xi)−logΔ∑ip(xi)Δ.
∑ip(xi)Δ=∑iPi=1, so H(XΔ)+logΔ=−∑ip(xi)logp(xi)Δ.
The right side is a Riemann sum of −plogp, and it tends to h(X) as Δ→0.■
In d dimensions, cubes of side Δ give H(XΔ)≈h(X)+dlog(1/Δ).
3.2 The multivariate Gaussian: entropy is a log-volume #
Let X∼N(μ,Σ) in d dimensions, with Σ positive definite. Its density is
p(x)=((2π)ddetΣ)−1/2exp(−21(x−μ)⊤Σ−1(x−μ)), so
−logp(x)=2dlog(2π)+21logdetΣ+21(x−μ)⊤Σ−1(x−μ).
The quadratic term has mean d. (Proof: E[(X−μ)⊤Σ−1(X−μ)]=E[tr(Σ−1(X−μ)(X−μ)⊤)]=tr(Σ−1Σ)=tr(Id)=d.)
So
Only detΣ enters. The ellipse (in d dimensions, the ellipsoid)
{x:(x−μ)⊤Σ−1(x−μ)≤1} has volume proportional to detΣ
(linear algebra lesson 03: the determinant scales
volume). So the entropy of a Gaussian is the log of the volume of its 1σ ellipsoid, plus a
constant. When two coordinates become almost perfectly correlated, the ellipse flattens to a line,
detΣ→0, and h→−∞.
Interactive figure: loading…
Change σ1,σ2 and the correlation ρ. The blue ellipse is
the 1σ ellipse of X; its area is πdetΣ and the readout gives
h(X)=21log((2πe)2detΣ). Push ρ towards ±1: the ellipse flattens and
h→−∞. Then move a1 or a2: the yellow dashed ellipse is
Y=AX with A=diag(a1,a2), a change of units, and h shifts by log∣detA∣.
Theorem 2 (affine maps). Let Y=AX+b, where A is an invertible d×d matrix and b
a vector. Then
h(Y)=h(X)+log∣detA∣.
Proof.
Change of variables (calculus lesson 10): the
density of Y is pY(y)=pX(A−1(y−b))/∣detA∣. A box of volume V maps to a box of
volume ∣detA∣V with the same probability, so the density divides by ∣detA∣.
At y=Ax+b this reads −logpY(y)=−logpX(x)+log∣detA∣.
Take the mean over X. The shift b has disappeared: moving a density does not change its
shape. ■
Check with Gaussians.ΣY=AΣA⊤ and det(AΣA⊤)=(detA)2detΣ, so
21logdetΣY=21logdetΣ+log∣detA∣. ✓
The units trap. A change of units is a map Y=cX. Metres to millimetres is c=1000, so h
grows by log1000=6.908 nats =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 g with Jacobian matrix Jg, the same three steps give
pY(g(x))=pX(x)/∣detJg(x)∣ and
h(g(X))=h(X)+E[log∣detJg(X)∣].
A normalizing flow uses the first identity in log form:
logpY(y)=logpX(x)−log∣detJg(x)∣ with x=g−1(y). Flow architectures are designed
so that log∣detJg∣ is cheap (triangular Jacobians). Example: X∼N(0,1) and
g(x)=x3:h(X3)=h(X)+E[log3X2]=1.419+1.099−1.270=1.247 nats, where
E[logX2]=−(γ+log2)=−1.270(γ=0.5772 is Euler's constant). If A is
singular, Y=AX lives on a lower-dimensional subspace and has no density on Rd; its
differential entropy is −∞ in the limit.
3.4 KL divergence for densities: no units problem #
For densities p and q on Rd, the KL divergence is
KL(p∥q)=∫p(x)logq(x)p(x)dx=Ep[logq(X)p(X)].
It is finite only if q(x)>0 wherever p(x)>0 (up to sets of zero probability). Gibbs'
inequality still holds:KL(p∥q)≥0, with equality only when p=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), because the two log(1/Δ) terms cancel.
Theorem 3 (KL does not depend on the coordinates). Let g be a smooth invertible map, and let
pY,qY be the densities of g(X) when X∼p and when X∼q. Then
KL(pY∥qY)=KL(p∥q).
Proof.
Both densities pick up the same Jacobian factor: pY(g(x))=p(x)/∣detJg(x)∣ and
qY(g(x))=q(x)/∣detJg(x)∣.
In the ratio the factor cancels: qY(g(x))pY(g(x))=q(x)p(x).
The KL is the mean of the log of this ratio under p, so it does not change. ■
So measuring in millimetres instead of metres changes every h, but no KL divergence and no mutual
information. This is why ML objectives use KL and mutual information, not h alone.
Quick check
Two forecast distributions p and q for a temperature are given in kelvin. You convert both to °F (y=1.8x+c). What changes?
Why.
h(AX+b)=h(X)+log∣detA∣, and here A=1.8. For the KL, both densities are divided by the same factor 1.8, which cancels in p/q. KL divergence and mutual information do not depend on the units; differential entropy does.
Theorem 4 (maximum entropy). Among all densities on Rd with mean μ and covariance
Σ(Σ positive definite), the Gaussian g=N(μ,Σ) has the largest
differential entropy, h(g)=21log((2πe)ddetΣ), and it is the only one.
Why this is true (idea).logg(x) is a quadratic function of x. 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 g". Gibbs' inequality then does the rest.
Proof.
Let p have mean μ and covariance Σ. By Gibbs,
0≤KL(p∥g)=Ep[logp]−Ep[logg]=−h(p)−Ep[logg(X)].
logg(x)=−21log((2π)ddetΣ)−21(x−μ)⊤Σ−1(x−μ).
The quadratic term has mean tr(Σ−1Σ)=d under p, exactly as under
g (section 3.2). So Ep[logg(X)]=Eg[logg(X)]=−h(g).
Step 1 becomes 0≤−h(p)+h(g), so h(p)≤h(g). Equality holds only if
KL(p∥g)=0, that is, p=g.■
Step 4 says more: for every p with the same mean and covariance,
h(g)−h(p)=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. The Gaussian has the largest h; the compared shape is
yellow, and the aqua gap is
KL(p∥Gaussian). Move σ: every h shifts by logσ, but the gaps stay
the same.
At unit variance: the two bumps of the figure have h=1.1659 nats; uniform on [−3,3] has
h=log12=1.2425 nats; Laplace with scale b=1/2 has h=1+log(2b)=1.3466 nats;
the Gaussian has 1.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∣ gives the Laplace.
Each term has a meaning: the trace compares the spreads, the quadratic term (the Mahalanobis
distance of the means, measured in units of Σ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. KL behaves like
half a squared distance.
The VAE term:KL(N(μ,diag(σ2))∥N(0,I))=21∑j(σj2+μj2−1−logσj2).
Proof of Theorem 5
KL=E0[logp0(X)−logp1(X)], where E0 is the mean under p0
and logpi(x)=−2dlog2π−21logdetΣi−21(x−μi)⊤Σi−1(x−μi).
One identity does all the work. If Z has mean m and covariance C, then
E[Z⊤MZ]=E[tr(MZZ⊤)]=tr(M(C+mm⊤))=tr(MC)+m⊤Mm.
Under p0,X−μ0 has mean 0 and covariance Σ0, so
E0[(X−μ0)⊤Σ0−1(X−μ0)]=tr(Id)=d.
X−μ1 has mean μ0−μ1 and covariance Σ0, so
E0[(X−μ1)⊤Σ1−1(X−μ1)]=tr(Σ1−1Σ0)+(μ0−μ1)⊤Σ1−1(μ0−μ1).
Subtract the two logs. The 2dlog2π terms cancel. The log-dets give
21log(detΣ1/detΣ0). The quadratic terms give 21(step 4−step 3).■
Example.KL(N(0,1)∥N(1,22))=log2+81+1−21=0.693+0.25−0.5=0.443
nats. The other direction is log21+24+1−21=1.307 nats: not symmetric.
Quick check
What is KL(N(2,1)∥N(0,1))?
Why.
With equal variances the log term is 0 and the spread term is 21−21=0, so only the mean term is left: (μ0−μ1)2/(2σ2)=4/2=2 nats. KL grows like half the squared distance of the means, not like the distance itself.
Fix a target p and a family of models qθ (for example, all Gaussians). Section 2.2 showed
the two fits in a picture. Now the precise statements.
Forward KL, minθKL(p∥qθ). Write
KL(p∥qθ)=−h(p)−Ep[logqθ(X)]. The first term does not depend on
θ. So minimizing the forward KL is maximizing Ep[logqθ(X)]:maximum
likelihood (lesson 04). You need samples of p
(the data), not its density.
Theorem 6 (forward KL to a Gaussian is moment matching). Let p have mean m and covariance
C (positive definite), and let g=N(m,C). For every Gaussian q,
KL(p∥q)=KL(p∥g)+KL(g∥q).
So the best Gaussian is q=g:match the mean and the covariance, and there is only one optimum.
Proof.
logq is a quadratic function of x, so Ep[logq]=Eg[logq] (step 3 of Theorem 4).
The second bracket is KL(g∥q). The first is KL(p∥g) (end of Theorem 4).
The first does not depend on q; the second is ≥0, with equality only for q=g.■
For the two-bump target p=0.25N(−3,1)+0.75N(3,1): the mean is
m=0.25⋅(−3)+0.75⋅3=1.5, and E[X2]=1+9=10 (each bump has
E[X2]=1+32), so the variance is 10−1.52=7.75. The forward fit is
q=N(1.5,7.75), a standard deviation of 2.78. It covers both bumps and puts its peak at
x=1.5, where p is small.
Reverse KL, minθKL(qθ∥p). Now
KL(qθ∥p)=Eqθ[logqθ(X)−logp(X)]. Two consequences:
Mode seeking and local optima. A qθ 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 −logwk, where wk is the weight of the bump? Where qθ has
mass, p(x)≈wkN(x;μk,1), because the other bump is far away. If qθ
equals that component, logpqθ≈logwk1 everywhere on its mass.
For the example, −log0.75=0.288 and −log0.25=1.386 nats; the exact optima are 0.285 and 1.378.
p is needed only up to a constant. Suppose p=p~/Z, where p~ is known and
the normalizing constant Z is not. Then
KL(q∥p)=Eq[logq−logp~]+logZ, and logZ does not depend on
θ. You need samples of q (you choose q, so this is easy) and the unnormalized p~.
A Bayesian posterior p(z∣x)=p(x,z)/p(x) is exactly this case: p(x,z) is known, p(x)
is not. This is why variational inference uses the reverse KL. The quantity
logZ−KL(q∥p) is the ELBO (lesson 09).
Quick check
Variational inference fits qϕ(z) to a posterior p(z∣x) by minimizing KL(qϕ∥p(⋅∣x)). Why this direction?
Why.
KL(q∥p(⋅∣x))=Eq[logq(z)−logp(x,z)]+logp(x), and logp(x) is a constant. The forward KL would need samples of the posterior, which is what we cannot get. The reverse KL is not always smaller, and it is mode seeking, not mode covering. No KL is ever negative.
Mean-field fits are too narrow. A mean-field (factorized) family assumes independent
coordinates: q(z)=∏iqi(zi). Take a correlated Gaussian target and a factorized Gaussian q.
Theorem 7 (factorized Gaussian fits). Let p=N(0,Σ) and
q=N(0,diag(s12,…,sd2)).
The forward KL is smallest for si2=Σii: the marginal variances.
The reverse KL is smallest for si2=1/(Σ−1)ii, which is never larger than Σii.
Proof. Use Theorem 5 with D=diag(s12,…,sd2) and zero means.
Forward: KL(p∥q)=21[∑iΣii/si2−d+∑ilogsi2−logdetΣ].
The derivative with respect to si2 is 21[−Σii/si4+1/si2]. It is zero at si2=Σii.
Reverse: KL(q∥p)=21[∑i(Σ−1)iisi2−d+logdetΣ−∑ilogsi2].
The derivative with respect to si2 is 21[(Σ−1)ii−1/si2]. It is zero at si2=1/(Σ−1)ii.
Each term has the form cu−logu with c>0: in step 1 with u=1/si2, in step 2 with
u=si2. This function is convex in u>0, so the stationary points are the minima.
1/(Σ−1)ii is the conditional variance Var(Xi∣Xrest) of a
Gaussian, and conditioning never increases a Gaussian variance. So 1/(Σ−1)ii≤Σii,
with equality only when Xi is uncorrelated with the other coordinates. ■
For Σ=(10.90.91), the forward fit has variances 1 and
the reverse fit has variances 1−0.92=0.19: a standard deviation of 0.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σ and 2σ
ellipses of the correlated target p.Orange: the factorized q. The forward
fit matches the marginal variances and spills into the empty corners; the reverse fit shrinks to the
conditional variances 1−ρ2 and stays inside p. Move ρ to 0: both fits agree.
forward KL(p∥q)
reverse KL(q∥p)
large penalty where
p>0 and q≈0
q>0 and p≈0
behaviour
mode covering, often too wide
mode seeking, often too narrow
needs
samples of p
samples of q;p up to a constant
Gaussian q
moment matching, one optimum
for a multimodal p: one local optimum per mode
used in
maximum likelihood, cross-entropy training, distillation
variational inference, ELBO, VAEs
Answers to section 1. (1) h=loga, which is negative when a<1 m. In millimetres,
Xmm=1000X, so h grows by log1000=6.91 nats (9.97 bits) for the same physical
uncertainty. (2) The forward KL gives the wide q=N(1.5,2.782) that covers both bumps.
The reverse KL gives a q close to N(3,1) or N(−3,1), depending on the start.
(3) Too small. A factorized q fitted by reverse KL has variances 1/(Σ−1)ii, the
conditional variances, which are smaller than the marginal variances Σii.
Y=10X:A=10I,detA=100, so h(Y)=2.327+log100=2.327+4.605=6.932 nats.
A 1-D N(0,0.22):h=21log(2πe)+log0.2=1.419−1.609=−0.190 nats. Negative,
because 0.2<0.242.
(c) Gaussian KL in 2-D.p0=N(0,I) and p1=N((1,0),diag(2,0.5)).
Σ1−1=diag(0.5,2), so the trace term is tr(Σ1−1I)=0.5+2=2.5.
Mean term: (1,0)Σ1−1(1,0)⊤=0.5.
Log-det term: logdetΣ0detΣ1=log11=0.
KL(p0∥p1)=21(2.5+0.5−2+0)=0.5 nats.
The other direction: the trace term is tr(Σ1)=2.5, the mean term is 12⋅1=1,
the log-det term is log11=0, so KL(p1∥p0)=21(2.5+1−2)=0.75 nats.
The asymmetry comes from the mean term: the same shift is measured in units of Σ1 in one
direction and of Σ0 in the other.
(d) Forward vs reverse on the two bumpsp=0.25N(−3,1)+0.75N(3,1),
by numerical integration (section 5):
q
KL(p∥q)
KL(q∥p)
N(1.5,2.782), the forward fit
0.465
0.935
N(3,1)
3.941
0.286
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)), and the
1-D formula gives log2.7841+27.75+2.25−21=−1.024+5−0.5=3.476;0.465+3.476=3.941 ✓.
(Σ−1)11=1/0.19=5.263, so the reverse fit has s12=s22=0.19.
The forward fit has s12=s22=Σ11=1.
The forward KL of the forward fit is 21[2−2+log1−log0.19]=0.830 nats; the reverse KL
of the reverse fit is 21[2−2+log0.19−log0.192]=0.830 nats. (In this symmetric
2-D case the two numbers agree; in general they do not.)
SciPy has the entropies of standard distributions built in (.entropy(), in nats), and
scipy.integrate.quad computes KL integrals in one dimension.
importnumpyasnpfromscipy.statsimportnorm,multivariate_normal,uniform,laplace,entropyfromscipy.integrateimportquad# (a) Differential entropy (nats): negative values and unitsprint(uniform(scale=0.5).entropy(),uniform(scale=500).entropy())# -0.6931 6.2146print(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)fordin[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 XS=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 < Gaussianprint(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 integrationdefgauss_kl(m0,S0,m1,S1):d,S1i,dm=len(m0),np.linalg.inv(S1),m1-m0return0.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(lambdax: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=lambdax:0.25*norm.pdf(x,-3,1)+0.75*norm.pdf(x,3,1)formu,sin[(1.5,np.sqrt(7.75)),(3.0,1.0),(-3.0,1.0)]:fwd=quad(lambdax:p(x)*np.log(p(x)/norm.pdf(x,mu,s)),-30,30,limit=400)[0]rev=quad(lambdax: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)_iiS=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.
VAEs. The encoder outputs qϕ(z∣x)=N(μ,diag(σ2)), and the
KL to the prior 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), is a reverse KL, estimated on samples of the policy.
Normalizing flows. The training loss of a flow is −logpX(g−1(y))−log∣detJg−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)=21logdetΣpostdetΣprior,
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
21logdet(2πeΣ). Precipitation in mm and in m differ by log1000 per dimension.
Report differences, KL divergences or mutual information instead.
Treating h like H.h can be negative and changes with the units:
h(cX)=h(X)+log∣c∣. A discrete H is ≥0 and does not change under relabelling.
Reading h as the limit of H.H(XΔ)→∞ as Δ→0.h is the finite part
after removing log(1/Δ).
"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): average under the data, mode covering,
maximum likelihood. Reverse KL(q∥p): average under the model, mode seeking, VI.
Gaussian KL slips. Mixing σ and σ2, forgetting the 21 or the −d, or
putting Σ0−1 instead of Σ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.
Give the differential entropy of the uniform density on [0,81] in bits. X∼N(0,σ2) and
Y=3X−5: what is h(Y)−h(X)?Answerlog281=−3 bits. h(Y)−h(X)=log3=1.099 nats; the shift −5 does not matter.
A normalizing flow on images scaled to [0,1) reports a log-density of +8000 nats per image.
Is a positive log-density (negative NLL) a bug?AnswerNo. A density on [0,1)D can be much larger than 1, so logp 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/)).
A VAE encoder outputs μ=(1,0) and σ=(0.5,0.5). Compute the KL to N(0,I).Answer21∑j(σj2+μj2−1−logσj2)=21[(0.25+1−1+1.386)+(0.25+0−1+1.386)]=21(1.636+0.636)=1.136 nats.
The target is p=0.5N(−5,1)+0.5N(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=26, so q=N(0,26). Reverse: q≈N(±5,1) with KL(q∥p)≈−log0.5=log2=0.693 nats (numerically 0.6931).
A posterior is N(0,Σ) with unit variances and correlation 0.6. Mean-field VI fits
q=N(0,diag(s12,s22)). What variances does it find?Answersi2=1/(Σ−1)ii=1−0.62=0.64, a standard deviation of 0.8 instead of 1.
Why does the Gaussian have the largest entropy among densities with a given covariance, in one sentence?AnswerFor any p with the same mean and covariance, h(g)−h(p)=KL(p∥g)≥0, because logg is quadratic and so its mean under p equals its mean under g.
Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
Define the differential entropy of a continuous random variable with density p.
h(X)=−∫p(x)logp(x)dx=E[−logp(X)].
What is the differential entropy of N(μ,σ2), and when is it negative?
21log(2πeσ2) nats. It is negative for σ<1/2πe≈0.242.
What is the entropy of a d-dimensional Gaussian N(μ,Σ)?
21log((2πe)ddetΣ). Only the volume term detΣ matters, not μ.
How does h change under Y=AX+b with A invertible?
h(Y)=h(X)+log∣detA∣. The shift b has no effect.
Relate the entropy of X quantized into bins of width Δ to h(X).
H(XΔ)≈h(X)+log(1/Δ). The discrete entropy goes to infinity as Δ→0;h is the finite remainder.
Why does the KL divergence between densities not depend on the units?
Under an invertible map both densities are divided by the same Jacobian factor, which cancels in the ratio p/q.
Which density has the largest differential entropy for a given mean and covariance?
The Gaussian N(μ,Σ). For any other p with the same moments, h(g)−h(p)=KL(p∥g)>0.
Give KL(N(μ0,σ02)∥N(μ1,σ12)).
logσ0σ1+2σ12σ02+(μ0−μ1)2−21.
What Gaussian minimizes the forward KL KL(p∥q) to a target p, and why is it often too wide?
The Gaussian with the mean and covariance of p (moment matching). It must cover all the mass of p, so for a multimodal p it also covers the gaps.
Why does variational inference minimize the reverse KL, and what is the side effect?
It needs only samples of q and the unnormalized target, since logZ is a constant. It is mode seeking: mean-field fits get variances 1/(Σ−1)ii, which are too small.
"Entropy of a d-dimensional Gaussian? Why can it be negative?"21log((2πe)ddetΣ).
A density can be larger than 1 when detΣ is small, so −logp can be negative on average.
"What happens to differential entropy if you rescale the data?" It shifts by
log∣detA∣; so units matter. KL and mutual information do not change.
"Derive the KL between two Gaussians." Use E[Z⊤MZ]=tr(MC)+m⊤Mm
for both log-densities (Theorem 5). Know the 1-D formula and the VAE term
21∑j(σj2+μj2−1−logσj2).
"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 q on a correlated posterior gets the conditional variances.
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
Kevin Murphy, Probabilistic Machine Learning: An Introduction,
free PDF: §6.1.6 (differential entropy and the Gaussian), §6.2.3 (KL between two Gaussians) and
§6.2.6 (forward vs reverse KL).
Christopher Bishop, Pattern Recognition and Machine Learning,
free PDF: §1.6 (differential entropy, maximum entropy) and §10.1.2 (Figures 10.2 and 10.3: factorized
approximations and the two KL directions).