Sign in

Information theory

Measures of uncertainty and of the difference between discrete distributions: entropy, cross-entropy, KL divergence and mutual information.

Overview

Entropy measures how surprised you are on average by a draw from a distribution. A fair coin is as uncertain as two outcomes can be and has an entropy of one bit, while a coin that always lands heads has zero. Cross-entropy is the average surprise when the world follows pp but you expected qq, and it is never smaller than the entropy of pp. The gap between the two is the KL divergence, the price of believing the wrong distribution. Mutual information applies the same idea to two variables: it measures how far their joint behaviour is from independence, which is how much knowing one tells you about the other.

A short history

Claude Shannon founded the field in 1948 with "A Mathematical Theory of Communication", written at Bell Labs. He defined entropy as the average number of bits needed to encode a source and proved limits on compression and on reliable transmission over a noisy channel. Solomon Kullback and Richard Leibler added the divergence that bears their names in 1951. Cross-entropy later became the standard training loss for classifiers.

How it works

  1. Write the distribution as an array of probabilities that sums to 1. A joint distribution of two variables is a two-dimensional table.
  2. Pick the logarithm base. Base 2 gives bits, base ee gives nats.
  3. For entropy, multiply each probability by the log of itself, add up and change the sign. A term with probability zero counts as zero.
  4. For cross-entropy, use log⁡q\log q in place of log⁡p\log p while still weighting by pp.
  5. Subtract the entropy from the cross-entropy to get the KL divergence from qq to pp.
  6. For mutual information, compare each cell of the joint table with the product of its row and column totals, and take the weighted average of the log ratio.

Watch out for

  • KL divergence is not symmetric. D(p ∥ q)D(p \,\|\, q) and D(q ∥ p)D(q \,\|\, p) answer different questions and usually differ, so it is not a distance.
  • If qq is zero where pp is not, cross-entropy and KL are infinite. The eps setting avoids this by adding a small value to qq, at the price of a slightly biased result.
  • Entropy estimated from a small sample is too low on average, because rare values are missing from the counts. Mutual information estimated the same way is too high.
  • Numbers in bits and in nats differ by a factor of ln⁡2≈0.693\ln 2 \approx 0.693. Mixing bases when comparing results is a common error.
  • These functions are for discrete distributions. Binning a continuous variable first makes the answer depend on the bins.

Use cases

When to use it

Choosing and understanding loss functions (cross-entropy is the standard classification loss), comparing a model's distribution with the data, and scoring how informative a feature is about a label.

In industry

Data compression
Formats such as ZIP and JPEG use Huffman or arithmetic coding, which give short codes to frequent symbols and approach the entropy limit.
Machine learning
Neural classifiers and language models are trained by minimising cross-entropy between the predicted distribution and the true labels.
Telecommunications
Engineers compare a link's data rate with its Shannon capacity to choose modulation and error-correcting codes.
Decision tree learning
Tree learners such as ID3 and C4.5 choose each split by information gain, the drop in label entropy after the split.

Choosing it: what must hold

  • Discrete distributions, or continuous data that has been binned, with probabilities that sum to 1.
  • Enough samples per category. Entropy and mutual information estimated from small counts are biased.
  • For KL divergence, the second distribution must give nonzero probability wherever the first does.

When to choose something else

IfUse instead
You need a symmetric, bounded difference between two distributionsJensen-Shannon divergence
You only need the strength of a straight-line relation between two numeric columnsCorrelation
Variables are continuous and binning would lose too muchA nearest-neighbour mutual information estimator, or a rank correlation

Math foundations

  1. Entropy

    H(p)=−∑xp(x)log⁡p(x)H(p) = -\sum_{x} p(x) \log p(x)

    The average surprise of a draw from pp, where the surprise of an outcome is −log⁡p(x)-\log p(x). It is zero for a certain outcome and largest, log⁡K\log K, for KK equally likely outcomes.

  2. Cross-entropy

    H(p,q)=−∑xp(x)log⁡q(x)H(p, q) = -\sum_{x} p(x) \log q(x)

    The average surprise when outcomes follow pp but surprise is measured with qq. With pp the true labels and qq the model's predictions, this is the classification loss.

  3. KL divergence

    DKL(p ∥ q)=∑xp(x)log⁡p(x)q(x)=H(p,q)−H(p) ≥ 0D_{\mathrm{KL}}(p \,\|\, q) = \sum_{x} p(x) \log \frac{p(x)}{q(x)} = H(p, q) - H(p) \ \ge\ 0

    The extra surprise caused by using qq in place of pp. It is zero only when the two distributions are equal. Since H(p)H(p) is fixed by the data, minimizing cross-entropy and minimizing KL are the same task.

  4. Conditional entropy

    H(Y∣X)=H(X,Y)−H(X)H(Y \mid X) = H(X, Y) - H(X)

    The uncertainty left in YY once XX is known. The joint entropy H(X,Y)H(X, Y) is the entropy formula applied to every cell of the joint table.

  5. Mutual information

    I(X;Y)=∑x,yp(x,y)log⁡p(x,y)p(x) p(y)=H(Y)−H(Y∣X)I(X; Y) = \sum_{x, y} p(x, y) \log \frac{p(x, y)}{p(x)\,p(y)} = H(Y) - H(Y \mid X)

    The KL divergence between the joint distribution and the product of its marginals. It is zero exactly when XX and YY are independent, and it equals the drop in uncertainty about YY from learning XX.

  6. Jensen-Shannon divergence

    JS⁡(p,q)=12DKL(p ∥ m)+12DKL(q ∥ m),m=12(p+q)\operatorname{JS}(p, q) = \tfrac{1}{2} D_{\mathrm{KL}}(p \,\|\, m) + \tfrac{1}{2} D_{\mathrm{KL}}(q \,\|\, m), \qquad m = \tfrac{1}{2}(p + q)

    A symmetric version of KL that is always finite, at most one bit in base 2. Each distribution is compared with the midpoint of the two.

  7. Perplexity

    PP⁡(p)=b H(p)\operatorname{PP}(p) = b^{\,H(p)}

    The number of equally likely outcomes that would have the same entropy, with bb the log base. A language model with perplexity 20 is as uncertain as a uniform choice among 20 words.

Symbols

p, qp,\ q
probability distributions over the same outcomes
x, yx,\ y
outcomes of the variables XX and YY
p(x,y)p(x, y)
the joint probability of the pair
p(x), p(y)p(x),\ p(y)
the marginal probabilities: row and column totals of the joint table
HH
entropy
DKLD_{\mathrm{KL}}
Kullback-Leibler divergence
I(X;Y)I(X; Y)
mutual information between XX and YY
mm
the midpoint distribution used by the Jensen-Shannon divergence
bb
the logarithm base (base in the config)
KK
the number of possible outcomes

Worked by hand

Take p=(0.5,0.25,0.25)p = (0.5, 0.25, 0.25) and q=(0.25,0.25,0.5)q = (0.25, 0.25, 0.5) and work in bits, using log⁡20.5=−1\log_2 0.5 = -1 and log⁡20.25=−2\log_2 0.25 = -2.

H(p)=0.5×1+0.25×2+0.25×2=1.5H(p) = 0.5 \times 1 + 0.25 \times 2 + 0.25 \times 2 = 1.5
H(p,q)=0.5×2+0.25×2+0.25×1=1.75H(p, q) = 0.5 \times 2 + 0.25 \times 2 + 0.25 \times 1 = 1.75
DKL(p ∥ q)=1.75−1.5=0.25D_{\mathrm{KL}}(p \,\|\, q) = 1.75 - 1.5 = 0.25

Using qq where pp is true costs a quarter of a bit per outcome on average. The loss comes from the first outcome, which qq rates as rarer than it is.

Visual example

Loading the example.

Try this

  • Move the weights of q until it matches p. The second block of the bar closes and the KL divergence reaches 0.
  • Pick the (0.9, 0.05, 0.05) truth and give outcome a very little weight in q: one badly judged outcome dominates the cost.
  • Compare D(p ‖ q) with D(q ‖ p). They are rarely equal.

Code sample

import numpy as np
from impl import InformationTheory, joint_from_samples

it = InformationTheory()                              # bits
it.entropy([0.5, 0.5])                                # 1.0
it.kl_divergence([0.5, 0.5], [0.25, 0.75])            # 0.2075
it.cross_entropy([0.5, 0.5], [0.25, 0.75])            # 1.2075 = entropy + KL

x = np.array([0, 0, 1, 1, 0, 1])
it.mutual_information(joint_from_samples(x, x))       # 1.0: x tells everything about itself
Read the implementation (112 lines)
"""Information theory for discrete distributions.

Entropy, cross-entropy, Kullback-Leibler and Jensen-Shannon divergence, joint and conditional entropy, and
mutual information, with the convention 0 log 0 = 0. Distributions are arrays of probabilities that sum to 1;
joint distributions are 2-D tables.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import InformationTheoryConfig
except ImportError:  # run from the template's own folder
    from config import InformationTheoryConfig

def joint_from_samples(x, y) -> np.ndarray:
    """Empirical joint distribution of two label sequences of equal length.

    Returns array (n_x, n_y) of relative frequencies, rows and columns in sorted label order.
    """
    x, y = np.asarray(x), np.asarray(y)
    if x.shape != y.shape or x.ndim != 1 or x.size == 0:
        raise ValueError("x and y must be 1-D, non-empty and of equal length")
    _, xi = np.unique(x, return_inverse=True)
    _, yi = np.unique(y, return_inverse=True)
    table = np.zeros((xi.max() + 1, yi.max() + 1))
    np.add.at(table, (xi, yi), 1.0)
    return table / table.sum()


class InformationTheory:
    """Information measures in the log base given by the config."""

    def __init__(self, config: InformationTheoryConfig | None = None) -> None:
        self.config = config or InformationTheoryConfig()
        self._log_base = math.log(self.config.base)

    @staticmethod
    def _dist(p, name: str = "p") -> np.ndarray:
        p = np.asarray(p, dtype=float)
        if np.any(p < 0) or abs(p.sum() - 1.0) > 1e-8:
            raise ValueError(f"{name} must be non-negative and sum to 1")
        return p

    def _plogq(self, p: np.ndarray, q: np.ndarray) -> np.ndarray:
        """Elementwise p * log(q) with 0 * log(anything) = 0 and p * log(0) = -inf for p > 0."""
        out = np.zeros_like(p)
        mask = p > 0
        with np.errstate(divide="ignore"):
            out[mask] = p[mask] * np.log(q[mask]) / self._log_base
        return out

    def entropy(self, p) -> float:
        """H(p) = -sum p log p. p has any shape and sums to 1 (a joint table gives the joint entropy)."""
        p = self._dist(p)
        return float(-self._plogq(p, p).sum())

    def cross_entropy(self, p, q) -> float:
        """H(p, q) = -sum p log q: the cost of coding samples of p with a code built for q."""
        p, q = self._dist(p), self._dist(q, "q") + self.config.eps
        if p.shape != q.shape:
            raise ValueError("p and q must have the same shape")
        return float(-self._plogq(p, q).sum())

    def kl_divergence(self, p, q) -> float:
        """D(p || q) = sum p log(p / q) = H(p, q) - H(p). Infinite when q is 0 somewhere p is not."""
        p, q = self._dist(p), self._dist(q, "q") + self.config.eps
        if p.shape != q.shape:
            raise ValueError("p and q must have the same shape")
        return float((self._plogq(p, p) - self._plogq(p, q)).sum())

    def js_divergence(self, p, q) -> float:
        """Jensen-Shannon divergence: the symmetric, bounded average of D(p || m) and D(q || m), m = (p + q) / 2."""
        p, q = self._dist(p), self._dist(q, "q")
        m = 0.5 * (p + q)
        return float(0.5 * (self._plogq(p, p) - self._plogq(p, m)).sum() + 0.5 * (self._plogq(q, q) - self._plogq(q, m)).sum())

    def conditional_entropy(self, joint) -> float:
        """H(Y | X) = H(X, Y) - H(X) for a joint table (n_x, n_y) with X on the rows."""
        joint = self._joint(joint)
        return self.entropy(joint) - self.entropy(joint.sum(axis=1))

    def mutual_information(self, joint) -> float:
        """I(X; Y) = sum p(x, y) log(p(x, y) / (p(x) p(y))) for a joint table (n_x, n_y)."""
        joint = self._joint(joint)
        product = np.outer(joint.sum(axis=1), joint.sum(axis=0))
        return float((self._plogq(joint, joint) - self._plogq(joint, product)).sum())

    def normalized_mutual_information(self, joint) -> float:
        """I(X; Y) / sqrt(H(X) H(Y)), between 0 and 1. Returns 0 when either variable is constant."""
        joint = self._joint(joint)
        h_x, h_y = self.entropy(joint.sum(axis=1)), self.entropy(joint.sum(axis=0))
        if h_x == 0 or h_y == 0:
            return 0.0
        return self.mutual_information(joint) / math.sqrt(h_x * h_y)

    def perplexity(self, p) -> float:
        """base ** H(p): the number of equally likely outcomes with the same entropy."""
        return float(self.config.base ** self.entropy(p))

    def entropy_of_samples(self, x) -> float:
        """Plug-in entropy estimate of a 1-D sequence of labels, from its relative frequencies."""
        _, counts = np.unique(np.asarray(x), return_counts=True)
        return self.entropy(counts / counts.sum())

    def _joint(self, joint) -> np.ndarray:
        joint = self._dist(joint, "joint")
        if joint.ndim != 2:
            raise ValueError("joint must be a 2-D table")
        return joint
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create InformationTheory with the default config and reproduce the worked numbers with entropy, cross_entropy and kl_divergence. Then set q to (0.8, 0.1, 0.1) and compute kl_divergence(p, q) and kl_divergence(q, p). Finally build a table with joint_from_samples from two label lists you write and compare mutual_information for a copied list and a shuffled one.

Check on learning

  1. Why does a classifier that puts probability zero on the correct class receive an infinite loss, and is that a sensible penalty?
    A way to think about it

    Look at −log⁡q(x)-\log q(x) as q(x)q(x) goes to zero. Then think about what being certain and wrong should cost.

  2. D(p ∥ q)D(p \,\|\, q) punishes qq for being small where pp is large. What does D(q ∥ p)D(q \,\|\, p) punish, and how would a model fitted with each behave on a two-peaked target?
    A way to think about it

    See which distribution supplies the weights in each sum. One direction forces coverage of every peak, the other allows sitting on a single peak.

  3. Two features each share 0.3 bits of mutual information with a label. Can the pair together share more than 0.6 bits?
    A way to think about it

    Think of a label that is the exclusive-or of two fair bits. Each bit alone tells you nothing, yet together they decide it.

  4. You estimate mutual information between two independent variables from 50 samples and get 0.08 bits, not 0. What explains it and how could you check?
    A way to think about it

    Random counts never match the product of the marginals exactly, and the measure cannot go negative. Shuffle one variable many times to see the size of that floor.

  5. If YY is a deterministic function of XX, what are H(Y∣X)H(Y \mid X) and I(X;Y)I(X; Y)?
    A way to think about it

    Once XX is known there is nothing left to learn about YY. Substitute that into the second form of the mutual information formula.