Information Theory, Entropy & Divergence Measures
Shannon entropy, cross-entropy, KL-divergence, Gibbs' inequality, and mutual information.
Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.
1. The idea
Information theory formalizes uncertainty, surprise, and distance between probability distributions. It provides the foundation for decision tree splitting (Information Gain), categorical cross-entropy loss in neural networks, and modern alignment objectives like DPO and RLHF.
2. The math
• Recall Jensen's inequality: For a strictly concave function phi(t), E[phi(t)] <= phi(E[t]). The logarithm ln(t) is strictly concave.
• Express -D_KL(P || Q) as an expectation under P: -D_KL(P || Q) = sum_x P(x) ln(Q(x)/P(x)) = E_{x ~ P}[ln(Q(x)/P(x))].
• Apply Jensen's inequality: E_{x ~ P}[ln(Q(x)/P(x))] <= ln(E_{x ~ P}[Q(x)/P(x)]) = ln(sum_x P(x) (Q(x)/P(x))).
• Simplify the summation: sum_x Q(x) = 1. Thus ln(1) = 0.
• Therefore, -D_KL(P || Q) <= 0 => D_KL(P || Q) >= 0, with equality if and only if P(x) = Q(x) for all x. Q.E.D.
3. How it works
4. The code (python)
import numpy as np
# Numerical computation of Entropy, Cross-Entropy, and KL-Divergence
def compute_divergences(p, q, eps=1e-12):
p = np.clip(p, eps, 1.0); p /= np.sum(p)
q = np.clip(q, eps, 1.0); q /= np.sum(q)
# Shannon Entropy H(P)
H_p = -np.sum(p * np.log2(p))
# Cross-Entropy H(P, Q)
H_pq = -np.sum(p * np.log2(q))
# KL Divergence D_KL(P || Q)
D_kl = np.sum(p * np.log2(p / q))
# Jensen-Shannon Divergence
m = 0.5 * (p + q)
D_js = 0.5 * np.sum(p * np.log2(p / m)) + 0.5 * np.sum(q * np.log2(q / m))
return {"H(P)": H_p, "H(P,Q)": H_pq, "D_KL(P||Q)": D_kl, "D_JS": D_js}
if __name__ == "__main__":
P = np.array([0.7, 0.2, 0.1]) # True distribution
Q = np.array([0.5, 0.3, 0.2]) # Model prediction
res = compute_divergences(P, Q)
for k, v in res.items():
print(f"{k:12s}: {v:.4f} bits")
assert abs(res["H(P,Q)"] - (res["H(P)"] + res["D_KL(P||Q)"])) < 1e-6
print("✓ Cross-Entropy Identity H(P, Q) = H(P) + D_KL(P || Q) Verified.")5. Check yourself
In the catalog
Finished this chapter?
The Epoch Zero newsletter
What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.