2/13
Part 1 of 7 · KL divergenceLearn and do
KL divergence is the extra cost of the wrong model
The OpenAI question is about continuous distributions, but start with the discrete version: the continuous one is the same idea with an integral.
The likelihood lesson split cross entropy into the entropy plus a gap. That gap is the KL divergence:
The Deep Learning book reads it as the extra information needed to send messages drawn from P with a code designed for Q. Here p is how often each of the shop's four sizes sells, and q is a model that gives every size the same chance.
import numpy as np
# how often each of 4 sizes sells
p = np.array([0.50, 0.30, 0.15, 0.05])
# a model that knows nothing
q = np.array([0.25, 0.25, 0.25, 0.25])
def kl(p, q):
"""D(p || q) in nats."""
keep = p > 0
return np.sum(p[keep] * np.log(p[keep] / q[keep]))
cross = -np.sum(p * np.log(q))
entropy = -np.sum(p * np.log(p))
print(f"KL(p || q) {kl(p, q):.4f} = cross entropy {cross:.4f} - entropy {entropy:.4f}")
print(f"KL(q || p) {kl(q, p):.4f}")
KL(p ‖ q) comes out at 0.244 nats. What does that say about the uniform model?
Pick one to see what it prints.
Pick an answer above to see the rest
A new model gives XL a 0% chance, but 5% of sales are XL. What's KL(p ‖ q)?
Pick an answer above to see the rest