Mutual information and the data processing inequality
Before this lesson: lesson 02 (joint and conditional entropy, the chain rule, the two-bar diagram), lesson 03 (KL divergence, Gibbs' inequality) and lesson 06 (differential entropy, the Gaussian, invariance of KL). Joint and conditional distributions from probability lesson 04 and the multivariate Gaussian from probability lesson 05. Time: about 75 minutes, plus the notebook.
Why this matters #
- Feature selection and decision trees.
mutual_info_classifin scikit-learn ranks features by their mutual information with the label. The "information gain" of a decision-tree split is the mutual information between the split and the label. - Representation learning. Contrastive methods (CPC, SimCLR, CLIP) maximize a lower bound on the mutual information between two views of the data (lesson 08). The data processing inequality limits what any encoder can keep.
- Bayesian experimental design. The expected information gain of an experiment is the mutual information between the unknown parameters and the measurement. Choose the sensor location or the simulation that maximizes it.
- Simulation-based inference. A summary statistic of simulator output can only lose information about the parameters. It loses nothing exactly when it is sufficient.
- Communication. The capacity of a noisy channel, the largest rate of reliable communication, is a maximum of mutual information.
In this track is the natural logarithm and gives nats; gives bits. Tables in this lesson are in bits; Gaussian formulas are in nats. is the binary entropy in bits (lesson 01).
1. Predict first #
2. The picture #
2.1 Two bits and a noisy channel #
Let be a fair bit. Three cases:
- Copy, . Learning tells you exactly: 1 bit of information.
- Independent, is a separate fair coin. Learning tells you nothing: 0 bits.
- Noisy copy. equals with probability and with probability . This is the binary symmetric channel BSC().
For the noisy copy, count the uncertainty about in two steps.
- is a fair bit too (each value is reached with probability ), so bit.
- If you know , the only uncertainty left is whether the channel flipped the bit: .
- The information is the uncertainty that knowing removes: .
For : , so bits. A channel that is right 80% of the time carries much less than 0.8 bits per use.
Move the flip probability . Left: the channel; the arrow widths are the transition probabilities. Middle: the bar is split into and the shared part ; the bar is split into and . Right: the violet curve and the current point. Notice that is as good as . Then move the input bias : the information drops below the violet curve.
is a fair bit and is sent through BSC(0.9): the bit is flipped 90% of the time. What is ?
, so bits. A channel that almost always flips is almost as useful as one that almost never flips: read . The useless channel is , where is a fair coin whatever is.
2.2 How far the joint is from independence #
The two-bar picture in the widget is the picture of lesson 02: the mutual information is the overlap of and . A second picture compares two tables:
- the real joint table ;
- the table you would get if and were independent but had the same marginals: .
For each cell, the pointwise mutual information is
It is positive when the pair occurs more often than under independence, and negative when it occurs less often. The mutual information is the average pmi under the joint:
Some pmi values can be negative, but the average is never negative: it is a KL divergence (lesson 03).
Edit the weights of the joint table, or try the presets. Left: the joint (blue). Middle: the product of its marginals (orange), the "independent version". Right: each cell's contribution in bits, violet when positive and grey when negative. Their sum is . Make all rows proportional and watch become 0. Try "": the correlation of this pair is 0, but is not.
In a joint table, two cells have a negative pointwise mutual information. What can you say about ?
, and Gibbs' inequality makes every KL , with equality only when the two tables are equal, that is, every pmi is 0. Negative pmi cells are always balanced by positive ones in the average under .
3. Definitions and main results #
3.1 Mutual information #
For discrete random variables with joint distribution and marginals , , the mutual information is
For densities, replace the sums by integrals. We write a semicolon, , because the two arguments are two groups of variables: is the information between and the pair .
Theorem 1 (identities and bounds).
- (a) .
- (b) , with equality if and only if and are independent.
- (c) and . For discrete variables, .
Proof.
- (a) Write the pmi as . Take the mean under : the first part gives , the second . So . Exchange the roles of and for the second form. The chain rule (lesson 02) gives the third.
- (b) is a KL divergence, so Gibbs' inequality gives , with equality only if for every : independence.
- (c) Symmetry is clear from the KL form. With , , so . Discrete conditional entropies are , so , and in the same way .
For continuous variables, (a) and (b) still hold, with differential entropies. The bound (c) fails: differential entropies can be negative, and for a continuous (a real number carries infinitely many bits about itself).
3.2 Conditional mutual information and the chain rule #
The conditional mutual information is the mutual information inside each slice , averaged over :
It is 0 if and only if and are independent given . Add and subtract to get the chain rule for mutual information:
Conditioning can increase mutual information. Let and be independent fair bits and (XOR). Then . But once you know , knowing tells you exactly: bit. This is why the three-circle Venn picture fails for three variables (lesson 02).
3.3 Mutual information of Gaussians #
Theorem 2 (Gaussian mutual information). Let be jointly Gaussian with positive definite covariance . Then
For two scalars with correlation : .
Proof.
- Use (Theorem 1a with differential entropies).
- A -dimensional Gaussian has (lesson 06). The factors cancel, and the log-dets give the formula.
- Scalars: , so .
A check with the other form. Given , is Gaussian with variance , for every . So ✓. The mutual information depends only on , not on the scales. At it is nats ( bits); as it goes to infinity.
Mutual information sees nonlinear dependence. Correlation measures only linear dependence. Let be uniform on and . Then : the correlation is 0. But is a function of , so and bits. The formula is the mutual information only for jointly Gaussian variables.
3.4 Invariance under invertible maps #
Theorem 3. Let and be invertible maps (for densities: smooth, with smooth inverses). Then .
Proof (densities).
- Let and . By the change of variables, at and : , and .
- In the ratio the Jacobian factors cancel, so at every point.
- Take the mean: .
For discrete variables an invertible map is a relabelling, which changes nothing. In contrast, the differential entropy changes, (lesson 06), and the correlation changes under nonlinear maps. Mutual information describes only the dependence, not the coordinates. This makes it the right quantity for continuous data with arbitrary units.
Apply or to the samples. The true mutual information does not change: the maps are invertible. The sample correlation drops, and the Gaussian formula with (orange) gives a wrong value, because the transformed data are not jointly Gaussian. The entropy of the horizontal coordinate changes too. Move to see how grows as .
Two variables have correlation exactly 0. What can you conclude about their mutual information?
Correlation measures only linear dependence. For uniform on and the correlation is 0, but bits, because is a function of . For jointly Gaussian variables, , so there does give .
3.5 The data processing inequality #
is a Markov chain if : is produced from alone, without looking at . Equivalently, and are independent given : . Every function , and every random processing of with its own independent noise, gives a Markov chain.
Theorem 4 (data processing inequality, DPI). If is a Markov chain, then
Equality holds if and only if : once is known, tells nothing more about .
Proof.
- Markov property: .
- Apply the chain rule for in two orders: .
- With step 1, .
- Conditional mutual information is , so , with equality exactly when .
Two channels in a row. is a fair bit, = BSC(0.2) of , and = BSC(0.2) of . differs from when exactly one of the two channels flips: probability . So is BSC(0.32) of , and bits, much less than bits.
Choose how is made from . The bars are , and (grey); the aqua segment is the information about that the processing lost. Try every option and both sliders: the yellow bar is never longer than the violet one. The copy and the relabelling (both invertible) lose nothing; a constant loses everything.
Corollaries.
- for every function : computing a feature cannot add information.
- A Markov chain also runs backwards, , so the DPI also gives .
- A second proof of Theorem 3: for an invertible , both and are Markov chains, so the DPI gives in both directions.
Sufficient statistics. Let be a parameter with a prior, the data and a statistic. is a Markov chain, so . The statistic is sufficient for when does not depend on (Fisher's definition). Then is also a Markov chain, and for every prior. Example: coin flips with bias , and = the number of heads. Given , every sequence with heads has probability , whatever is. So the count keeps all the information about , and the order of the flips adds nothing.
with bits, and for a cleverly designed function . Which value of is possible?
The DPI gives for every function , linear or not, and mutual information is never negative. Equality holds when is invertible, or more generally when is a sufficient statistic: it merges only values of with the same . A good encoder can make information easier to use, but it cannot create more of it.
The DPI for KL divergence, and why deterministic encoders break
DPI for KL. Send two input distributions and through the same channel , giving output distributions and . Then .
- Form the joints and . In their log-ratio the channel cancels, so .
- Factor the same joints through the output: .
The DPI for mutual information is the special case and with the channel acting on . The same holds for every f-divergence (lesson 08).
Deterministic encoders. Let be continuous and with injective and smooth. Then : knowing gives exactly, and a real number carries infinitely many bits. So "the encoder compresses the input", measured by , means nothing for a deterministic network on continuous inputs. It needs noise in the encoder () or a discrete . This point matters in the information-bottleneck debate about deep networks (lesson 10).
3.6 Estimating mutual information from samples #
In practice we have samples, not the joint distribution. The simplest estimator is the plug-in estimator: count the pairs, form the empirical table , and compute . For independent or weakly dependent variables it is biased upward:
- always. If the true value is 0, every error is upward: a finite sample always shows some spurious dependence.
- More precisely, each plug-in entropy is biased down, nats for cells with positive probability and (the Miller–Madow correction). In the joint entropy has the most cells, so it has the most bias. For independent with and values, the bias of is about
The bias is not always upward. For , the joint table has only positive cells, so , which is biased down by .
Test before you trust. A small positive is not evidence of dependence. Compare it with a permutation baseline: shuffle many times (this destroys any dependence but keeps both marginals), recompute each time, and see where the real value falls. is the G-test statistic of classical statistics; under independence it is approximately with degrees of freedom, whose mean gives the bias formula above.
Change and , then switch to "weak dependence". The magenta histogram shows 400 plug-in estimates; its mean is the magenta line. The blue line is the true , and the aqua dashed line is the true plus the predicted bias . The yellow line is one data set, with its permutation p-value. Notice: with and the bias is large; with large the estimates concentrate at the truth.
For continuous data you must also choose bins, and the answer depends on them. The
-nearest-neighbour (KSG) estimator of Kraskov, Stögbauer and Grassberger avoids bins and is used
by mutual_info_regression and mutual_info_classif in scikit-learn; it is still biased in high
dimensions. For high-dimensional data such as images, tables and neighbours fail, and we need the
variational bounds of lesson 08.
and are independent, each with 10 values, and you have samples. What plug-in estimate do you expect on average?
For independent variables, nats. Every estimate is , so errors around a true value of 0 can only be upward. A measured value near 0.04 is therefore no evidence of dependence; a permutation test tells you more.
3.7 Channel capacity, in one paragraph #
A channel is a conditional distribution . Its capacity is , the largest mutual information over all input distributions. Shannon's channel coding theorem says that reliable communication is possible at every rate below bits per channel use, and impossible above it. For the BSC, for input ; it is largest at , so . For , bits per use (MacKay, chapters 9–10).
Answers to section 1. (1) bits: much less than 0.8 bits. (2) No. and then any processing of is still a Markov chain from , so the DPI gives . For two BSC(0.2) in a row, bits. (3) The correlation is 0, but bits: is a function of .
4. Worked example #
(a) A forecast table, three ways. : heavy rain observed (1) or not (0). : heavy rain forecast (1) or not (0).
| 0.70 | 0.10 | 0.80 | |
| 0.05 | 0.15 | 0.20 | |
| 0.75 | 0.25 |
In bits:
- From . . The columns give : and . So and .
- From . . The rows give , and ✓.
- KL form. The pmi values are , , and . Weighted by : ✓. Two pmi values are negative; the average is not.
A forecast of rain makes you less sure about the outcome for that one value (), but on average the forecast helps.
(b) Gaussians. For : nats bits. For : nats. Five independent pairs with (so ) have nats: mutual information adds over independent pairs, because the covariance is block diagonal and the determinants multiply.
(c) Two channels in a row. fair, = BSC(0.2) of , = BSC(0.2) of :
- bits;
- = BSC(0.32) of , so bits ✓;
- bits, so holds too.
(d) A sufficient statistic. is or with probability each, and is three flips of a coin with bias . Exact computation over the joint table (notebook): bits; with = the number of heads, bits (nothing lost); with only the first flip, bits.
(e) Plug-in bias. Independent with 4 values each and : nats, although the true value is 0.
5. In code #
SciPy computes entropies and KL divergences; scikit-learn has the plug-in estimator
(mutual_info_score, in nats) and the kNN estimator (mutual_info_regression).
import numpy as np
from scipy.stats import entropy, multivariate_normal
from sklearn.metrics import mutual_info_score
from sklearn.feature_selection import mutual_info_regression
# (a) MI of the forecast table, three ways (bits)
pxy = np.array([[0.70, 0.10],
[0.05, 0.15]])
px, py = pxy.sum(axis=1), pxy.sum(axis=0)
H = lambda t: entropy(np.ravel(t), base=2)
print(H(px) + H(py) - H(pxy)) # 0.2142
print(entropy(pxy.ravel(), np.outer(px, py).ravel(), base=2)) # 0.2142, the KL form
print(mutual_info_score(None, None, contingency=100 * pxy) / np.log(2)) # 0.2142 (sklearn wants counts, gives nats)
# (b) Gaussian MI from entropies: h(X) + h(Y) - h(X, Y)
C = np.array([[1.0, 0.9], [0.9, 1.0]])
h = lambda S: multivariate_normal(cov=S).entropy()
print(h(C[:1, :1]) + h(C[1:, 1:]) - h(C), -0.5 * np.log(1 - 0.9**2)) # 0.8304 0.8304
# (c) DPI: a joint table times a channel matrix p(z | y) gives p(x, z)
K = np.array([[0.8, 0.2], [0.2, 0.8]]) # BSC(0.2); each row sums to 1
pxy2 = np.diag([0.5, 0.5]) @ K # X fair, Y = BSC(X)
pxz = pxy2 @ K # Z = BSC(Y)
for t in (pxy2, pxz):
print(entropy(t.ravel(), np.outer(t.sum(1), t.sum(0)).ravel(), base=2)) # 0.2781, then 0.0956
# (d) Plug-in bias for independent X, Y with 4 values each and N = 500 (nats)
rng = np.random.default_rng(0)
est = [mutual_info_score(rng.integers(0, 4, 500), rng.integers(0, 4, 500)) for _ in range(2000)]
print(np.mean(est), 3 * 3 / (2 * 500)) # 0.0089 0.009
# (e) Invariance: x -> x^3 and y -> exp(y) change the correlation, not the MI
x, y = rng.multivariate_normal([0, 0], C, size=5000).T
print(np.corrcoef(x, y)[0, 1], np.corrcoef(x**3, np.exp(y))[0, 1]) # 0.903 0.668
ksg = lambda a, b: mutual_info_regression(a[:, None], b, random_state=0)[0] # kNN (KSG) estimator, nats
print(ksg(x, y), ksg(x**3, np.exp(y))) # 0.860 0.823: both near the true 0.830
The kNN estimate is not exactly invariant (distances change under the maps); the true mutual
information is. mutual_info_score(labels_x, labels_y) builds the table of counts for you; pass
contingency= when you already have one.
6. Where it shows up #
- Feature selection.
SelectKBest(mutual_info_classif)keeps the features with the largest estimated mutual information with the label, nonlinear dependence included. Compare the scores with a permutation baseline; small scores of independent features are not zero. - Decision trees. The information gain of a split is , the mutual information between the split and the label (the decision-tree lesson of the ML fundamentals track, in preparation).
- Representations and the DPI. For a label , an input and a representation , the chain is Markov, so : an encoder can keep label information or lose it, never create it. It can make the information easier to use for a simple classifier: the DPI is about information, not usable information. Keeping while dropping the rest of is the information bottleneck (lesson 10).
- Contrastive learning. InfoNCE (CPC, SimCLR, CLIP) is a lower bound on the mutual information between two views; lesson 08 derives it.
- Bayesian experimental design. The expected information gain of a design is . For a linear-Gaussian model it is , the Gaussian mutual information of section 3.3.
- Simulation-based inference. Neural summary statistics are often trained to maximize a bound on . The DPI caps them at , and sufficiency is the equality case.
- Dependence between scientific fields. The mutual information between a ground-motion amplitude and a site parameter is the same for the amplitude and its logarithm, unlike the correlation. A histogram estimate between two climate indices needs a permutation baseline.
7. Common mistakes #
- "Correlation 0 means independent." For uniform on and , the correlation is 0 but bits. Only for jointly Gaussian variables does imply independence.
- Using on non-Gaussian data. It is the mutual information only for jointly Gaussian variables; on other data it uses only the linear part of the dependence.
- Applying the DPI without a Markov chain. must depend on only through . And conditioning on a third variable can increase mutual information (the XOR example).
- Treating mutual information like entropy for continuous data. changes with the units; mutual information does not. Continuous mutual information can be infinite (); discrete mutual information is at most .
- Trusting a small plug-in estimate. For independent variables it is about nats, not 0. Use a permutation test.
- Confusing information with usable information. The DPI does not say that preprocessing is useless. It says it cannot add information; it can still make the information easier to extract.
8. Check yourself #
- is uniform on and . Compute and in bits.
Answer
, so the correlation is 0. is a function of , so and bits. - is jointly Gaussian with . Give . What happens to and to if you
replace by ?
Answer
nats. does not change ( is invertible). , because the log-Jacobian of is . - is a Markov chain. Prove .
Answer
The chain also runs backwards, ( and are independent given , which is symmetric). The DPI for this chain gives , and mutual information is symmetric. - and are independent with 10 values each, and . You measure nats. Is
that evidence of dependence?
Answer
No. The expected value under independence is nats. , against a null with mean 81 and standard deviation , gives . A permutation test gives the same message. - Give for a discrete and for a continuous .
Answer
Discrete: . Continuous: , because knowing removes an infinite amount of uncertainty about a real number (). - What is the capacity of BSC(0.2), and which input distribution reaches it?
Answer
bits per use, reached by the uniform input , which makes as large as possible (1 bit).
Write the mutual information as a difference of entropies.
.
Write the mutual information as a KL divergence.
: the distance of the joint from the product of its marginals.
What is for a fair bit sent through BSC()?
bits; for , bits.
What is the mutual information of two jointly Gaussian scalars with correlation ?
nats; for it is nats.
What is for a discrete ?
, because .
State the data processing inequality and its condition.
If is a Markov chain ( depends on only through ), then .
Why does the data processing inequality hold?
The chain rule gives when , and conditional mutual information is .
How does mutual information change under invertible maps , ?
It does not change: the Jacobian factors cancel in . Differential entropy and correlation do change.
What is the expected plug-in mutual information of independent variables with and values and samples?
About nats, not 0: the plug-in estimator is biased upward.
Give an example with zero correlation but positive mutual information.
uniform on and : the correlation is 0 and bits.
9. Interview angle #
- "What is mutual information, and why use it instead of correlation?" The KL from the joint to the product of the marginals. It is zero exactly for independent variables, it sees nonlinear dependence, and it does not change under invertible transforms of each variable.
- "Prove the data processing inequality." Expand with the chain rule in two orders, use and .
- "Can a neural network's hidden layer contain more information about the label than the input?" No: is Markov, so . It can contain more usable information for a linear probe.
- "How would you estimate mutual information between two signals?" Discrete: plug-in with a permutation baseline (or a bias correction). Continuous, low dimension: the Gaussian formula if the data are Gaussian, else KSG. High dimension: a variational bound with a learned critic (InfoNCE). Always state the bias.
- "What is the information gain of a decision-tree split?" .
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
mutual_information(pxy)from a joint table, checked three ways: entropies, the KL form, andsklearn.metrics.mutual_info_scoreon counts.gaussian_mutual_information(cov, dx)from log-determinants, checked against and against invariance under invertible linear maps of each block.- The DPI by simulation: multiply a joint table by random channel matrices and check .
- The plug-in bias: simulate independent data, compare the mean estimate with , and write a permutation test.
- Rank the features of the breast-cancer data set (
sklearn.datasets.load_breast_cancer) by mutual information and by correlation with the label, with one synthetic feature whose spread, not its mean, depends on the class: correlation misses it, mutual information does not.
11. Watch and read #
- David MacKay, Information Theory, Inference, and Learning Algorithms, free PDF: §8.1 (mutual information and the two-bar diagram), §8.3 and exercise 8.9 (the data-processing theorem, with solution), chapter 9 (channels and capacity).
- Kevin Murphy, Probabilistic Machine Learning: An Introduction, free PDF: §6.3 (mutual information, conditional mutual information, the data processing inequality, sufficient statistics).
- Thomas Cover and Joy Thomas, Elements of Information Theory, 2nd edition, §2.4–2.9 (mutual information, chain rules, the data-processing inequality, sufficient statistics) and §8.5 (mutual information of densities; example 8.5.1 is the Gaussian case).
- Alexander Kraskov, Harald Stögbauer and Peter Grassberger, "Estimating mutual information" (2004): the kNN (KSG) estimator used by scikit-learn.
- Liam Paninski, "Estimation of entropy and mutual information" (Neural Computation, 2003): the bias of plug-in estimators and how to correct it.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.