All formulas

Information theory

Kullback-Leibler divergence

info.kl-divergenceAlso called kl divergence, kl, kld, relative entropy

DKL(p∥q)=∑i=1npiln⁡piqiD_{\mathrm{KL}}(p \parallel q) = \sum_{i=1}^{n} p_i \ln\frac{p_i}{q_i}

Relative entropy of p with respect to q, in nats. Non-negative, zero only when p = q, and not symmetric.

Notation

pp

probability vector

p ∈ Δn: pi > 0, ∑pi = 1

qq

second probability vector

q ∈ Δn: qi > 0, ∑qi = 1

nn

number of outcomes

Size, at least 2

DKLD_{\mathrm{KL}}

Result: the divergence, in nats

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    p=[0.5,0.5],q=[0.25,0.75]p = [0.5, 0.5], q = [0.25, 0.75]

    Result

    DKL=log⁡(43)2\displaystyle D_{\mathrm{KL}} = \frac{\log{\left(\frac{4}{3} \right)}}{2}

    ≈ 0.143841036226

  2. Given

    p=[0.25,0.75],q=[0.25,0.75]p = [0.25, 0.75], q = [0.25, 0.75]

    Result

    DKL=0\displaystyle D_{\mathrm{KL}} = 0
  3. Given

    p=[1/3,2/3],q=[2/3,1/3]p = [1/3, 2/3], q = [2/3, 1/3]

    Result

    DKL=log⁡(2)3\displaystyle D_{\mathrm{KL}} = \frac{\log{\left(2 \right)}}{3}

    ≈ 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

    doi.org
  • Goodfellow et al. 2016, §3.13, eq. 3.50

    Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.

    deeplearningbook.org
  • Cover and Thomas 2006

    Cover, Thomas M.; Thomas, Joy A. Elements of Information Theory. 2nd ed. Wiley-Interscience, 2006. doi:10.1002/047174882X

    doi.org