Equations · Kullback and Leibler (1951)

The KL divergence formula, explained

How much one probability distribution differs from another: the expected extra log-loss from using QQ when the data really follow PP.

DKL(P ∥ Q)=∑xP(x)log⁡P(x)Q(x)D_{\mathrm{KL}}(P \,\|\, Q) = \sum_{x} P(x) \log \frac{P(x)}{Q(x)}

Open in the decoder →

Term by term

  1. DKL(P ∥ Q)D_{\mathrm{KL}}(P \,\|\, Q)

    The divergence of QQ from PP. The ∥\| separates the arguments; the order matters.

  2. ∑xP(x)\sum_{x} P(x)

    An average over outcomes xx, weighted by PP: an expectation under PP. For continuous variables, an integral.

  3. log⁡P(x)Q(x)\log \frac{P(x)}{Q(x)}

    The log-ratio of the two probabilities. Zero where they agree; large where QQ gives little probability to something PP thinks likely.

A small worked example

P=(0.5,0.5)P = (0.5, 0.5), Q=(0.9,0.1)Q = (0.9, 0.1): 0.5ln⁡0.50.9+0.5ln⁡0.50.1≈−0.294+0.805=0.5110.5 \ln\frac{0.5}{0.9} + 0.5 \ln\frac{0.5}{0.1} \approx -0.294 + 0.805 = 0.511 nats. Reversed, DKL(Q ∥ P)≈0.368D_{\mathrm{KL}}(Q \,\|\, P) \approx 0.368.

In code

import numpy as np

def kl(p, q):
    return np.sum(p * np.log(p / q))

Every symbol in it

DKL(q ∥ p)D_{\mathrm{KL}}(q \,\|\, p)KL divergence∑i=1Nxi\sum_{i=1}^{N} x_iSummationp(x),  q(z)p(\mathbf{x}), \; q(\mathbf{z})Probability p(x)log⁡pθ(x)\log p_\theta(x)Logarithmab\frac{a}{b}Fraction

Other equations