The Kullback-Leibler (KL) divergence, also known as relative entropy, is a measure that quantifies how one probability distribution differs from a second, reference probability distribution. It's widely used in machine learning, statistics, and information theory.
Basic Formulas
Discrete Probability Distributions
For discrete probability distributions P and Q, the KL divergence is defined as:
DKL(P∥Q)=∑x∈XP(x)log(Q(x)P(x))
This can also be written as:
DKL(P∥Q)=
Which is the difference between the cross-entropy and the entropy[1].
Continuous Probability Distributions
For continuous distributions with probability density functions p(x) and q(x), the formula becomes:
DKL(P∥Q)=∫
Interpretation and Properties
-
Non-negativity: KL divergence is always greater than or equal to zero, with equality if and only if P and Q are identical[3].
-
Asymmetry: KL divergence is not symmetric, meaning:
DKL(P∥Q)=
This is why it's called a divergence rather than a distance[1][3].
Special Cases
Multivariate Normal Distributions
For multivariate normal distributions with means μ₀, μ₁ and covariance matrices Σ₀, Σ₁ of dimension k:
DK
Where tr is the trace operator[3].
Univariate Normal Distributions
For univariate normal distributions:
DKL(p∥q)=log
Where μ₀, σ₀ and μ₁, σ₁ are the means and standard deviations[3].
Exponential Family Distributions
For the exponential family, with natural parameters θ₁ and θ₂:
DKL(θ1∥
Where μ₁ is the mean parameter and A is the log-partition function[3].
Related Concept: Jensen-Shannon Divergence
The Jensen-Shannon divergence (JS) provides a symmetrized and smoothed version of KL divergence:
JS(P∥Q)=21
Where M = ½(P + Q)[1].
Implementation in Code
In Python, you can calculate KL divergence using the formula directly:
from math import log2
def kl_divergence(p, q):
return sum(p[i] * log2(p[i]/q[i]) for i in range(len(p)))
Or using SciPy's rel_entr function:
from scipy.special import rel_entr
import numpy as np
def kl_divergence(p, q):
return np.sum(rel_entr(p, q))
The choice of logarithm base determines the units of the result: base-2 gives "bits" while the natural logarithm (base-e) gives "nats"[1].