Before this lesson:lesson 01 (surprisal and
entropy) and lesson 02 (conditional entropy).
Convex functions from optimization lesson 02;
the expectation of a function of a random variable from
the probability track.
Time: about 60 minutes, plus the notebook.
KL divergence is inside many training objectives. The cross-entropy loss of every classifier and
language model is the entropy of the data plus a KL term (lesson 04).
RLHF (reinforcement learning from human feedback) adds a penalty βKL(πθ∥πref)
so that the tuned language model stays close to the reference model. Knowledge distillation trains a
small student to match a large teacher by minimizing a KL. The VAE loss has a KL term that pulls the
encoder towards the prior (lesson 09). TRPO limits each
policy update to a small KL ball (a trust region). Monitoring systems detect data drift by comparing
the feature distributions of two time windows with KL or a symmetric version of it.
Jensen's inequality is the tool behind the proofs. It shows that KL is never negative, that the
uniform distribution has the largest entropy, and that the ELBO of variational inference is a lower
bound on the log-likelihood.
In this track log is the natural logarithm and gives nats; log2 gives bits, and
1 nat=1/ln2≈1.443 bits. NumPy, SciPy and PyTorch use nats.
A function f is convex if every chord lies on or above its graph. Take two points a and b
and a weight λ∈[0,1]. Let X be a random variable that equals a with probability
λ and b with probability 1−λ. Then
E[X]=λa+(1−λ)b is a point between a and b;
E[f(X)]=λf(a)+(1−λ)f(b) is the height of the chord above that point;
f(E[X]) is the height of the graph above the same point.
The chord is above the graph, so f(E[X])≤E[f(X)]. For two points, this
inequality is exactly the definition of convexity.
Now let X take values x1,…,xn with probabilities p1,…,pn. Put a mass pi on
the graph at the point (xi,f(xi)). The centre of mass of these masses is
(∑ipixi,∑ipif(xi))=(E[X],E[f(X)]). It lies
inside the polygon spanned by the points. For a convex f this polygon lies on or above the graph, so
the centre of mass does too: E[f(X)]≥f(E[X]). This is Jensen's inequality.
Interactive figure: loading…
Drag the blue points along the curve and move the weight sliders. The
yellow dot is the centre of mass (E[X],E[f(X)]); the
small dot on the curve is (E[X],f(E[X])). The aqua segment
is the Jensen gap. For a convex f the yellow dot is always above the curve; switch to logx or
x and it is always below. Put all the weight on one point: the gap closes.
A function is concave if −f is convex: every chord lies on or below the graph. The logarithm
is concave, so
E[logX]≤logE[X](X>0).
Example.X is 1 or 4, each with probability 21. Then E[X]=2.5 and
logE[X]=log2.5=0.916, but E[logX]=21(log1+log4)=log2=0.693.
Take the exponential of both sides: the geometric mean1⋅4=2 is at most the
arithmetic mean2.5. This is the AM–GM inequality, and it is Jensen for log.
Quick check
Apply Jensen's inequality to the convex function f(x)=x2. Which known fact do you get?
Why.
For convex f, Jensen says f(E[X])≤E[f(X)], so (E[X])2≤E[X2]. Move one side over: the variance is never negative. The first option has the inequality the wrong way round. Equality holds only when X is constant, because x2 is strictly convex.
KL divergence: the extra surprise of a wrong model #
Lesson 01 measured the surprisal of an outcome x as −log2p(x) bits. Now the data come
from p, but you predict with a model q. Each
outcome surprises you by −log2q(x).
A fair coin, p=(0.5,0.5), and a model that believes q=(0.8,0.2):
outcome
p(x)
q(x)
surprise under q:−log2q(x)
surprise under p:−log2p(x)
heads
0.5
0.8
0.322 bits
1 bit
tails
0.5
0.2
2.322 bits
1 bit
The coin is fair, so each row happens half of the time.
Your average surprise with the model is 21(0.322+2.322)=1.322 bits. This average is
the cross-entropyH(p,q) (lesson 04 studies it).
The best possible average is the entropy H(p)=1 bit. You reach it only with the right model q=p.
The difference, 1.322−1=0.322 bits, is the Kullback–Leibler (KL) divergenceKL(p∥q): the price of the wrong belief, per coin flip.
Look at the rows separately. On heads, the model is less surprised than the truth would be
(0.322<1). On tails it is more surprised (2.322>1). The losses on tails are larger than the
gains on heads, so the average is positive. This is the content of Gibbs' inequality below.
Interactive figure: loading…
Drag the tops of the bars to change the true distribution p (blue) and
the model q (orange). The lower chart shows each
term p(x)logq(x)p(x) (aqua): some terms are negative, but their
sum is never below 0. Switch the lower chart to the terms of KL(q∥p) and compare the two
totals. Then drag one orange bar to 0 where the blue bar is not 0.
Quick check
For one outcome, p(x)=0.3 and q(x)=0.4. What is the sign of the term p(x)logq(x)p(x)?
Why.
log(0.3/0.4)=log0.75<0, so the term is 0.3log0.75=−0.086 nats. Single terms are negative wherever q(x)>p(x). Only the sum is guaranteed to be non-negative (Gibbs' inequality). The base of the log changes the size of the term, not its sign.
It is strictly convex if the inequality is strict whenever a=b and 0<λ<1. It
is (strictly) concave if −f is (strictly) convex. A twice differentiable f is convex when
f′′(x)≥0 on I, and strictly convex when f′′(x)>0
(optimization lesson 02).
Strictly convex: x2,ex,1/x for x>0,tlogt for t≥0.
Strictly concave: logx and x for x>0.
Convex but not strictly: ∣x∣, and every linear function ax+b (it is also concave).
Theorem 1 (Jensen). Let f be convex on an interval I, and let X take values in I with
E[X] and E[f(X)] finite. Then
f(E[X])≤E[f(X)].
If f is strictly convex, equality holds if and only if X is constant (with probability 1). For a
concave f the inequality is reversed: f(E[X])≥E[f(X)].
Why this is true. A convex function lies above each of its tangent lines. A line is easy to
average: the average of a line is the line at the average. So the average of f is above the
average of the line, which is the value of f at the mean.
Proof.
Let μ=E[X]. If μ is an endpoint of I, say the left one, then X−μ≥0
and E[X−μ]=0. A non-negative variable with mean 0 is 0 with probability 1, so
X=μ and both sides equal f(μ). From now on, μ is an interior point of I.
A convex f has a supporting line at every interior point: a slope c with
f(x)≥f(μ)+c(x−μ) for all x∈I. If f is differentiable, c=f′(μ) and
the line is the tangent line.
Put x=X and take the expectation of both sides. Expectation is linear and keeps
inequalities, so E[f(X)]≥f(μ)+c(E[X]−μ)=f(μ).
Equality case. The difference D=f(X)−f(μ)−c(X−μ) is ≥0. Equality in step 3
means E[D]=0, so D=0 with probability 1: X only takes values where the graph
touches the supporting line.
A strictly convex f touches a line below it at one point only. (If it touched at μ and at
x′=μ, then at the midpoint of μ and x′ the graph would lie strictly below the chord,
which is a piece of the line. That contradicts f≥ line.) So X=μ with probability 1.
For a concave f, apply steps 1–5 to the convex function −f.■
For a convex f that is not strictly convex, equality can hold with a random X: when f is
linear on the values of X. For example f(x)=∣x∣ and X∈{1,3}:∣E[X]∣=2=E[∣X∣].
The Jensen gap for log is logE[X]−E[logX]≥0. Let
μ=E[X] and σ2=Var(X). When X stays close to μ,
logE[X]−E[logX]≈2μ2σ2.
Derivation.
Second-order Taylor expansion of log at μ:logx≈logμ+μx−μ−2μ2(x−μ)2.
Put x=X and take expectations. E[X−μ]=0 and E[(X−μ)2]=σ2, so
E[logX]≈logμ−2μ2σ2.
Subtract from logE[X]=logμ.
For X∈{0.9,1.1} with equal probabilities, the exact gap is 0.00503 and the approximation
gives 0.005. For X∈{1,4} (a large spread) the exact gap is 0.223 and the approximation
gives 0.18: the Taylor expansion is only good for a small spread. The lesson to remember: the
gap grows with the relative spread σ/μ. Lesson 09 uses this to explain why the IWAE
bound, which averages several samples inside the log, is tighter than the ELBO.
Preview: why the ELBO is a lower bound
In a latent-variable model p(x,z), the evidence p(x)=∑zp(x,z) is often too expensive to
compute. Choose any distribution q(z) that is positive wherever p(x,z)>0, and define the weight
w(z)=p(x,z)/q(z). Then p(x)=∑zq(z)w(z)=Ez∼q[w(z)]. Jensen for the
concave log gives
logp(x)=logEq[w]≥Eq[logw]=Eq[logq(z)p(x,z)].
The right side is the evidence lower bound (ELBO). Lesson 09
shows that the gap is exactly a KL divergence, KL(q(z)∥p(z∣x)).
Read it as: the average, under the truth p, of the extra surprise −logq(x)−(−logp(x)).
The first argument is the distribution we average under. In machine learning it is usually the data
distribution, and the second argument is the model.
Conventions for zeros (they are the limits of tlogt and tlog(t/s)):
0logq0=0 for every q≥0: outcomes that never happen cost nothing.
plog0p=+∞ for p>0: an outcome that happens but has model probability 0
makes the KL infinite.
So KL(p∥q)<∞ exactly when q(x)>0 for every x with p(x)>0 (the
support of p lies inside the support of q). For densities, replace the sum by an integral; the
results below stay the same (lesson 06).
Theorem 2 (Gibbs' inequality).KL(p∥q)≥0, with equality if and only if p=q.
Proof.
Let S={x:p(x)>0} be the support of p. If q(x)=0 for some x∈S, the KL is
+∞ and there is nothing to prove. Otherwise, the terms outside S are 0, and
−KL(p∥q)=∑x∈Sp(x)logp(x)q(x).
This is E[logp(X)q(X)] with X∼p. Jensen for the concave log
moves the log outside: −KL(p∥q)≤log∑x∈Sp(x)p(x)q(x),
and the right side simplifies to log∑x∈Sq(x).
The probabilities q(x) over the part S add up to at most 1, so the right side is
≤log1=0. Hence KL(p∥q)≥0.
Equality needs both steps to be tight. Step 2 is tight only if q(x)/p(x)=c is the same
number for all x∈S(log is strictly concave). Step 3 is tight only if
∑x∈Sq(x)=1. Then 1=∑Sq=c∑Sp=c, so q=p on S, and q=0
outside S. That is, q=p.■
Second proof: the log-sum inequality (and the convexity of KL)
Theorem 3 (log-sum inequality). For ai≥0 and bi>0, with A=∑iai and
B=∑ibi,
i∑ailogbiai≥AlogBA,
with equality if and only if ai/bi is the same for all i.
Proof.
Let g(t)=tlogt for t≥0. Then g′′(t)=1/t>0, so g is strictly convex.
Define weights wi=bi/B (positive, sum 1) and ratios ti=ai/bi.
Rewrite the left side: ∑iailogbiai=∑ibitilogti=B∑iwig(ti).
Jensen with the weights w:∑iwig(ti)≥g(∑iwiti)=g(A/B), because
∑iwiti=∑iai/B=A/B.
Multiply by B: the left side is ≥B⋅BAlogBA=AlogBA.
Equality holds when Jensen is tight for the strictly convex g: all ti are equal. ■
Gibbs from log-sum. Put a=p and b=q (restrict to the x with q(x)>0). Then
A=B=1 and the right side is 1⋅log1=0.
KL is jointly convex. For two pairs (p1,q1),(p2,q2) and λ∈[0,1],
Proof: fix one outcome x and apply the log-sum inequality to the two terms
a1=λp1(x),a2=(1−λ)p2(x),b1=λq1(x),b2=(1−λ)q2(x).
The λ inside the logs cancels. Then add over x. Convexity is why minimizing a KL over a
convex set of distributions has no bad local minima.
Quick check
The true distribution is p=(0.99,0.01). A model predicts q=(1,0). What is KL(p∥q)?
Why.
The term for the rare outcome is 0.01log00.01=+∞. One outcome that happens but has model probability 0 makes the whole KL infinite, however rare it is. The other direction is finite: KL(q∥p)=1⋅log0.991+0=0.010 nats, because outcomes with q(x)=0 cost nothing when we average under q.
Gibbs gives logK−H(p)≥0, with equality only if p=u.■
So the entropy gap to the maximum is a KL divergence to the uniform distribution. For
p=(21,41,81,81):H(p)=1.75 bits, log24=2 bits, and
KL(p∥u)=0.25 bits.
Corollary 2 (conditioning reduces entropy on average).H(Y∣X)≤H(Y), with equality if
and only if X and Y are independent.
Proof.
Write both entropies as averages over the joint distribution p(x,y):H(Y)=∑x,yp(x,y)logp(y)1 and H(Y∣X)=∑x,yp(x,y)logp(y∣x)1.
Subtract: H(Y)−H(Y∣X)=∑x,yp(x,y)logp(y)p(y∣x).
Multiply the top and bottom of the fraction by p(x):p(y)p(y∣x)=p(x)p(y)p(x,y).
So H(Y)−H(Y∣X)=KL(p(x,y)∥p(x)p(y))≥0 by Gibbs. Equality holds only
if p(x,y)=p(x)p(y) for all x,y: independence. ■
The difference H(Y)−H(Y∣X) is the mutual informationI(X;Y)
(lesson 07). Step 4 shows that it is the
KL divergence from the joint distribution to the product of the marginals.
Quick check
A distribution on 8 values has entropy H(p)=2.2 bits. What is KL(p∥u) for the uniform u on the 8 values?
Why.
KL(p∥u)=log28−H(p)=3−2.2=0.8 bits. Only the entropy is needed, because logu(x)1=logK is the same for every outcome.
A metric (distance) d must be symmetric, d(p,q)=d(q,p), and must satisfy the triangle
inequality, d(p,r)≤d(p,q)+d(q,r). KL fails both.
Not symmetric. For the coin, KL(p∥q)=0.223 nats (0.322 bits) but
KL(q∥p)=0.8log1.6+0.2log0.4=0.376−0.183=0.193 nats (0.278 bits). The
two arguments play different roles: the first one decides where we average.
No triangle inequality. Write Ber(a) for the coin with P(heads)=a. Then
KL(Ber(0.9)∥Ber(0.1))=1.758 nats, but the two steps through the fair coin
give KL(Ber(0.9)∥Ber(0.5))+KL(Ber(0.5)∥Ber(0.1))=0.368+0.511=0.879 nats.
The direct route is twice as long as the detour.
This is why the name is "divergence", not "distance". For two close distributions, KL behaves like
half a squared distance (see the folded block below), and squared distances also break the
triangle inequality: 22>12+12.
Bernoulli KL. For two coins, KL(Ber(a)∥Ber(b)) has two terms, one for heads and one for tails:
alogba+(1−a)log1−b1−a.
Interactive figure: loading…
Move a (the true coin) and b (the model coin). The aqua curve is
KL(Ber(a)∥Ber(b)) as a function of b; the grey dashed curve is the reverse,
KL(Ber(b)∥Ber(a)). Both touch 0 only at b=a. Near b=0 or b=1 the
aqua curve shoots up to infinity, but the dashed one stays finite. Try the preset a=0.
Near p, KL is half a squared distance
Let q=p+δ with a small change δ(∑xδ(x)=0, and p(x)>0). A
second-order Taylor expansion of log(1+t)≈t−t2/2 gives
This is half a weighted squared distance (the weights 1/p(x) are the Fisher information of the
categorical distribution). The reverse KL has the same second-order term, so for close distributions
the asymmetry disappears; it shows up only at third order. For p=(0.5,0.5) and
q=(0.52,0.48): both KLs are 0.000800 nats, and the formula gives 21(0.0008+0.0008)=0.0008.
Natural-gradient methods and TRPO use this local metric.
Answers to section 1. (1) No. KL(p∥q)=0.322 bits for the fair coin modelled as
(0.8,0.2), but KL(q∥p)=0.278 bits for the reverse situation. (2) Infinite: the term
0.01log00.01 is +∞. (3) Yes. A term is negative wherever q(x)>p(x); only the
total is ≥0.
Quick check
What is KL(Ber(0.5)∥Ber(0.25)) in bits?
Why.
0.5log20.250.5+0.5log20.750.5=0.5⋅1+0.5⋅(−0.585)=0.208 bits. The value 0.189 is the reverse, KL(Ber(0.25)∥Ber(0.5))=0.25log20.5+0.75log21.5: the arguments in the wrong order. 0.5 is the first term alone; the negative second term also counts.
(a) Jensen for the log.X is 1 or 4 with probability 21 each.
E[X]=21⋅1+21⋅4=2.5, so logE[X]=log2.5=0.916.
E[logX]=21log1+21log4=0+log2=0.693.
Gap: 0.916−0.693=0.223=log22.5=log1.25. It is positive, as Jensen says.
Variance: E[X2]−2.52=21(1+16)−6.25=2.25. The Taylor estimate
σ2/(2μ2)=2.25/12.5=0.18 is in the right range, but not exact, because the spread is large.
(b) KL on three outcomes, term by term.p=(0.6,0.3,0.1) and q=(0.3,0.4,0.3), in bits.
x
p(x)
q(x)
p(x)/q(x)
p(x)log2q(x)p(x)
1
0.6
0.3
2
0.6⋅1=0.600
2
0.3
0.4
0.75
0.3⋅(−0.415)=−0.125
3
0.1
0.3
0.333
0.1⋅(−1.585)=−0.158
KL(p∥q)=0.600−0.125−0.158=0.317 bits. Two of the three terms are negative.
The reverse direction averages under q:KL(q∥p)=0.3log20.60.3+0.4log20.30.4+0.3log20.10.3=−0.300+0.166+0.475=0.342 bits.
The largest term now comes from outcome 3, where q puts three times the mass of p.
In nats, multiply by ln2:0.220 and 0.237 nats.
(c) Distance to the uniform distribution.p=(21,41,81,81) on K=4
values. Surprisals: 1, 2, 3, 3 bits, so
H(p)=21⋅1+41⋅2+81⋅3+81⋅3=1.75 bits. Then
KL(p∥u)=log24−1.75=0.25 bits. Direct check:
21log21/41/2+41log21+2⋅81log21/41/8=0.5+0−0.25=0.25 bits.
SciPy has the KL divergence built in: scipy.stats.entropy(p, q) is KL(p∥q), and
scipy.special.rel_entr(p, q) returns the single terms plog(p/q) with the zero conventions.
importnumpyasnpfromscipy.statsimportentropyfromscipy.specialimportrel_entr# (a) Jensen for log: E[log X] <= log E[X]x,w=np.array([1.0,4.0]),np.array([0.5,0.5])print(np.log(w@x),w@np.log(x))# 0.9163 0.6931# (b) KL term by term, in bits, and the reversep,q=np.array([0.6,0.3,0.1]),np.array([0.3,0.4,0.3])print(rel_entr(p,q)/np.log(2))# [ 0.6 -0.1245 -0.1585]print(entropy(p,q,base=2),entropy(q,p,base=2))# 0.3170 0.3415# The coin: not symmetricprint(entropy([0.5,0.5],[0.8,0.2]),entropy([0.8,0.2],[0.5,0.5]))# 0.2231 0.1927 nats# (c) KL to the uniform distribution = log K - H(p)p4=np.array([1/2,1/4,1/8,1/8])print(entropy(p4,np.full(4,1/4),base=2),2-entropy(p4,base=2))# 0.25 0.25# Zeros: q = 0 where p > 0 gives inf; p = 0 terms give 0print(entropy([0.99,0.01],[1.0,0.0]),entropy([1.0,0.0],[0.99,0.01]))# inf 0.01005
entropy(p, q) normalizes both inputs so that they sum to 1. Pass probabilities, not counts with
different totals, if you want to see a mistake instead of a silent fix.
RLHF and fine-tuning. PPO-based RLHF maximizes reward minus βKL(πθ∥πref),
estimated on samples from the tuned policy. Without this term the policy drifts into text that
fools the reward model. DPO is derived from the same KL-regularized objective.
Knowledge distillation. A student q is trained on KL(pteacher∥q), the KL
from the teacher's softened output distribution (lesson 04).
VAEs and variational inference. The VAE loss contains KL(qϕ(z∣x)∥p(z)), and the
gap of the ELBO is a KL (lesson 09). Which direction of KL you
minimize changes the fit (lesson 06).
Trust regions. TRPO constrains Es[KL(πold(⋅∣s)∥πθ(⋅∣s))]≤δ.
Near the old policy, KL is half a squared distance with the Fisher information as the metric.
Data drift and monitoring. The population stability index (PSI) used in credit scoring and
model monitoring is ∑x(p(x)−q(x))logq(x)p(x)=KL(p∥q)+KL(q∥p),
a symmetric version of KL between the binned feature distributions of two time windows.
ML for science. Model selection with AIC estimates the expected KL from the true data
distribution to a fitted model. In climate and weather work, KL compares a forecast distribution
with an observed or reference one; it needs the support condition, so forecasts must never give
probability 0 to an event that can occur.
Wrong direction of Jensen for the log.E[logX]≤logE[X], because log is
concave. If unsure, draw the chord, or check with X∈{1,4}.
"Every term of KL is non-negative." Single terms p(x)logq(x)p(x) are negative
wherever q(x)>p(x). Only the sum is ≥0.
Swapping the arguments.KL(p∥q) averages under p. In general
KL(p∥q)=KL(q∥p), so always say which one you mean.
Calling KL a distance. It is not symmetric and it breaks the triangle inequality. If you need a
true metric, use the total variation distance, the Hellinger distance or the square root of the
Jensen–Shannon divergence (lesson 08).
Forgetting the zeros. A model probability of exactly 0 for a possible outcome gives an
infinite KL (and an infinite loss). In code, p * np.log(p / q) gives nan for p=0; use
scipy.special.rel_entr, which applies 0logq0=0.
Wrong equality condition in Jensen. For a strictly convex f, equality holds only if X is
constant. For a convex f that is linear on the range of X (such as ∣x∣ on x>0), equality
can hold with a random X.
Use Jensen to show E[1/X]≥1/E[X] for a positive random variable X. Check it
for X uniform on {1,3}.Answerf(x)=1/x has f′′(x)=2/x3>0 on x>0, so it is strictly convex and Jensen gives 1/E[X]≤E[1/X], with equality only for a constant X. Example: E[1/X]=21(1+31)=32 and 1/E[X]=21; indeed 32≥21.
Compute KL(Ber(0.5)∥Ber(0.9)) and KL(Ber(0.9)∥Ber(0.5)) in nats.Answer0.5log0.90.5+0.5log0.10.5=21log925=log35=0.511 nats. The other way: 0.9log1.8+0.1log0.2=0.529−0.161=0.368 nats. Not equal.
In the proof of Gibbs' inequality, why do we sum q(x) only over the support S of p, and why
is that sum at most 1?AnswerTerms with p(x)=0 contribute 0 by the convention 0logq0=0, so the KL is a sum over S only, and Jensen is applied to X∼p, which lives on S.q may put some mass outside S, so ∑x∈Sq(x)≤∑xq(x)=1.
A model predicts q=(0.5,0.5,0) for data with p=(0.5,0.25,0.25). What is
KL(p∥q)? What is KL(q∥p) in bits?AnswerKL(p∥q)=+∞, because outcome 3 has p=0.25>0 and q=0. The reverse is finite: 0.5log20.50.5+0.5log20.250.5+0=0.5 bits.
Show that H(X,Y)≤H(X)+H(Y), using a result of this lesson.AnswerBy the chain rule of lesson 02, H(X,Y)=H(X)+H(Y∣X). Corollary 2 gives H(Y∣X)≤H(Y). So H(X,Y)≤H(X)+H(Y), with equality only for independent X and Y. Equivalently, H(X)+H(Y)−H(X,Y)=KL(p(x,y)∥p(x)p(y))≥0.
Two distributions are very close: p=(0.5,0.5) and q=(0.52,0.48). Estimate
KL(p∥q) without a calculator.AnswerUse KL≈21∑xδ(x)2/p(x) with δ=(0.02,−0.02):21(0.0004/0.5+0.0004/0.5)=0.0008 nats. The exact value is 0.000800 nats.
Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
State Jensen's inequality for a convex function f, with the equality condition.
f(E[X])≤E[f(X)]. If f is strictly convex, equality holds only when X is constant (with probability 1).
Which way does Jensen's inequality go for log, and why?
E[logX]≤logE[X], because log is concave: its chords lie below the graph.
About how large is the Jensen gap logE[X]−E[logX] when X has mean μ and small variance σ2?
About σ2/(2μ2), from a second-order Taylor expansion of log at μ.
Define the KL divergence KL(p∥q) of two discrete distributions.
∑xp(x)logq(x)p(x)=Ex∼p[logp(x)−logq(x)]: the average extra surprise under p of using q.
State Gibbs' inequality.
KL(p∥q)≥0, with equality if and only if p=q.
When is KL(p∥q) infinite?
When q(x)=0 for some outcome x with p(x)>0.
What is KL(p∥u) for the uniform distribution u on K values?
logK−H(p). Since it is ≥0, it proves H(p)≤logK.
Write the KL divergence between two coins, KL(Ber(a)∥Ber(b)).
alogba+(1−a)log1−b1−a.
Compute KL(p∥q) in bits for a fair coin p and the model q=(0.8,0.2).
0.5log20.80.5+0.5log20.20.5=0.322 bits (cross-entropy 1.322 minus entropy 1).
Why is the KL divergence not a metric?
It is not symmetric, and it breaks the triangle inequality: KL(Ber(0.9)∥Ber(0.1))=1.758>0.368+0.511 nats via Ber(0.5).
"Prove that the KL divergence is non-negative." Write −KL(p∥q)=Ep[log(q/p)],
apply Jensen for the concave log: ≤logEp[q/p]=log∑x:p(x)>0q(x)≤0.
Equality only for p=q.
"Is KL a distance?" No: not symmetric, no triangle inequality. Give the coin numbers. Near p
it behaves like half a squared distance with the Fisher metric.
"What happens if the model assigns probability 0 to a real outcome?" The KL (and the
cross-entropy loss) is infinite. This is why models use a softmax, which is never exactly 0, and why
probabilities are clipped or smoothed.
"Why is the ELBO a lower bound?" Jensen for the concave log:
logEq[p(x,z)/q(z)]≥Eq[log(p(x,z)/q(z))].
"Which distribution on K outcomes has the largest entropy?" The uniform one, because
logK−H(p)=KL(p∥u)≥0.
Yury Polyanskiy and Yihong Wu, Information Theory: From Coding to Learning,
free draft: chapter 2 (divergence, its convexity and the log-sum inequality), for a rigorous treatment.
Code along in Colab
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.