Information theory
Kullback-Leibler divergence
info.kl-divergenceAlso called kl divergence, kl, kld, relative entropy
Relative entropy of p with respect to q, in nats. Non-negative, zero only when p = q, and not symmetric.
Notation
probability vector
p ∈ Δn: pi > 0, ∑pi = 1
second probability vector
q ∈ Δn: qi > 0, ∑qi = 1
number of outcomes
Size, at least 2
Result: the divergence, in nats
scalar
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
≈ 0.143841036226
Given
Result
Given
Result
≈ 0.231049060187
Common mistakes
Computes DKL(q ‖ p)
The arguments are reversed. PyTorch's kl_div(input, target) expects log q as input and p as target.
Fix: Weight by p: Σ pi ln(pi/qi).
Uses log base 2
The result is in bits.
Fix: Use the natural logarithm, or multiply by ln 2.
Sources
Kullback and Leibler 1951
Kullback, Solomon; Leibler, Richard A. On Information and Sufficiency. The Annals of Mathematical Statistics 22(1): 79-86, 1951. doi:10.1214/aoms/1177729694
Goodfellow et al. 2016, §3.13, eq. 3.50
Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.
Cover and Thomas 2006
Cover, Thomas M.; Thomas, Joy A. Elements of Information Theory. 2nd ed. Wiley-Interscience, 2006. doi:10.1002/047174882X