Lensa ML
Lensa ML

How KL Divergence Works

Step 1 of 6

Two Distributions

Compare P and Q visually

A40%25%B30%25%C20%25%D10%25%P (true)Q (approx)
P distribution
A40%
B30%
C20%
D10%
Q distribution
A25%
B25%
C25%
D25%
ENTROPY OF P
H(P) = 1.846 bits
ENTROPY OF Q
H(Q) = 2.000 bits

Both P and Q are nearly uniform — high entropy means maximum uncertainty in both.

Step 1 of 6: Two Distributions

Compare P and Q visually

A40%25%B30%25%C20%25%D10%25%P (true)Q (approx)
P distribution
A40%
B30%
C20%
D10%
Q distribution
A25%
B25%
C25%
D25%
ENTROPY OF P
H(P) = 1.846 bits
ENTROPY OF Q
H(Q) = 2.000 bits

Both P and Q are nearly uniform — high entropy means maximum uncertainty in both.

Step 2 of 6: The KL Formula

Information gap, term by term

KL(P‖Q) = Σ P(x) · ln( P(x)/Q(x) )
0.347A0.000B-0.077C-0.092DPer-class KL contribution: P(x)·ln(P(x)/Q(x))
P distribution
A50%
B25%
C15%
D10%
Q distribution
A25%
B25%
C25%
D25%
KL(P‖Q)
0.1783 nats
=
Term A
0.347
+
Term B
0.000
+
Term C
-0.077
+
Term D
-0.092

There is a moderate information gap between P and Q.

Step 3 of 6: Asymmetry

KL(P‖Q) ≠ KL(Q‖P)

ABCDP (reference)Q (approx)
P distribution (reference)
A60%
B20%
C15%
D5%
Q distribution (approx)
A20%
B30%
C30%
D20%
KL(P‖Q)
0.4048
KL(Q‖P)
0.3871
|Diff|
0.0177

The two directions are nearly equal here — but that's a special case, not the norm!

Step 4 of 6: KL = Cross-Entropy − Entropy

Breaking down the divergence

H(P,Q) = H(P) + KL(P‖Q)
cross-entropy = entropy + divergence
H(P)1.235H(P)+KLKL=0.151H(P,Q)1.386
P distribution
A45%
B30%
C15%
D10%
Q distribution
A25%
B25%
C25%
D25%
H(P)
1.235 nats
KL(P‖Q)
0.151 nats
H(P,Q)
1.386 nats

Cross-entropy is always ≥ entropy. The extra cost is exactly the KL divergence — the price of using Q instead of P.

Step 5 of 6: Mode-Seeking vs Mode-Covering

How the direction changes fitting behavior

Mode 1Mode 2MISSEDMISSEDP (bimodal)Q (fitted)
Q center
Q spread
KL(P‖Q)
1.836 nats
Modes hit
0/2

Mode-covering: KL(P‖Q) penalizes Q for missing anywhere P has mass. Q must spread to cover both peaks — try increasing spread!

Step 6 of 6: Cross-Entropy Loss

How classifiers learn from KL

Loss = −log(P(true class)) = −log(0.188) = 1.669
cross-entropy loss = how surprised the model is by the correct answer
118.8%Cat ✓071.5%Dog09.7%BirdTrue labelModel prediction
True class
Model confidence (logits)
Cat18.8%
Dog71.5%
Bird9.7%
CROSS-ENTROPY LOSS
1.669
P(Cat)
18.8%

The model is unsure — Cat isn't even the top prediction. High cross-entropy loss means the model would receive a strong gradient update.