Module contents
Lesson 3 of 19Core 110 min

Mutual information, data processing and Fano

Mutual information measures how much one variable reduces uncertainty about another and is defined as KL between the joint and product of marginals. Prove its properties, chain rule, data processing inequality and Fano's inequality, bounding any estimator's error. Study information diagrams and their limitations with three variables, where synergy appears.

After this lesson you can

  • Calculate I(X;Y) by its three equivalent formulas and verify agreement.
  • Prove conditioning reduces entropy on average using I(X;Y) ≥ 0.
  • Prove data processing and explain what it does and does not imply for learned representations.
  • Apply Fano's inequality to lower-bound classifier error probability.
  • Construct a three-variable information diagram and detect negative interaction information (XOR).
  • Characterize a sufficient statistic as a transformation preserving I(θ;X).

Before you start

Motivation: how much one variable tells me about another

A laboratory has a test for a disease with 10% prevalence. The test is correct 90% of the time for both ill people (sensitivity) and healthy people (specificity). Let X∈{sano,enfermo}X \in \{\text{sano}, \text{enfermo}\} be true status and Y∈{−,+}Y \in \{-, +\} the result. Before testing, uncertainty about XX is entropy H(X)=h(0.1)=0.469H(X) = h(0.1) = 0.469 bits, with hh the binary entropy function. And after?

  • Positive result (occurs 18% of the time). By Bayes, P(enfermo∣+)=0.1⋅0.90.1⋅0.9+0.9⋅0.1=0.5\Pr(\text{enfermo} \mid +) = \frac{0.1 \cdot 0.9}{0.1 \cdot 0.9 + 0.9 \cdot 0.1} = 0.5. Uncertainty about XX is now H(X∣Y=+)=1H(X \mid Y = +) = 1 bit: more than twice as high as before looking.
  • Negative result (82%). P(enfermo∣−)=0.012\Pr(\text{enfermo} \mid -) = 0.012 and H(X∣Y=−)=0.095H(X \mid Y = -) = 0.095 bits.

Mean remaining uncertainty is conditional entropy H(X∣Y)=0.82⋅0.095+0.18⋅1=0.258H(X \mid Y) = 0.82 \cdot 0.095 + 0.18 \cdot 1 = 0.258 bits. The test reduced uncertainty on average by 0.469−0.258=0.2110.469 - 0.258 = 0.211 bits. This number is mutual information I(X;Y)I(X;Y), and the example teaches two things. First, a particular result can leave you more uncertain than before (a positive screening test), but waiting to see YY never worsens mean uncertainty. Second, 0.2110.211 bits measures the test’s value without mentioning any decision rule, false-positive cost or prior utility distribution.

This quantity appears under different names throughout later work:

  • Feature selection. Ranking features XiX_i by I(Xi;Y)I(X_i; Y) is the most-used filter, and decision-tree information gain is exactly mutual information (feature selection taxonomy).
  • Representation learning. Contrastive learning maximizes lower bounds on mutual information between two views of the same datum (InfoNCE), and model probing asks how much information about a concept a layer contains.
  • Channels. Channel capacity is maximum I(X;Y)I(X;Y) over possible inputs (lesson 9).
  • Learning limits. Processing creates no information (data processing inequality), and information variables leave unresolved lower-bounds any classifier’s error (Fano’s inequality). Information generalization bounds measure I(datos;paraˊmetros)I(\text{datos}; \text{parámetros}) (information-theoretic bounds).

This lesson defines mutual information as Kullback–Leibler divergence and derives its three equivalent formulas and properties; extends it to conditional information and the chain rule; constructs information diagrams and shows where they stop being reliable (three variables introduce synergy). It proves data processing and Fano inequalities and closes with mutual information versus correlation. Unless stated otherwise, log⁡\log is base-2 logarithm and information is in bits.

Definition and three ways to calculate it

Let X,YX, Y be discrete random variables with finite alphabets, joint p(x,y)p(x, y) and marginals p(x)p(x), p(y)p(y). If XX and YY were independent, the joint would be product p(x) p(y)p(x)\,p(y). Mutual information measures the distance (in the KL sense) between reality and that imagined world.

Summand i(x;y)=log⁡p(x,y)p(x)p(y)i(x; y) = \log\frac{p(x, y)}{p(x)p(y)} is pointwise mutual information (PMI): positive if pair (x,y)(x, y) occurs more often than under independence and negative if less. I(X;Y)I(X;Y) is its mean under pp. Individual terms may be negative; the mean, by Gibbs, is not (seen in lesson 2’s first figure and here again with table cells).

Proof

Since p(x,y)/(p(x)p(y))=p(x∣y)/p(x)p(x, y)/(p(x)p(y)) = p(x \mid y)/p(x) in every cell with mass,

I(X;Y)=E[log⁡p(X∣Y)]−E[log⁡p(X)]=−H(X∣Y)+H(X).I(X;Y) = \E\big[\log p(X \mid Y)\big] - \E\big[\log p(X)\big] = -H(X \mid Y) + H(X).

The ratio is also p(y∣x)/p(y)p(y \mid x)/p(y), and the same argument gives the second equality. For the third, log⁡p(x,y)p(x)p(y)=log⁡p(x,y)−log⁡p(x)−log⁡p(y)\log\frac{p(x,y)}{p(x)p(y)} = \log p(x, y) - \log p(x) - \log p(y) and taking expectation I(X;Y)=−H(X,Y)+H(X)+H(Y)I(X;Y) = -H(X, Y) + H(X) + H(Y). (With the entropy chain rule, H(X,Y)=H(X)+H(Y∣X)H(X,Y) = H(X) + H(Y \mid X), all three expressions agree.)

∎

The last formula has a concrete coding interpretation. Describing XX and YY separately costs H(X)+H(Y)H(X) + H(Y) bits on average; describing jointly costs only H(X,Y)H(X, Y). The difference, saved by exploiting dependence, is mutual information. The first formula reads as uncertainty reduction: uncertainty XX loses on learning YY. Shannon introduced it in 1948 in that spirit: channel transmission rate is R=H(x)−Hy(x)R = H(x) - H_y(x), input entropy minus its equivocation (uncertainty left after seeing output).

Proof

(1) The three formulas are symmetric or swap roles of XX and YY. (2) Gibbs’ inequality applied to pXYp_{XY} and pX⊗pYp_X \otimes p_Y: divergence is zero exactly when distributions coincide, i.e. p(x,y)=p(x)p(y)p(x,y) = p(x)p(y) for every pair (independence). (3) H(X∣X)=0H(X \mid X) = 0. (4) I(X;Y)=H(X)−H(X∣Y)≤H(X)I(X;Y) = H(X) - H(X \mid Y) \le H(X) because H(X∣Y)≥0H(X \mid Y) \ge 0, with equality exactly when H(X∣Y)=0H(X \mid Y) = 0, i.e. for each yy with p(y)>0p(y) > 0 distribution p(⋅∣y)p(\cdot \mid y) is degenerate: XX is determined by YY. Swap roles for H(Y)H(Y).

∎

A constantly used corollary resolves the motivating test paradox: observing a variable does not increase uncertainty about another on average.

The first statement rewrites I(X;Y)≥0I(X;Y) \ge 0. The second applies the chain rule H(X1,…,Xn)=∑iH(Xi∣X<i)H(X_1, \dots, X_n) = \sum_i H(X_i \mid X_{<i}) and the first to each term. The key words are “on average”: with H(X∣Y=+)=1>0.469=H(X)H(X \mid Y = +) = 1 > 0.469 = H(X) the positive test increases uncertainty. What always holds is ∑yp(y) H(X∣Y=y)≤H(X)\sum_y p(y)\,H(X \mid Y = y) \le H(X).

For any joint table the geometry is transparent. Draw circles for XX and YY with areas H(X)H(X) and H(Y)H(Y). If overlap has area I(X;Y)I(X;Y), the rest of the first is H(X∣Y)H(X \mid Y) and the rest of the second H(Y∣X)H(Y \mid X). With two variables, and only two, this picture is exact: the theorem’s three formulas read the same areas differently.

InteractiveLive information diagram
y1y2y3x10.33x20.32x30.35p(x)0.200.080.050.050.220.050.030.070.250.280.370.35p(y)1
XY1.23H(X|Y)0.35I(X;Y)1.22H(Y|X)area = bits: circles H(X), H(Y), overlap I(X;Y)
  • H(X∣Y)H(X\mid Y): what remains of XX after seeing YY
  • I(X;Y)I(X;Y): shared information
  • H(Y∣X)H(Y\mid X)
Cells show
H(X)H(X) (bits)1.584
H(Y)H(Y)1.575
H(X,Y)H(X,Y)2.805
H(X∣Y)H(X\mid Y)1.230
H(Y∣X)H(Y\mid X)1.221
H(X)−H(X∣Y)H(X) - H(X\mid Y)0.354
H(Y)−H(Y∣X)H(Y) - H(Y\mid X)0.354
H(X)+H(Y)−H(X,Y)H(X) + H(Y) - H(X,Y)0.354
KL⁡(pXY ∥ pXpY)\KL(p_{XY}\,\|\,p_X p_Y)0.354
Mutual information occupies 22% of the smaller circle. It reaches 100% only with Y=f(X)Y = f(X) or X=g(Y)X = g(Y).
A joint table 3×33 \times 3 edited by dragging each cell (others rescale). At right, circles with areas H(X)H(X) and H(Y)H(Y) whose overlap has exactly area I(X;Y)I(X;Y); crescents are H(X∣Y)H(X\mid Y) and H(Y∣X)H(Y\mid X). The four highlighted readings (three formulas and KL) agree. Try presets: with ‘independent’ circles touch without overlap; with noninjective Y=f(X)Y = f(X) the YY circle lies inside XX; with a bijection they coincide. Switch cells to ‘contribution to I’: blue adds, red subtracts. Can the total be negative?

What to take from the figure:

  1. Areas are exact. Overlap has area I(X;Y)I(X;Y) and circles H(X)H(X) and H(Y)H(Y), so circles cannot be “more inside” than information allows: I(X;Y)≤min⁡{H(X),H(Y)}I(X;Y) \le \min\{H(X), H(Y)\} expresses impossibility of a circle protruding beyond itself.
  2. Independence is tangency, determinism inclusion. With p(x,y)=p(x)p(y)p(x, y) = p(x)p(y) all contributions are zero and circles touch. With Y=f(X)Y = f(X) the YY circle is inside XX. Inclusion is asymmetric: knowing XX tells all about YY (H(Y∣X)=0H(Y \mid X) = 0), but knowing YY does not tell all about XX.
  3. Some cells subtract, but the total does not. Where p(x,y)>p(x)p(y)p(x, y) > p(x)p(y) the pair attracts and contributes positively; where p(x,y)<p(x)p(y)p(x,y) < p(x)p(y) it contributes negatively. Because marginals have the same sum, losses in some are more than compensated by others. Gibbs again, with a table.

Conditional mutual information and the chain rule

Usually the question is not how much YY says about XX in isolation, but how much beyond what you already know. If you have read ZZ, information contributed by YY is what remains after discounting what ZZ already said.

The three expressions agree by the same calculation as before, with p(x∣y,z)=p(x,y∣z)/p(y∣z)p(x \mid y, z) = p(x, y \mid z)/p(y \mid z). The last also proves nonnegativity: it averages KL divergences, one per value of zz, each ≥0\ge 0 by Gibbs; zero if and only if all are zero, i.e. p(x,y∣z)=p(x∣z)p(y∣z)p(x, y \mid z) = p(x \mid z)p(y \mid z) for every zz with mass. An often-used equivalent form is I(X;Y∣Z)=H(X,Z)+H(Y,Z)−H(Z)−H(X,Y,Z)I(X;Y \mid Z) = H(X, Z) + H(Y, Z) - H(Z) - H(X, Y, Z). An interpretation returning in graphical models: every conditional independence read from a graph (d-separation) is a statement like I(X;Y∣Z)=0I(X;Y \mid Z) = 0.

Information, like entropy, divides into an ordered sum of contributions.

Proof

Write I(X1:n;Y)=H(X1:n)−H(X1:n∣Y)I(X_{1:n}; Y) = H(X_{1:n}) - H(X_{1:n} \mid Y) and apply the entropy chain rule to each term, unconditional and conditioned on YY:

I(X1:n;Y)=∑i=1nH(Xi∣X<i)−∑i=1nH(Xi∣X<i,Y)=∑i=1nI(Xi;Y∣X<i).I(X_{1:n}; Y) = \sum_{i=1}^n H(X_i \mid X_{<i}) - \sum_{i=1}^n H(X_i \mid X_{<i}, Y) = \sum_{i=1}^n I(X_i; Y \mid X_{<i}). ∎

Read variables one by one: each XiX_i contributes about YY only what earlier ones did not already provide. Two consequences:

  • More variables do not remove information. Since each term is ≥0\ge 0, I(X,Z;Y)=I(Z;Y)+I(X;Y∣Z)≥I(Z;Y)I(X, Z; Y) = I(Z; Y) + I(X; Y \mid Z) \ge I(Z; Y): adding predictor variables cannot remove information about the target (whether the model can use it is another matter).
  • Summands depend on order, total does not. I(X1;Y)+I(X2;Y∣X1)=I(X2;Y)+I(X1;Y∣X2)I(X_1; Y) + I(X_2; Y \mid X_1) = I(X_2; Y) + I(X_1; Y \mid X_2). Each variable’s marginal contribution is not “its” contribution: dividing a total among variables depends on reading order. The same reason probability’s chain rule gives different factorizations under different orders.

An extreme case prepares the next section. Let X1,X2X_1, X_2 be independent uniform bits and Y=X1⊕X2Y = X_1 \oplus X_2 their sum modulo 2. Then I(X1;Y)=0I(X_1; Y) = 0 (parity of two uniform bits is a uniform bit independent of each separately) and I(X2;Y∣X1)=1I(X_2; Y \mid X_1) = 1 (if X1X_1 is already known, knowing X2X_2 determines YY). The chain rule gives I(X1,X2;Y)=0+1=1I(X_1, X_2; Y) = 0 + 1 = 1 bit: neither variable alone says anything about YY, and together they say everything.

Information diagrams and where they mislead

With two variables there are three regions, all easy to read. With three variables X,Y,ZX, Y, Z, the natural picture is three intersecting circles with seven regions. If circles have areas H(X)H(X), H(Y)H(Y), H(Z)H(Z), each region corresponds to an information quantity, and everyone draws this. The question is which quantity each region represents and whether all can be areas.

Proof

H(X∣Y,Z)=H(X,Y,Z)−H(Y,Z)H(X \mid Y, Z) = H(X, Y, Z) - H(Y, Z) and I(X;Y∣Z)=H(X,Z)+H(Y,Z)−H(Z)−H(X,Y,Z)I(X;Y \mid Z) = H(X, Z) + H(Y, Z) - H(Z) - H(X, Y, Z) are conditional entropy and conditional mutual information, both ≥0\ge 0. The center is as defined. And I(X;Y)=I(X;Y∣Z)+I(X;Y;Z)I(X;Y) = I(X;Y \mid Z) + I(X;Y;Z) rewrites the definition of I(X;Y;Z)I(X;Y;Z).

∎

Six of seven regions are always legitimate nonnegative areas. The seventh is not. This is not a technical defect but a phenomenon.

Conditioning on ZZ created dependence between XX and YY where none existed. Another view: I(X;Y;Z)<0I(X;Y;Z) < 0 means I(X,Y;Z)>I(X;Z)+I(Y;Z)I(X, Y; Z) > I(X; Z) + I(Y; Z): both variables together tell more about ZZ than their separate contributions sum to. This is synergy. When it is >0> 0 there is redundancy: what XX and YY tell about ZZ overlaps.

InteractiveSynergy: XOR breaks Venn diagrams
X,YX, Y are independent uniform bits and Z=X⊕YZ = X \oplus Y, flipped with probability ε\varepsilon.
XYZ0.00H(X|YZ)0.00H(Y|XZ)0.00H(Z|XY)1.00I(X;Y|Z)1.00I(X;Z|Y)1.00I(Y;Z|X)−1.00I(X;Y;Z)
Information about Z, in bits012I(X;Z)0.00I(Y;Z)0.00separately0.00I(X,Y;Z) together1.00I(X;Z|Y)1.00p(x, y, z)0.250000.000010.000100.250110.001000.251010.251100.00111
  • H(⋅∣rest)H(\cdot\mid\text{rest})
  • I(⋅ ;⋅∣rest)I(\cdot\,;\cdot\mid\text{rest})
  • I(X;Y;Z)≥0I(X;Y;Z) \ge 0
  • I(X;Y;Z)<0I(X;Y;Z) < 0 (synergy)
0.00
I(X;Y)I(X;Y) (bits)0.000
I(X;Z)I(X;Z)0.000
I(Y;Z)I(Y;Z)0.000
I(X,Y;Z)I(X,Y;Z)1.000
I(X;Z∣Y)I(X;Z\mid Y)1.000
I(X;Y;Z)I(X;Y;Z) = central region−1.000
The central region is I(X;Y;Z)=−1.00I(X;Y;Z) = −1.00 bits: negative. Together XX and YY reveal 1.00 bits more about ZZ than the sum of their separate contributions. Conditioning on ZZ creates dependence: I(X;Y)=0.00I(X;Y) = 0.00 but I(X;Y∣Z)=1.00I(X;Y\mid Z) = 1.00.
Four three-bit systems with adjustable noise ε\varepsilon. Left, seven information-diagram regions with values in bits (central region red when negative). Right, information about ZZ supplied by XX and YY separately, their sum and joint contribution, and probabilities of the eight outcomes (x,y,z)(x, y, z). Start with noiseless XOR: bars for XX and YY are 00 and together 11. Increase ε\varepsilon: how does synergy fade? Switch to ‘Chain’ and ‘Common cause’: what sign is the center now? With ‘AND’, how much synergy is there without noise?

What the figure shows:

  • Only the center changes sign. With XOR center is −1-1, surrounding three I(⋅ ;⋅∣⋅)I(\cdot\,;\cdot \mid \cdot) regions each 11 and outer three 00: the diagram remains coherent bookkeeping (each I(X;Y)I(X;Y) sums two regions, 1−1=01 - 1 = 0, and each H(X)H(X) four, 0+1+1−1=10 + 1 + 1 - 1 = 1), but not as areas.
  • A Markov chain and a common cause give center ≥0\ge 0. In X→Y→ZX \to Y \to Z and X←Z→YX \leftarrow Z \to Y conditional independence holds (X⊥ ⁣ ⁣ ⁣⊥Z∣YX \indep Z \mid Y and X⊥ ⁣ ⁣ ⁣⊥Y∣ZX \indep Y \mid Z respectively), so I(X;Z∣Y)=0I(X;Z \mid Y) = 0 or I(X;Y∣Z)=0I(X;Y \mid Z) = 0. The next section uses this rule.
  • Logical AND is a collider. With Z=X∧YZ = X \wedge Y both inputs are independent (I(X;Y)=0I(X;Y) = 0), but given Z=0Z = 0, knowing X=1X = 1 forces Y=0Y = 0: I(X;Y∣Z)=0.189I(X;Y \mid Z) = 0.189 bits and center −0.189-0.189. This is “explaining away” or selection bias: conditioning on a common consequence induces dependence between independent causes.

The three-circle diagram with areas proportional to information does not generally exist, because areas would be negative. Signed bookkeeping does exist: the diagram correctly remembers identities (Yeung’s I-measure is a signed measure with these regions as atoms), not actual areas. The mistake is treating it as a set Venn diagram.

Data processing

Any data pipeline transforms one variable into another: a quantizer, feature extractor, network layer. Can that transformation increase knowledge about a variable of interest? An emphatic no, provided the pipeline does not consult the source again.

The canonical example: Z=g(Y)Z = g(Y) with gg a deterministic or independently noisy function that reads only YY, not XX. If YY is a noisy function of XX and ZZ of YY, we have a Markov chain.

Proof

Expand I(X;Y,Z)I(X; Y, Z) both ways using the chain rule:

I(X;Y,Z)=I(X;Z)+I(X;Y∣Z)=I(X;Y)+I(X;Z∣Y).I(X; Y, Z) = I(X; Z) + I(X; Y \mid Z) = I(X; Y) + I(X; Z \mid Y).

By the Markov property I(X;Z∣Y)=0I(X; Z \mid Y) = 0. Thus I(X;Y)=I(X;Z)+I(X;Y∣Z)≥I(X;Z)I(X;Y) = I(X;Z) + I(X;Y \mid Z) \ge I(X;Z) because conditional information is nonnegative. Equality holds exactly when I(X;Y∣Z)=0I(X;Y \mid Z) = 0.

∎

Immediate uses:

  • If Z=g(Y)Z = g(Y) is a function of YY, I(X;g(Y))≤I(X;Y)I(X; g(Y)) \le I(X;Y): computation cannot increase information. In particular H(X∣g(Y))≥H(X∣Y)H(X \mid g(Y)) \ge H(X \mid Y).
  • If gg is injective (on the support of YY), YY is recovered from ZZ and therefore I(X;Y)=I(X;g(Y))I(X;Y) = I(X;g(Y)): relabeling, rescaling and any invertible coordinate change preserve information. Thus I(f(X);g(Y))=I(X;Y)I(f(X); g(Y)) = I(X;Y) for bijections f,gf, g, an invariance correlation lacks.
  • If ZZ comes from YY by adding noise independent of XX, I(X;Z)≤I(X;Y)I(X;Z) \le I(X;Y), with strict loss unless noise leaves what matters unaffected.
  • For models. Let YY be a label, XX input and hℓ(X)h_\ell(X) the activation of layer ℓ\ell. Since Y→X→h1→h2→⋯Y \to X \to h_1 \to h_2 \to \cdots is a Markov chain, I(Y;hℓ)≤I(Y;X)I(Y; h_\ell) \le I(Y; X) for every layer. No network, however deep, extracts more label information from input than the input contains.
InteractiveProcessing data creates no information
Xchannel from X to X3.00I(X;X)Y1channel from X to Y12.25I(X;Y1)Y2channel from X to Y21.44I(X;Y2)Y3channel from X to Y31.44I(X;Y3)noise−0.75group−0.81permute= 0
0.10
I(X;X)=H(X)I(X;X) = H(X) (bits)3.000
I(X;Y1)I(X;Y_1)2.250
I(X;Y2)I(X;Y_2)1.442
I(X;Y3)I(X;Y_3)1.442
Total loss1.558
I(X;Yk)I(X;Y_k) only decreases or stays equal. Stages 1 and 2 lose information; stage 3 tie. In total 1.56 of 3 bits are lost.
XX is uniform over 8 symbols (3 bits). Build a chain of up to three stages and see at each output YkY_k the channel matrix 8×88 \times 8 from XX to YkY_k (rows: XX value; columns: YkY_k value) and bar I(X;Yk)I(X; Y_k). Noise and quantization stages lose information; permutation is invertible and loses none. Press ‘Find a counterexample’: 3000 random channels, functions and permutations are tried on the last output to test whether any increases I(X;⋅)I(X;\cdot). Then change stage 2 to ‘look at X again’ and observe the bar and why the inequality no longer applies.

At initial values, noise with ε=0.1\varepsilon = 0.1 lowers information from 3 to 2.252.25 bits, grouping symbols in pairs takes it to 1.441.44, and final permutation leaves it unchanged. In the search no channel raises the bar: ties are those not confusing symbols distinguished by previous output (permutations and other injective functions on what remains), all others lower it. Only the cheating stage looking again at XX raises the bar: then output no longer depends solely on previous output and the theorem’s hypothesis fails. That is the meaning of “provided it is a Markov chain”: the inequality concerns one-way information flow, not arbitrary derived variables.

What the inequality does not say

Data processing concerns Shannon information, assuming a computationally unlimited decoder. It is therefore often misused. “Since I(Y;hℓ)≤I(Y;X)I(Y; h_\ell) \le I(Y; X), learned representations are useless” is wrong: a representation’s job is not to create information, but make it accessible to a limited decoder (linear layer, small tree). Two classic examples of processing helping limited resources:

  • Encryption. Ciphertext contains all plaintext information (a bijection with the key), but an adversary without the key cannot extract it. Decryption does not increase I(mensaje;⋅)I(\text{mensaje}; \cdot) yet makes unusable information usable.
  • Features. In XOR a linear classifier on (x1,x2)(x_1, x_2) cannot learn y=x1⊕x2y = x_1 \oplus x_2 (loss no better than chance), but adding feature x1x2x_1 x_2 lets it learn perfectly. Shannon information of yy about (x1,x2)(x_1, x_2) is 1 bit in both cases.

This is formalized as usable information (V\mathcal{V}-information; Xu et al., 2020): fix a decoder family V\mathcal{V} and define mutual information restricted to it, which can increase under processing. The data-processing proof does not apply because it uses optimal decoders.

[ ]Same Shannon information, different usable informationBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss

rng = np.random.default_rng(0)
n = 2000
X2 = rng.integers(0, 2, (n, 2))
y = X2[:, 0] ^ X2[:, 1]                                  # etiqueta: XOR de los dos bits

crudo = LogisticRegression().fit(X2, y)                   # decodificador lineal sobre (x1, x2)
con_producto = np.c_[X2, X2[:, 0] * X2[:, 1]]             # añade la característica x1 * x2
procesado = LogisticRegression(C=100).fit(con_producto, y)
for nombre, modelo, datos in [("(x1, x2)", crudo, X2), ("(x1, x2, x1 * x2)", procesado, con_producto)]:
    print(f"decodificador lineal sobre {nombre:18s} acierto = {modelo.score(datos, y):.3f}   "
          f"pérdida logarítmica = {log_loss(y, modelo.predict_proba(datos)):.3f} nats   (azar: {np.log(2):.3f})")
# el par (x1, x2) -> (x1, x2, x1 * x2) es inyectivo: la información de Shannon sobre y es la misma (1 bit)

With raw bits log loss is 0.6920.692 nats: chance (ln⁡2=0.693\ln 2 = 0.693). The model learned nothing, and accuracy 0.2690.269 is an artifact of ties at near-zero weights, not a signal. With the added feature accuracy is 1.01.0 and loss 0.0010.001. Processing created no information (all four pairs remain distinguishable and yy is their function) but made it usable by that decoder.

Sufficient statistics as lossless processing

A special equality case connects to statistics. In inference, θ\theta is the unknown parameter (with prior π\pi), XX the sample and T(X)T(X) a summary. By construction θ→X→T(X)\theta \to X \to T(X) is a Markov chain (the summary reads only the sample), so I(θ;T(X))≤I(θ;X)I(\theta; T(X)) \le I(\theta; X). When is equality attained?

Proof

Since TT is a function of XX, the chain rule gives I(θ;X,T(X))=I(θ;X)+I(θ;T∣X)=I(θ;X)I(\theta; X, T(X)) = I(\theta; X) + I(\theta; T \mid X) = I(\theta; X) (given XX, TT has no uncertainty). Meanwhile I(θ;X,T)=I(θ;T)+I(θ;X∣T)I(\theta; X, T) = I(\theta; T) + I(\theta; X \mid T). Hence

I(θ;X)−I(θ;T(X))=I(θ;X∣T(X)).I(\theta; X) - I(\theta; T(X)) = I(\theta; X \mid T(X)).

Sufficiency implies equality. By definition of sufficiency, conditional distribution p(x∣T(x)=t,θ)p(x \mid T(x) = t, \theta) does not depend on θ\theta (by the factorization theorem equivalent to p(x∣θ)=g(T(x),θ) h(x)p(x \mid \theta) = g(T(x), \theta)\,h(x)). This is X⊥ ⁣ ⁣ ⁣⊥θ∣TX \indep \theta \mid T, i.e. I(θ;X∣T)=0I(\theta; X \mid T) = 0 and by the identity above information agrees.

Equality implies sufficiency. If I(θ;T)=I(θ;X)I(\theta; T) = I(\theta; X), the identity gives I(θ;X∣T)=0I(\theta; X \mid T) = 0, meaning p(x∣t,θ)=p(x∣t)p(x \mid t, \theta) = p(x \mid t) for every θ\theta with π(θ)>0\pi(\theta) > 0; with full-support prior, every θ\theta. This is the definition of sufficiency.

∎

This is the information characterization: a statistic is sufficient if and only if it summarizes the sample without losing one bit about the parameter. The lowest-entropy sufficient statistic (minimal sufficient) is the best lossless compressor of what the sample says about θ\theta, an idea relaxed by the information bottleneck in lesson 19 to allow controlled losses.

A numerical example: θ∈{0.2,0.5,0.8}\theta \in \{0.2, 0.5, 0.8\} with uniform prior and XX three tosses of a coin of parameter θ\theta. Information in the full sample about θ\theta is I(θ;X)=0.4454I(\theta; X) = 0.4454 bits. The three-head count is sufficient and I(θ;suma)=0.4454I(\theta; \text{suma}) = 0.4454: not one bit less. The first toss alone retains 0.18540.1854 bits, first two 0.32880.3288, and majority vote (at least two heads?) 0.34560.3456: summaries discarding information. See implementation.

Fano’s inequality

So far we measured how much information exists. Now turn it into the question important to classification or estimation: given uncertainty remaining about XX after observing YY, how much error is inevitable, whatever the method?

Let XX take mm values (true class), YY be what is observed (data), and X^=g(Y)\hat X = g(Y) the decision of any deterministic or random estimator reading only YY. Then X→Y→X^X \to Y \to \hat X is a Markov chain. Error probability is Pe=P(X^≠X)P_e = \Pr(\hat X \ne X).

Proof

Let E=1[X^≠X]E = \ind[\hat X \ne X] be the error indicator, with P(E=1)=Pe\Pr(E = 1) = P_e. Expand H(E,X∣X^)H(E, X \mid \hat X) in two ways by the chain rule:

H(E,X∣X^)=H(X∣X^)+H(E∣X,X^)⏟= 0=H(E∣X^)+H(X∣E,X^).H(E, X \mid \hat X) = H(X \mid \hat X) + \underbrace{H(E \mid X, \hat X)}_{=\,0} = H(E \mid \hat X) + H(X \mid E, \hat X).

The first extra term is zero because EE is a function of (X,X^)(X, \hat X). Thus H(X∣X^)=H(E∣X^)+H(X∣E,X^)H(X \mid \hat X) = H(E \mid \hat X) + H(X \mid E, \hat X). Now bound the two summands:

  • H(E∣X^)≤H(E)=h(Pe)H(E \mid \hat X) \le H(E) = h(P_e), because conditioning reduces entropy.
  • H(X∣E,X^)=(1−Pe) H(X∣E=0,X^)+Pe H(X∣E=1,X^)H(X \mid E, \hat X) = (1 - P_e)\,H(X \mid E = 0, \hat X) + P_e\,H(X \mid E = 1, \hat X). If E=0E = 0 then X=X^X = \hat X and entropy is 0. If E=1E = 1, XX differs from known X^\hat X, so takes at most m−1m - 1 values with entropy ≤log⁡(m−1)\le \log(m - 1). Therefore H(X∣E,X^)≤Pelog⁡(m−1)H(X \mid E, \hat X) \le P_e \log(m - 1).

This proves H(X∣X^)≤h(Pe)+Pelog⁡(m−1)H(X \mid \hat X) \le h(P_e) + P_e \log(m - 1). The first inequality is data processing for X→Y→X^X \to Y \to \hat X: I(X;X^)≤I(X;Y)I(X; \hat X) \le I(X;Y), i.e. H(X)−H(X∣X^)≤H(X)−H(X∣Y)H(X) - H(X \mid \hat X) \le H(X) - H(X \mid Y). The weak version follows from h(Pe)≤1h(P_e) \le 1 and log⁡(m−1)≤log⁡m\log(m - 1) \le \log m.

∎

Read it as a lower bound on error of every estimator: whatever the classifier, network or human, if observations leave H(X∣Y)H(X \mid Y) bits of class uncertainty, error probability is at least the solution of h(Pe)+Pelog⁡(m−1)=H(X∣Y)h(P_e) + P_e \log(m - 1) = H(X \mid Y) (the left function increases from 0 to log⁡m\log m for Pe∈[0,m−1m]P_e \in [0, \tfrac{m-1}{m}], so inverts uniquely). The figure draws the curve from both ends.

InteractiveFano's bound
012300.250.50.751error probability PₑH(X | X̂) in bitslog₂ muniform randomforbidden by FanoH(X|Y) = 2.008 real classifiers (digits)
  • Fano curve F(Pe)=h(Pe)+Pelog⁡2(m−1)F(P_e) = h(P_e) + P_e \log_2(m-1)
  • feasible region with H(X∣Y)=hH(X\mid Y) = h
  • forbidden region
  • minimum error (exact Fano)
  • weak bound (h−1)/log⁡2m(h - 1)/\log_2 m
  • logistic regression
  • nearest neighbors
  • uniform random
10
2.00
log⁡2m\log_2 m (bits)3.322
H(X∣Y)H(X\mid Y)2.000
Pe≥P_e \ge (Fano)0.3394
Pe≥P_e \ge (weak version)0.3010
Maximum accuracy66.1 %
Uniform random: PeP_e0.9000
With m=10m = 10 classes and residual uncertainty H(X∣Y)=2.00H(X\mid Y) = 2.00 bits, no classifier based on YY can err less than 33.9%: maximum accuracy is 66.1%.
The (Pe,H)(P_e, H) plane with Fano curve F(Pe)=h(Pe)+Pelog⁡2(m−1)F(P_e) = h(P_e) + P_e\log_2(m-1). Above the curve (light red) no pair (error probability, conditional entropy H(X∣X^)H(X\mid\hat X)) can lie. The horizontal line is residual problem uncertainty H(X∣Y)H(X\mid Y) (drag it or use the control): it marks minimum error (dashed red line) and the green region containing classifiers for that problem. Points are real classifiers on the first mm handwritten digit classes. Hover: none touches the curve, and those below the line (faint) are incompatible with that residual uncertainty. Why is it so loose? Increase mm and observe inevitable error rise. Compare exact and weak bounds.

What to take away:

  • Inevitable error grows with mm and residual uncertainty. With m=10m = 10 equiprobable classes, if features leave H(X∣Y)=2H(X \mid Y) = 2 bits (contributing I(X;Y)=log⁡210−2=1.32I(X;Y) = \log_2 10 - 2 = 1.32 of the 3.323.32 bits needed), every classifier errs at least 33.9 %33.9\ \% of the time. The weak version gives 30.1 %30.1\ \% and the version replacing log⁡m\log m by log⁡(m−1)\log(m-1) gives 31.5 %31.5\ \%.
  • The bound is exact only for a symmetric channel. Equality requires H(E∣X^)=H(E)H(E \mid \hat X) = H(E) (error independent of the decision) and, on error, XX uniform among the remaining m−1m - 1 classes. Real classifiers mostly fail on a few specific confusions (similarly drawn digits), not equally across other classes, so H(X∣X^)H(X \mid \hat X) lies well below the curve. The inequality does not describe model error; it is a certificate about the problem: if H(X∣Y)H(X \mid Y) is large no model can fix it.
  • It is an ingredient of the channel-coding converse. Fano explains why transmission above capacity cannot have small error (lesson 10) and is a standard technique for minimax statistical lower bounds. Robert M. Fano published it in 1952 in MIT information-transmission course notes (the reference Cover and Thomas give).

Mutual information versus correlation

Mutual information is often viewed as “correlation not limited to straight lines”. The precise difference lies in a converse. If X⊥ ⁣ ⁣ ⁣⊥YX \indep Y then Cov⁡(X,Y)=0\operatorname{Cov}(X, Y) = 0 (zero correlation) and also I(X;Y)=0I(X;Y) = 0. But correlation’s converse fails while mutual information’s holds: I(X;Y)=0I(X;Y) = 0 if and only if X⊥ ⁣ ⁣ ⁣⊥YX \indep Y.

For jointly Gaussian variables both measures agree because I(X;Y)=−12log⁡(1−ρ2)I(X;Y) = -\tfrac12 \log(1 - \rho^2) increases with ∣ρ∣\abs{\rho} (from Gaussian differential entropy, lesson 11). But for a parabola, circle or wave correlation sees only linear projection while mutual information sees everything.

InteractiveWhat do correlation and mutual information see?
XYPearson r (−1 to 1)−101Estimated mutual information (bits)bias02.58 (maximum with 6×6 bins)
0.10
1500
Pearson rr−0.037
Spearman ρ\rho−0.058
I^\hat I plug-in (bits)0.946
Bias (shuffling YY)0.013
I^\hat I minus bias0.933
Correlation is nearly zero (r=−0.04r = −0.04), but estimated mutual information exceeds estimator bias by 0.93 bits: strong nonlinear dependence is invisible to rr.
A point cloud with adjustable dependence shape, noise and sample size. At right Pearson coefficient rr and mutual information estimated with a grid of 6×66 \times 6 equal-frequency bins, with a dashed estimator-bias mark (value obtained breaking dependence by shuffling YY). With parabola, circle, wave and cross, rr is almost 00 and mutual information large. With a line, both detect dependence. With independent variables the estimate is nonzero: lower sample size and watch bias rise. At what noise level is dependence lost?

Two cautions. Mutual information is not normalized (measured in bits and depends on variable entropies, unlike r∈[−1,1]r \in [-1, 1]), and estimation is hard: plug-in estimation of a table with KX×KYK_X \times K_Y bins and nn samples has upward bias around (KX−1)(KY−1)/(2nln⁡2)(K_X - 1)(K_Y - 1)/(2n \ln 2) bits even for independent variables (lesson 17). The figure therefore subtracts bias measured on shuffled data.

Implementation from scratch

First mutual information by all three formulas, the motivating diagnostic test, and verification that formulas agree on random tables.

[ ]Mutual information from tables and its three formulasBrowser
import numpy as np

def entropia(p):
    """Entropía en bits de un array de probabilidades (cualquier forma)."""
    p = np.asarray(p, dtype=float).ravel()
    p = p[p > 0]                                   # convención 0 log 0 = 0
    return float(-np.sum(p * np.log2(p)))

def info_mutua(pxy):
    """I(X;Y) en bits: KL entre la conjunta y el producto de las marginales."""
    pxy = np.asarray(pxy, dtype=float)
    prod = pxy.sum(axis=1, keepdims=True) * pxy.sum(axis=0, keepdims=True)
    s = pxy > 0                                    # solo cuentan las celdas con masa
    return float(np.sum(pxy[s] * np.log2(pxy[s] / prod[s])))

def tres_formas(pxy):
    pxy = np.asarray(pxy, dtype=float)
    hx, hy, hxy = entropia(pxy.sum(axis=1)), entropia(pxy.sum(axis=0)), entropia(pxy)
    return info_mutua(pxy), hx - (hxy - hy), hx + hy - hxy   # KL, H(X) - H(X|Y), H(X) + H(Y) - H(X,Y)

# 1) la tabla simétrica del ejercicio y el canal binario simétrico
pxy = np.array([[0.4, 0.1], [0.1, 0.4]])
print("tabla 2x2:", np.round(tres_formas(pxy), 6), "  1 - h(0.2) =", round(1 - entropia([0.2, 0.8]), 6))

# 2) el test diagnóstico: prevalencia 10 %, sensibilidad y especificidad 90 %
test = np.array([[0.9 * 0.9, 0.9 * 0.1], [0.1 * 0.1, 0.1 * 0.9]])   # filas: sano, enfermo; columnas: -, +
print("test: H(X) =", round(entropia(test.sum(axis=1)), 4), "  I(X;Y) =", round(info_mutua(test), 4))
for y, nombre in enumerate(["negativo", "positivo"]):
    post = test[:, y] / test[:, y].sum()
    print(f"  H(X | Y = {nombre}) = {entropia(post):.4f}   (P(Y = {nombre}) = {test[:, y].sum():.2f})")

# 3) las tres formas coinciden en tablas aleatorias, e I(X;X) = H(X)
rng = np.random.default_rng(0)
err = max(np.ptp(tres_formas(rng.dirichlet(np.ones(12)).reshape(4, 3))) for _ in range(1000))
print("diferencia máxima entre las tres formas en 1000 tablas 4x3:", f"{err:.1e}")
px = rng.dirichlet(np.ones(5))
print("I(X;X) =", round(info_mutua(np.diag(px)), 6), "  H(X) =", round(entropia(px), 6))

Information of the symmetric table is 1−h(0.2)=0.27811 - h(0.2) = 0.2781 bits, test 0.21110.2111, and positives leave 11 bit of uncertainty versus negatives’ 0.09500.0950. All three formulas agree up to rounding. Now the conditional version for three-dimensional tables, interaction information, chain rule and data processing on thousands of random Markov chains.

[ ]Conditional information, interaction, chain rule and data processingBrowser
import numpy as np

def info_mutua_cond(pxyz):
    """I(X;Y|Z) para una tabla con ejes (x, y, z): H(X,Z) + H(Y,Z) - H(Z) - H(X,Y,Z)."""
    p = np.asarray(pxyz, dtype=float)
    return entropia(p.sum(axis=1)) + entropia(p.sum(axis=0)) - entropia(p.sum(axis=(0, 1))) - entropia(p)

def interaccion(p):
    """I(X;Y;Z) = I(X;Y) - I(X;Y|Z)."""
    return info_mutua(p.sum(axis=2)) - info_mutua_cond(p)

# el XOR: X, Y bits uniformes independientes, Z = X xor Y
xor = np.zeros((2, 2, 2))
for x in (0, 1):
    for y in (0, 1):
        xor[x, y, x ^ y] = 0.25
print("XOR:  I(X;Z) =", round(info_mutua(xor.sum(axis=1)), 3),
      " I(X;Z|Y) =", round(info_mutua_cond(np.transpose(xor, (0, 2, 1))), 3),
      " I(X;Y;Z) =", round(interaccion(xor), 3))
andl = np.zeros((2, 2, 2))
for x in (0, 1):
    for y in (0, 1):
        andl[x, y, x & y] = 0.25
print("AND:  I(X;Y) =", round(info_mutua(andl.sum(axis=2)), 3),
      " I(X;Y|Z) =", round(info_mutua_cond(andl), 4), " I(X;Y;Z) =", round(interaccion(andl), 4))

rng = np.random.default_rng(1)

# regla de la cadena: I(X1,X2;Y) = I(X1;Y) + I(X2;Y|X1) en tablas aleatorias con ejes (x1, x2, y)
err = 0.0
for _ in range(500):
    p = rng.dirichlet(np.ones(24)).reshape(3, 4, 2)
    izq = info_mutua(p.reshape(12, 2))                                          # I((X1,X2); Y)
    der = info_mutua(p.sum(axis=1)) + info_mutua_cond(np.transpose(p, (1, 2, 0)))   # I(X1;Y) + I(X2;Y|X1)
    err = max(err, abs(izq - der))
print("regla de la cadena: error máximo =", f"{err:.1e}")

# procesamiento de datos con cadenas de Markov X -> Y -> Z aleatorias, y la identidad I(X;Y) - I(X;Z) = I(X;Y|Z)
peor, ident, n_malas = 1.0, 0.0, 0
for _ in range(2000):
    px = rng.dirichlet(np.ones(4))
    K1, K2 = rng.dirichlet(np.ones(4) * 0.4, 4), rng.dirichlet(np.ones(4) * 0.4, 4)   # filas: p(y|x), p(z|y)
    pxyz = px[:, None, None] * K1[:, :, None] * K2[None, :, :]
    huecos = info_mutua(pxyz.sum(axis=2)) - info_mutua(pxyz.sum(axis=1))
    peor = min(peor, huecos)
    n_malas += huecos < -1e-12
    ident = max(ident, abs(huecos - info_mutua_cond(pxyz)))
print(f"procesamiento: I(X;Z) > I(X;Y) en {n_malas} de 2000 cadenas; menor hueco I(X;Y) - I(X;Z) = {peor:.2e}")
print("identidad hueco = I(X;Y|Z): error máximo =", f"{ident:.1e}")

# igualdad con una permutación (canal invertible): el hueco es cero
perm = np.eye(4)[[2, 0, 3, 1]]
px, K1 = rng.dirichlet(np.ones(4)), rng.dirichlet(np.ones(4), 4)
pxy = px[:, None] * K1
print("con Z = permutación(Y): I(X;Y) =", round(info_mutua(pxy), 6), " I(X;Z) =", round(info_mutua(pxy @ perm), 6))

Two things to check in output. First XOR formulas: 00, 11 and −1-1 (and for AND 00, 0.18870.1887 and −0.1887-0.1887). Second, data-processing gap I(X;Y)−I(X;Z)I(X;Y) - I(X;Z) equals I(X;Y∣Z)I(X;Y \mid Z) in each chain as proved and is never negative. Now sufficient statistics and correlation versus mutual information with samples.

[ ]Sufficiency and correlation missing the parabolaBrowser
import itertools
import numpy as np

# θ en {0.2, 0.5, 0.8} con a priori uniforme y X = tres lanzamientos de una moneda de parámetro θ
thetas = np.array([0.2, 0.5, 0.8])
xs = list(itertools.product([0, 1], repeat=3))
J = np.array([[np.prod([t if b else 1 - t for b in x]) / 3 for x in xs] for t in thetas])   # p(θ, x)

def info_con_resumen(f):
    """I(θ; f(X)) en bits para una función f de las tres monedas."""
    valores = sorted({f(x) for x in xs})
    K = np.zeros((3, len(valores)))
    for j, x in enumerate(xs):
        K[:, valores.index(f(x))] += J[:, j]
    return info_mutua(K)

for nombre, f in [("muestra completa", lambda x: x), ("suma de caras (suficiente)", sum),
                  ("solo el primer lanzamiento", lambda x: x[0]), ("los dos primeros", lambda x: x[:2]),
                  ("mayoría de caras", lambda x: int(sum(x) >= 2))]:
    print(f"I(θ; {nombre:28s}) = {info_con_resumen(f):.4f} bits")

# Y = X^2 con X uniforme en {-2, ..., 2}: correlación nula, información mutua máxima
x = np.arange(-2, 3)
p = np.zeros((5, 3))
for i, v in enumerate(x):
    p[i, abs(v)] = 0.2
EX, EY = np.sum(0.2 * x), np.sum(0.2 * x**2)
print("\nY = X^2: Cov(X,Y) =", round(float(np.sum(0.2 * x * x**2) - EX * EY), 12),
      "  I(X;Y) =", round(info_mutua(p), 4), "  H(Y) =", round(entropia(p.sum(axis=0)), 4))

# con muestras continuas: rejilla de igual frecuencia y sesgo por barajado
def mi_plugin(a, b, bins=6):
    ra, rb = a.argsort().argsort(), b.argsort().argsort()
    ia, ib = np.minimum(ra * bins // len(a), bins - 1), np.minimum(rb * bins // len(b), bins - 1)
    tabla = np.zeros((bins, bins))
    np.add.at(tabla, (ia, ib), 1)
    return info_mutua(tabla / len(a))

rng = np.random.default_rng(2)
n = 1500
u = rng.uniform(-1, 1, n)
for nombre, v in [("parábola Y = X² + ruido", u**2 + 0.1 * rng.normal(size=n)), ("independiente", rng.uniform(-1, 1, n))]:
    sesgo = np.mean([mi_plugin(u, rng.permutation(v)) for _ in range(6)])
    print(f"{nombre:26s} r = {np.corrcoef(u, v)[0, 1]:+.3f}   Î = {mi_plugin(u, v):.3f}   sesgo = {sesgo:.3f} bits")

Summary information values are 0.44540.4454 (full sample and sum: identical), 0.18540.1854, 0.32880.3288 and 0.34560.3456. With Y=X2Y = X^2 on five values, correlation is zero and mutual information 1.5221.522 bits, equal to H(Y)H(Y). With continuous noisy parabola samples, r=0.048r = 0.048 but I^=1.003\hat I = 1.003 bits versus bias 0.0130.013; independent variables give r=0.026r = 0.026 and I^=0.013\hat I = 0.013, exactly the bias.

The library version

scikit-learn provides mutual_info_score (mutual information between discrete labelings, in nats) and mutual_info_classif (per feature, discrete or continuous with a nearest-neighbor estimator, also nats). Divide by ln⁡2\ln 2 for bits.

[ ]mutual_info_score, bias and feature selection with XORBrowser
import numpy as np
from sklearn.metrics import mutual_info_score
from sklearn.feature_selection import mutual_info_classif

rng = np.random.default_rng(1)
LN2 = np.log(2)

# muestras de una tabla conocida: el estimador converge a la información mutua exacta
pxy = np.array([[0.4, 0.1], [0.1, 0.4]])
celdas = rng.choice(4, size=20000, p=pxy.ravel())
a, b = celdas // 2, celdas % 2
print("mutual_info_score (nats):", round(mutual_info_score(a, b), 4), " en bits:", round(mutual_info_score(a, b) / LN2, 4),
      "  exacta:", round(info_mutua(pxy), 4))
cont = np.histogram2d(a, b, bins=2)[0]
print("desde la tabla de contingencia (bits):", round(mutual_info_score(None, None, contingency=cont) / LN2, 4))

# el sesgo del estimador plug-in: variables independientes con 10 categorías y n = 200
c, d = rng.integers(0, 10, 200), rng.integers(0, 10, 200)
print("independientes, n = 200: Î =", round(mutual_info_score(c, d) / LN2, 3), "bits;  sesgo teórico (K-1)²/(2 n ln 2) =",
      round(81 / (2 * 200 * LN2), 3))

# selección de variables: y = x1 xor x2, y una copia ruidosa x3 de y (20 % de errores)
n = 4000
x1, x2 = rng.integers(0, 2, n), rng.integers(0, 2, n)
y = x1 ^ x2
x3 = y ^ (rng.random(n) < 0.2).astype(int)
X = np.c_[x1, x2, x3]
puntuaciones = mutual_info_classif(X, y, discrete_features=True, random_state=0) / LN2
print("I(x_i; y) por característica:", np.round(puntuaciones, 3), "  (x1 y x2 parecen inútiles)")
print("I((x1, x2); y) con las dos a la vez:", round(mutual_info_score(2 * x1 + x2, y) / LN2, 3), "bits")

With discrete_features=True the estimator is plug-in and inherits bias (theoretical 0.2920.292 bits in the 10-category example and n=200n = 200). The univariate filter recognizes x3 (estimates 0.2850.285 bits; exact information of a channel with ε=0.2\varepsilon = 0.2 is 0.2780.278) and discards x1 and x2, which together completely determine yy.

Fano on a real classifier

Train logistic regression on scikit-learn’s digits dataset, half for training and half evaluation; the evaluation confusion matrix gives empirical joint distribution of (X,X^)(X, \hat X), yielding PeP_e and H(X∣X^)H(X \mid \hat X). Repeat with only three principal components as features for a much worse second classifier.

[ ]Fano inequality for a digit classifierBrowser
import numpy as np
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline

X, y = load_digits(return_X_y=True)
X = X / 16.0
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
m = 10

def h(p):
    return entropia([p, 1 - p])

def cota_fano(pe, m):
    return h(pe) + pe * np.log2(m - 1)

def error_minimo(H, m):
    """Menor P_e con h(P_e) + P_e log2(m-1) >= H, por bisección en la rama creciente [0, (m-1)/m]."""
    lo, hi = 0.0, (m - 1) / m
    for _ in range(60):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if cota_fano(mid, m) < H else (lo, mid)
    return hi

def evaluar(nombre, modelo):
    pred = modelo.fit(Xtr, ytr).predict(Xte)
    P = confusion_matrix(yte, pred, labels=range(m)).astype(float)
    P /= P.sum()                                      # conjunta empírica de (X, X̂)
    pe = 1 - np.trace(P)
    Hc = entropia(P) - entropia(P.sum(axis=0))          # H(X | X̂) = H(X, X̂) - H(X̂)
    print(f"{nombre:24s} Pe = {pe:.4f}   H(X|X̂) = {Hc:.4f}   F(Pe) = {cota_fano(pe, m):.4f}   "
          f"holgura = {cota_fano(pe, m) - Hc:.4f}   Pe mínimo dado H(X|X̂) = {error_minimo(Hc, m):.4f}")
    assert Hc <= cota_fano(pe, m) + 1e-12 and pe >= error_minimo(Hc, m) - 1e-9

evaluar("64 píxeles", LogisticRegression(max_iter=300))
evaluar("3 componentes", make_pipeline(PCA(3, random_state=0), LogisticRegression(max_iter=300)))
print("azar uniforme: Pe =", (m - 1) / m, "  H(X|X̂) = log2 10 =", round(np.log2(m), 4), " F = ", round(cota_fano((m - 1) / m, m), 4))

In both cases the inequality holds (the cell checks with assert). With 64 pixels, Pe=0.039P_e = 0.039 and H(X∣X^)=0.270H(X \mid \hat X) = 0.270 versus F(Pe)=0.361F(P_e) = 0.361; with 3 components, Pe=0.320P_e = 0.320 and H(X∣X^)=1.344H(X \mid \hat X) = 1.344 versus F(Pe)=1.920F(P_e) = 1.920. Fano’s minimum error given H(X∣X^)H(X \mid \hat X) is below actual error, with much greater slack for the worse classifier: real model errors are not spread equally among the other nine classes as needed for F(Pe)F(P_e) to be exact. The bound concerns H(X∣X^)H(X \mid \hat X), at least H(X∣Y)H(X \mid Y) (what truly matters and cannot be measured from data): Fano’s problem certificate is weaker still than shown here.

Common mistakes

Exercises

NumericThe first mutual information
Let X,YX, Y be bits with p(0,0)=p(1,1)=0.4p(0,0) = p(1,1) = 0.4 and p(0,1)=p(1,0)=0.1p(0,1) = p(1,0) = 0.1. Calculate I(X;Y)I(X;Y) in bits.
NumericThe unavoidable error
A classification problem has m=10m = 10 classes and, after observing features YY, residual class uncertainty is H(X∣Y)=2H(X \mid Y) = 2 bits. According to Fano's inequality (exact form, not weak), what is the minimum error probability of any classifier? (Solve h2(Pe)+Pelog⁡29=2h_2(P_e) + P_e \log_2 9 = 2 for Pe≤0.9P_e \le 0.9.)
NumericTwo channels in series
XX is a uniform bit. YY is XX flipped with probability 0.10.1 and ZZ is YY independently flipped with probability 0.10.1 (so X→Y→ZX \to Y \to Z). Calculate I(X;Z)I(X;Z) in bits.
ProofData processing with the chain rule
Prove: If X→Y→ZX \to Y \to Z is a Markov chain, then I(X;Z)≤I(X;Y)I(X;Z) \le I(X;Y), with equality if and only if I(X;Y∣Z)=0I(X;Y \mid Z) = 0.
0
Use the mutual-information chain rule and that Markov chain X→Y→ZX \to Y \to Z means I(X;Z∣Y)=0I(X;Z \mid Y) = 0.

Step 1 of 4. What quantity do you expand with the chain rule, and how?

ProofFano using the error indicator
Prove: Let XX have mm values and X→Y→X^X \to Y \to \hat X be a Markov chain with Pe=P(X^≠X)P_e = \Pr(\hat X \ne X). Then H(X∣Y)≤h(Pe)+Pelog⁡(m−1)H(X \mid Y) \le h(P_e) + P_e \log(m - 1).
0
Let E=1[X^≠X]E = \ind[\hat X \ne X]. The idea is to calculate H(E,X∣X^)H(E, X \mid \hat X) in two ways.

Step 1 of 4. How do you expand H(E,X∣X^)H(E, X \mid \hat X) with the entropy chain rule?

QuizThe XOR trio
Let X,YX, Y be independent uniform bits and Z=X⊕YZ = X \oplus Y. What values, in bits, do (I(X;Z),  I(X;Z∣Y),  I(X;Y;Z))\bigl(I(X;Z),\; I(X;Z \mid Y),\; I(X;Y;Z)\bigr) take?
CodeConditional mutual information for 3D tables
Implement conditional_mutual_information(pxyz) for a joint table pxyz (axes x, y, z, summing to 1) and return I(X;Y∣Z)I(X;Y \mid Z) in bits. Handle zero cells (convention 0log⁡0=00\log 0 = 0) and zz values with zero mass (ignored), without producing nan, and do not return negative rounding values exceeding 10−1210^{-12} in absolute magnitude.
import numpy as np

def entropia(p):
  p = np.asarray(p, dtype=float).ravel()
  p = p[p > 0]
  return float(-np.sum(p * np.log2(p)))

def conditional_mutual_information(pxyz):
  """I(X;Y|Z) en bits para una tabla con ejes (x, y, z)."""
  pxyz = np.asarray(pxyz, dtype=float)
  # tu código: por ejemplo, H(X,Z) + H(Y,Z) - H(Z) - H(X,Y,Z), o la media sobre z de las KL
  return 0.0
Shift+Enter to run
QuizCan a network create information?
A deep network receives input XX and produces layers h1(X),h2(h1),…h_1(X), h_2(h_1), \dots. Let YY be the label. What statement is correct?
QuizTrue or false, carefully
Which statements are true for discrete finite-alphabet variables?

More than one answer may be correct.

Summary

Key idea
Mutual information I(X;Y)=KL⁡(pXY ∥ pX⊗pY)=H(X)−H(X∣Y)I(X;Y) = \KL(p_{XY}\,\|\,p_X \otimes p_Y) = H(X) - H(X \mid Y) is mean uncertainty reduction about XX on learning YY. It is symmetric, never negative and zero only under independence. No processing (Markov chain) can increase it, and residual uncertainty H(X∣Y)H(X \mid Y) lower-bounds any estimator’s error.
  • Definition and formulas. I(X;Y)=∑p(x,y)log⁡p(x,y)p(x)p(y)=H(X)−H(X∣Y)=H(Y)−H(Y∣X)=H(X)+H(Y)−H(X,Y)I(X;Y) = \sum p(x,y)\log\frac{p(x,y)}{p(x)p(y)} = H(X) - H(X \mid Y) = H(Y) - H(Y \mid X) = H(X) + H(Y) - H(X,Y). Conditioning reduces entropy on average; a specific YY value can increase it.
  • Conditional and chain rule. I(X;Y∣Z)=H(X∣Z)−H(X∣Y,Z)≥0I(X;Y \mid Z) = H(X \mid Z) - H(X \mid Y,Z) \ge 0 and I(X1:n;Y)=∑iI(Xi;Y∣X<i)I(X_{1:n}; Y) = \sum_i I(X_i; Y \mid X_{<i}): each variable contributes what was not in earlier ones.
  • Information diagrams. Exact with two variables; with three, six regions are ≥0\ge 0 and center I(X;Y;Z)=I(X;Y)−I(X;Y∣Z)I(X;Y;Z) = I(X;Y) - I(X;Y \mid Z) can be negative (XOR, colliders: synergy, −1-1 bit in XOR). Pairwise dependence does not control joint dependence.
  • Data processing. If X→Y→ZX \to Y \to Z, I(X;Z)≤I(X;Y)I(X;Z) \le I(X;Y), equality if and only if I(X;Y∣Z)=0I(X;Y \mid Z) = 0 (permutations, sufficient statistics). A Markov chain is required. Shannon information cannot increase through processing; information usable by a limited decoder can.
  • Sufficiency. TT is sufficient if and only if I(θ;T(X))=I(θ;X)I(\theta; T(X)) = I(\theta; X): a lossless summary of what the sample says about the parameter.
  • Fano. For X→Y→X^X \to Y \to \hat X with mm classes, H(X∣Y)≤h(Pe)+Pelog⁡(m−1)H(X \mid Y) \le h(P_e) + P_e\log(m - 1), hence Pe≥(H(X∣Y)−1)/log⁡mP_e \ge (H(X \mid Y) - 1)/\log m. With m=10m = 10 and H(X∣Y)=2H(X \mid Y) = 2 bits, Pe≥0.339P_e \ge 0.339 for any model. It is exact only with errors uniform across other classes.
  • Versus correlation. I=0  ⟺  I = 0 \iff independence, while Cov⁡=0\operatorname{Cov} = 0 does not imply independence; Y=X2Y = X^2 with symmetric XX has correlation 00 and I=H(Y)=1.52I = H(Y) = 1.52 bits. The plug-in estimator has bias ≈(KX−1)(KY−1)/(2nln⁡2)\approx (K_X - 1)(K_Y - 1)/(2n\ln 2) bits.