Mutual information: dependence beyond a straight line
互信息
Compute information in bits, expose nonlinear and XOR dependence, and separate population identities from empirical estimates.
mutual-informationHow much does one variable tell you about another?
A fair binary signal X is copied into Y, but independently flipped one quarter of the time. Before seeing X, Y is equally likely to be zero or one: one bit of uncertainty. After seeing X, the remaining uncertainty is the entropy of a 25% flip. The reduction is about 0.188722 bits. A perfect copy gives one bit; an independent fair bit gives none.
Mutual information describes a joint probability distribution. It does not certify that a feature is causal, useful on a new population or learnable with the available sample size. Read entropy and KL divergence first.
Compare the joint distribution with independence
For finite-valued X and Y, the product p(x)p(y) is the independent distribution with the same marginals. Their mutual information in bits is:
A positive joint cell necessarily has positive row and column marginals, so its ratio is well-defined. A zero cell contributes zero. KL nonnegativity gives I≥0, with equality exactly when the finite joint distribution factorizes. Swapping X and Y leaves the sum unchanged. Shalizi’s lecture explains both the dependence interpretation and pointwise mutual information.
The logarithm inside the expectation is PMI. It may be negative: in the noisy-copy example, a mismatch cell has mass1/8 while its independent reference mass is1/4, giving log₂(1/2)=−1 bit. The two matching cells give positive contributions. Average PMI, not each individual PMI, is nonnegative.
Expand the logarithm into log p(x,y)−log p(x)−log p(y), and sum each marginal term. This yields:
Conditional entropy averages over X; a particular observation can increase uncertainty even though the average cannot. For the binary flip model, H(Y|X)=h₂(1/4), where h₂(r)=−r log₂r−(1−r)log₂(1−r). Thus I=1−h₂(1/4). This is a population calculation for the specified distribution, not an estimated confidence bound.
Zero correlation can hide dependence
Let X be uniform on −1,0,1 and Y=X². Symmetry makes E[X]=E[XY]=0, so covariance and correlation are zero; both variances are positive. Yet Y is determined by X. Its probabilities are1/3 and2/3, giving I(X;Y)=H(Y)≈0.918296 bits. A straight-line association measure misses this dependence.
Two weak-looking features can work together
Let independent fair bits X,Y determine Z=X XOR Y. Each input alone is independent of Z, but the pair determines it. The chain rule states:
Here the terms are1=0+1 bits. Conditional MI is the average KL dependence within positive-probability conditioning slices. It is not obtained by simply subtracting I(Y;X). MIT’s notes, Sections2.3–2.4 and3.1 give the chain rule and data-processing conditions. If Z is generated only from Y, with X conditionally independent of Z given Y, then I(X;Z)≤I(X;Y). A processing step cannot invent information about X under that Markov condition.
Read information from a contingency table
This complete Python 3.12 program accepts rectangular integer count tables up to32×32, with each count between0 and one million and a positive total. Rows and columns identify categories, not measured numeric distances. It converts positive cell ratios exactly with fractions, then evaluates logarithms in floating point. Results are in bits and are not exact rational information values.
from fractions import Fraction as F
from math import fsum, log2
def mutual_information(counts):
table = [list(row) for row in counts]
if not table or not table[0] or len(table)>32 or len(table[0])>32:
raise ValueError('nonempty table up to 32 by 32 required')
width = len(table[0])
if any(len(row)!=width for row in table):
raise ValueError('rectangular table required')
if any(type(v) is not int or not 0 <= v <= 10**6 for row in table for v in row):
raise ValueError('integer counts in [0,1000000] required')
rows = list(map(sum,table)); total = sum(rows)
if total == 0: raise ValueError('positive total required')
cols = [sum(row[j] for row in table) for j in range(width)]
terms = [float(F(v,total))*log2(float(F(v*total,rows[i]*cols[j])))
for i,row in enumerate(table) for j,v in enumerate(row) if v]
return fsum(terms)
if __name__ == '__main__':
examples = {
'independent': [[1,1],[1,1]],
'perfect copy': [[2,0],[0,2]],
'noisy copy, flip probability 1/4': [[3,1],[1,3]],
'X versus X squared': [[0,1],[1,0],[0,1]],
'X versus XOR(X,Y)': [[1,1],[1,1]],
'(X,Y) versus XOR(X,Y)': [[1,0],[0,1],[0,1],[1,0]],
}
for name, table in examples.items():
print(name+':', f'{mutual_information(table):.6f}', 'bits')
pmi_mismatch = log2(float(F(1,2)))
print('noisy-copy mismatch PMI:',f'{pmi_mismatch:.6f}','bits')
Output:
independent: 0.000000 bits
perfect copy: 1.000000 bits
noisy copy, flip probability 1/4: 0.188722 bits
X versus X squared: 0.918296 bits
X versus XOR(X,Y): 0.000000 bits
(X,Y) versus XOR(X,Y): 1.000000 bits
noisy-copy mismatch PMI: -1.000000 bits
The tables encode the specified toy distributions exactly. If the same program receives sampled counts, it instead computes the plug-in estimate from the empirical distribution. These are different interpretations of the same arithmetic.
For r rows and c columns, the computation takes O(rc) operations and O(rc) storage because the input is copied and terms are collected. Zero rows and columns add no information. Relabeling categories, transposing the table or multiplying all counts by a common positive integer leaves the represented probabilities and MI unchanged, within floating-point tolerance. The small input bounds avoid extreme probability ratios; they are an implementation contract, not a theorem about every possible count table.
A good dependence measure is not a free estimator
Sparse empirical tables can produce apparent dependence even when the population variables are independent. Increasing the number of bins may change the estimate substantially; report the estimator, category construction and uncertainty. Feature selection using MI must happen inside training folds. Selecting features using test labels leaks information even if the final classifier never sees those labels directly.
MI is symmetric, so it does not identify causal direction. Shared causes and selection can create dependence. For continuous variables the KL definition extends beyond discrete tables, but deterministic continuous relationships may have infinite MI; subtracting ill-defined differential entropies can fail. A histogram program is not a general continuous-information estimator.
The XOR example also warns against selecting features only by their individual score. A useful interaction can be invisible in every pairwise comparison. Conversely, a high score can be redundant with already selected features; conditional questions matter.
Keep distribution, units and conditioning explicit
- What is I(X;X) for a fair bit, and what is I(X;Y) for independent fair bits?
Answer 1: One bit and zero bits respectively.
- Does a negative mismatch PMI contradict MI nonnegativity?
Answer 2: No. MI averages PMI over the joint distribution; individual terms can be negative.
- In XOR, how much information does Y provide about Z after X is known?
Answer 3: One bit. Given X, Y determines Z, even though I(Y;Z)=0 without conditioning.
- Why does duplicating every table count leave MI unchanged?
Answer 4: The normalized joint and marginal probabilities are unchanged. Sample size matters for estimation uncertainty, which this scalar calculation does not report.
From a score to a question about representation
Information theory asks how uncertainty changes under coding and observation; machine learning often estimates related quantities to compare representations or select features. Those estimates depend on a sampling and modeling procedure. The two course sources provide the probability identities; the noisy-copy, nonlinear and XOR calculations here make distinct failure modes visible.
Project: sample independent categorical variables, vary sample size and category count, and compare plug-in MI with a permutation null. Keep binning and feature selection inside the resampling procedure when required by the test. Report an estimated dependence quantity separately from a calibrated test decision.
Make a prediction, then check
Can two features each have zero MI with a label but jointly determine it?
Learning objectives
- Compute finite MI and distinguish it from pointwise information.
- Explain nonlinear dependence and conditional feature interactions.
Prerequisites & connections
Explore related knowledge →References
- MIT 6.441 — Course Notes, Chapters2–3
Yury Polyanskiy; Yihong Wu · 2016 - Information Theory I — Scene Setting and Statistical Applications, Lecture9
Cosma Shalizi · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, exact/literal and numerical checks, and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: cited primary-source locations, explicit assumptions, original derivations and examples, bilingual equations and four matching exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed: literal reference cases, mathematical invariants or full finite-design calibration, invalid inputs and bilingual structure. Rational arithmetic is separated from floating logarithms. R/SciPy documentation was read without claiming those runtimes were executed.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- MIT 6.441 — Course Notes, Chapters2–3 · 2016 course notes Sections2.3–2.4 and3.1: MI as divergence, finite entropy identities, conditional chain rule and Markov data processing.
- Information Theory I — Scene Setting and Statistical Applications, Lecture9 · Lecture9: dependence, PMI as the pointwise log ratio, conditional information and estimation cautions. Tables and exact toy distributions are original.
Related topics