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 but you expected , and it is never smaller than the entropy of . 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
- Write the distribution as an array of probabilities that sums to 1. A joint distribution of two variables is a two-dimensional table.
- Pick the logarithm base. Base 2 gives bits, base gives nats.
- For entropy, multiply each probability by the log of itself, add up and change the sign. A term with probability zero counts as zero.
- For cross-entropy, use in place of while still weighting by .
- Subtract the entropy from the cross-entropy to get the KL divergence from to .
- 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. and answer different questions and usually differ, so it is not a distance.
- If is zero where is not, cross-entropy and KL are infinite. The eps setting avoids this by adding a small value to , 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 . 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
| If | Use instead |
|---|---|
| You need a symmetric, bounded difference between two distributions | Jensen-Shannon divergence |
| You only need the strength of a straight-line relation between two numeric columns | Correlation |
| Variables are continuous and binning would lose too much | A nearest-neighbour mutual information estimator, or a rank correlation |
Math foundations
Entropy
The average surprise of a draw from , where the surprise of an outcome is . It is zero for a certain outcome and largest, , for equally likely outcomes.
Cross-entropy
The average surprise when outcomes follow but surprise is measured with . With the true labels and the model's predictions, this is the classification loss.
KL divergence
The extra surprise caused by using in place of . It is zero only when the two distributions are equal. Since is fixed by the data, minimizing cross-entropy and minimizing KL are the same task.
Conditional entropy
The uncertainty left in once is known. The joint entropy is the entropy formula applied to every cell of the joint table.
Mutual information
The KL divergence between the joint distribution and the product of its marginals. It is zero exactly when and are independent, and it equals the drop in uncertainty about from learning .
Jensen-Shannon divergence
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.
Perplexity
The number of equally likely outcomes that would have the same entropy, with the log base. A language model with perplexity 20 is as uncertain as a uniform choice among 20 words.
Symbols
- probability distributions over the same outcomes
- outcomes of the variables and
- the joint probability of the pair
- the marginal probabilities: row and column totals of the joint table
- entropy
- Kullback-Leibler divergence
- mutual information between and
- the midpoint distribution used by the Jensen-Shannon divergence
- the logarithm base (base in the config)
- the number of possible outcomes
Worked by hand
Take and and work in bits, using and .
Using where is true costs a quarter of a bit per outcome on average. The loss comes from the first outcome, which 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 itselfRead 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
- 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 as goes to zero. Then think about what being certain and wrong should cost.
- punishes for being small where is large. What does 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.
- 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.
- 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.
- If is a deterministic function of , what are and ?
A way to think about it
Once is known there is nothing left to learn about . Substitute that into the second form of the mutual information formula.