Information Theory, Entropy & Divergence Measures
Shannon entropy, cross-entropy, KL-divergence, Gibbs' inequality, and mutual information.
π‘ 1. Core Intuition & Concepts
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. Mathematical Formulations & Derivations
β’ 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. Step-by-Step Computational Mechanism
π» 4. Code from Scratch (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. Comprehension Checkpoint
In the catalog
Finished this chapter?