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 be true status and the result. Before testing, uncertainty about is entropy bits, with the binary entropy function. And after?
- Positive result (occurs 18% of the time). By Bayes, . Uncertainty about is now bit: more than twice as high as before looking.
- Negative result (82%). and bits.
Mean remaining uncertainty is conditional entropy bits. The test reduced uncertainty on average by bits. This number is mutual information , 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 never worsens mean uncertainty. Second, 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 by 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 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 (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, is base-2 logarithm and information is in bits.
Definition and three ways to calculate it
Let be discrete random variables with finite alphabets, joint and marginals , . If and were independent, the joint would be product . Mutual information measures the distance (in the KL sense) between reality and that imagined world.
Summand is pointwise mutual information (PMI): positive if pair occurs more often than under independence and negative if less. is its mean under . 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 in every cell with mass,
The ratio is also , and the same argument gives the second equality. For the third, and taking expectation . (With the entropy chain rule, , all three expressions agree.)
∎The last formula has a concrete coding interpretation. Describing and separately costs bits on average; describing jointly costs only . The difference, saved by exploiting dependence, is mutual information. The first formula reads as uncertainty reduction: uncertainty loses on learning . Shannon introduced it in 1948 in that spirit: channel transmission rate is , input entropy minus its equivocation (uncertainty left after seeing output).
Proof
(1) The three formulas are symmetric or swap roles of and . (2) Gibbs’ inequality applied to and : divergence is zero exactly when distributions coincide, i.e. for every pair (independence). (3) . (4) because , with equality exactly when , i.e. for each with distribution is degenerate: is determined by . Swap roles for .
∎A constantly used corollary resolves the motivating test paradox: observing a variable does not increase uncertainty about another on average.
The first statement rewrites . The second applies the chain rule and the first to each term. The key words are “on average”: with the positive test increases uncertainty. What always holds is .
For any joint table the geometry is transparent. Draw circles for and with areas and . If overlap has area , the rest of the first is and the rest of the second . With two variables, and only two, this picture is exact: the theorem’s three formulas read the same areas differently.
What to take from the figure:
- Areas are exact. Overlap has area and circles and , so circles cannot be “more inside” than information allows: expresses impossibility of a circle protruding beyond itself.
- Independence is tangency, determinism inclusion. With all contributions are zero and circles touch. With the circle is inside . Inclusion is asymmetric: knowing tells all about (), but knowing does not tell all about .
- Some cells subtract, but the total does not. Where the pair attracts and contributes positively; where 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 says about in isolation, but how much beyond what you already know. If you have read , information contributed by is what remains after discounting what already said.
The three expressions agree by the same calculation as before, with . The last also proves nonnegativity: it averages KL divergences, one per value of , each by Gibbs; zero if and only if all are zero, i.e. for every with mass. An often-used equivalent form is . An interpretation returning in graphical models: every conditional independence read from a graph (d-separation) is a statement like .
Information, like entropy, divides into an ordered sum of contributions.
Proof
Write and apply the entropy chain rule to each term, unconditional and conditioned on :
∎Read variables one by one: each contributes about only what earlier ones did not already provide. Two consequences:
- More variables do not remove information. Since each term is , : 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. . 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 be independent uniform bits and their sum modulo 2. Then (parity of two uniform bits is a uniform bit independent of each separately) and (if is already known, knowing determines ). The chain rule gives bit: neither variable alone says anything about , 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 , the natural picture is three intersecting circles with seven regions. If circles have areas , , , 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
and are conditional entropy and conditional mutual information, both . The center is as defined. And rewrites the definition of .
∎Six of seven regions are always legitimate nonnegative areas. The seventh is not. This is not a technical defect but a phenomenon.
Conditioning on created dependence between and where none existed. Another view: means : both variables together tell more about than their separate contributions sum to. This is synergy. When it is there is redundancy: what and tell about overlaps.
What the figure shows:
- Only the center changes sign. With XOR center is , surrounding three regions each and outer three : the diagram remains coherent bookkeeping (each sums two regions, , and each four, ), but not as areas.
- A Markov chain and a common cause give center . In and conditional independence holds ( and respectively), so or . The next section uses this rule.
- Logical AND is a collider. With both inputs are independent (), but given , knowing forces : bits and center . 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: with a deterministic or independently noisy function that reads only , not . If is a noisy function of and of , we have a Markov chain.
Proof
Expand both ways using the chain rule:
By the Markov property . Thus because conditional information is nonnegative. Equality holds exactly when .
∎Immediate uses:
- If is a function of , : computation cannot increase information. In particular .
- If is injective (on the support of ), is recovered from and therefore : relabeling, rescaling and any invertible coordinate change preserve information. Thus for bijections , an invariance correlation lacks.
- If comes from by adding noise independent of , , with strict loss unless noise leaves what matters unaffected.
- For models. Let be a label, input and the activation of layer . Since is a Markov chain, for every layer. No network, however deep, extracts more label information from input than the input contains.
At initial values, noise with lowers information from 3 to bits, grouping symbols in pairs takes it to , 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 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 , 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 yet makes unusable information usable.
- Features. In XOR a linear classifier on cannot learn (loss no better than chance), but adding feature lets it learn perfectly. Shannon information of about is 1 bit in both cases.
This is formalized as usable information (-information; Xu et al., 2020): fix a decoder family and define mutual information restricted to it, which can increase under processing. The data-processing proof does not apply because it uses optimal decoders.
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 nats: chance (). The model learned nothing, and accuracy is an artifact of ties at near-zero weights, not a signal. With the added feature accuracy is and loss . Processing created no information (all four pairs remain distinguishable and is their function) but made it usable by that decoder.
Sufficient statistics as lossless processing
A special equality case connects to statistics. In inference, is the unknown parameter (with prior ), the sample and a summary. By construction is a Markov chain (the summary reads only the sample), so . When is equality attained?
Proof
Since is a function of , the chain rule gives (given , has no uncertainty). Meanwhile . Hence
Sufficiency implies equality. By definition of sufficiency, conditional distribution does not depend on (by the factorization theorem equivalent to ). This is , i.e. and by the identity above information agrees.
Equality implies sufficiency. If , the identity gives , meaning for every with ; with full-support prior, every . 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 , an idea relaxed by the information bottleneck in lesson 19 to allow controlled losses.
A numerical example: with uniform prior and three tosses of a coin of parameter . Information in the full sample about is bits. The three-head count is sufficient and : not one bit less. The first toss alone retains bits, first two , and majority vote (at least two heads?) : 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 after observing , how much error is inevitable, whatever the method?
Let take values (true class), be what is observed (data), and the decision of any deterministic or random estimator reading only . Then is a Markov chain. Error probability is .
Proof
Let be the error indicator, with . Expand in two ways by the chain rule:
The first extra term is zero because is a function of . Thus . Now bound the two summands:
- , because conditioning reduces entropy.
- . If then and entropy is 0. If , differs from known , so takes at most values with entropy . Therefore .
This proves . The first inequality is data processing for : , i.e. . The weak version follows from and .
∎Read it as a lower bound on error of every estimator: whatever the classifier, network or human, if observations leave bits of class uncertainty, error probability is at least the solution of (the left function increases from 0 to for , so inverts uniquely). The figure draws the curve from both ends.
What to take away:
- Inevitable error grows with and residual uncertainty. With equiprobable classes, if features leave bits (contributing of the bits needed), every classifier errs at least of the time. The weak version gives and the version replacing by gives .
- The bound is exact only for a symmetric channel. Equality requires (error independent of the decision) and, on error, uniform among the remaining classes. Real classifiers mostly fail on a few specific confusions (similarly drawn digits), not equally across other classes, so lies well below the curve. The inequality does not describe model error; it is a certificate about the problem: if 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 then (zero correlation) and also . But correlation’s converse fails while mutual information’s holds: if and only if .
For jointly Gaussian variables both measures agree because increases with (from Gaussian differential entropy, lesson 11). But for a parabola, circle or wave correlation sees only linear projection while mutual information sees everything.
Two cautions. Mutual information is not normalized (measured in bits and depends on variable entropies, unlike ), and estimation is hard: plug-in estimation of a table with bins and samples has upward bias around 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.
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 bits, test , and positives leave bit of uncertainty versus negatives’ . 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.
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: , and (and for AND , and ). Second, data-processing gap equals in each chain as proved and is never negative. Now sufficient statistics and correlation versus mutual information with samples.
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 (full sample and sum: identical), , and . With on five values, correlation is zero and mutual information bits, equal to . With continuous noisy parabola samples, but bits versus bias ; independent variables give and , 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 for bits.
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 bits in the 10-category example and ). The univariate filter recognizes x3 (estimates bits; exact information of a channel with is ) and discards x1 and x2, which together completely determine .
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 , yielding and . Repeat with only three principal components as features for a much worse second classifier.
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, and versus ; with 3 components, and versus . Fano’s minimum error given 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 to be exact. The bound concerns , at least (what truly matters and cannot be measured from data): Fano’s problem certificate is weaker still than shown here.
Common mistakes
Exercises
Step 1 of 4. What quantity do you expand with the chain rule, and how?
Step 1 of 4. How do you expand with the entropy chain rule?
conditional_mutual_information(pxyz) for a joint table pxyz (axes x, y, z, summing to 1) and return in bits. Handle zero cells (convention ) and values with zero mass (ignored), without producing nan, and do not return negative rounding values exceeding 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.0More than one answer may be correct.
Summary
- Definition and formulas. . Conditioning reduces entropy on average; a specific value can increase it.
- Conditional and chain rule. and : each variable contributes what was not in earlier ones.
- Information diagrams. Exact with two variables; with three, six regions are and center can be negative (XOR, colliders: synergy, bit in XOR). Pairwise dependence does not control joint dependence.
- Data processing. If , , equality if and only if (permutations, sufficient statistics). A Markov chain is required. Shannon information cannot increase through processing; information usable by a limited decoder can.
- Sufficiency. is sufficient if and only if : a lossless summary of what the sample says about the parameter.
- Fano. For with classes, , hence . With and bits, for any model. It is exact only with errors uniform across other classes.
- Versus correlation. independence, while does not imply independence; with symmetric has correlation and bits. The plug-in estimator has bias bits.