Skip to content
LeetQuant
E03 Information Theory

E03 · Information Theory · Lesson 2 of 4

Mutual Information

Mutual information as the reduction in uncertainty one variable gives about another: its properties, why it detects nonlinear dependence that correlation misses, how badly the plug-in estimator is biased, and how to use it to rank features.

17 min

Objective

Be able to compute mutual information from a contingency table, explain how it differs from correlation, estimate it from data without fooling yourself, and use it to screen features.

Definition

Mutual information is how many bits knowing YY saves you about XX:

I(X;Y)=H(X)−H(X∣Y)=H(Y)−H(Y∣X)=H(X)+H(Y)−H(X,Y).I(X; Y) = H(X) - H(X \mid Y) = H(Y) - H(Y \mid X) = H(X) + H(Y) - H(X, Y).

Equivalently, it is the KL divergence between the joint distribution and the product of the marginals, which is what the joint would be under independence:

I(X;Y)=D(p(x,y) ∥ p(x)p(y))=∑x,yp(x,y)log⁡2p(x,y)p(x) p(y).I(X; Y) = D\big(p(x, y) \,\big\|\, p(x)p(y)\big) = \sum_{x, y} p(x, y)\log_2\frac{p(x, y)}{p(x)\,p(y)} .

Properties

  • Symmetric: I(X;Y)=I(Y;X)I(X; Y) = I(Y; X).
  • Non-negative, and zero exactly at independence: it is a KL divergence, so I≥0I \ge 0, with I=0I = 0 if and only if p(x,y)=p(x)p(y)p(x, y) = p(x)p(y) everywhere.
  • Bounded: I(X;Y)≤min⁡(H(X),H(Y))I(X; Y) \le \min(H(X), H(Y)). Equality I=H(Y)I = H(Y) means YY is a function of XX.
  • Self-information: I(X;X)=H(X)I(X; X) = H(X).
  • Invariant to relabelling: for one-to-one maps f,gf, g, I(f(X);g(Y))=I(X;Y)I(f(X); g(Y)) = I(X; Y). Taking logs, ranks or any monotone transform of a feature leaves its MI with the target unchanged. Pearson correlation does not have this property.
  • Data processing inequality: if X→Y→ZX \to Y \to Z is a Markov chain (for example ZZ is computed from YY alone), then I(X;Z)≤I(X;Y)I(X; Z) \le I(X; Y). No transformation of a signal can create information about the target that the signal did not contain.
  • Chain rule: I(X;Y,Z)=I(X;Y)+I(X;Z∣Y)I(X; Y, Z) = I(X; Y) + I(X; Z \mid Y). The second term is what ZZ adds once you already have YY, the quantity that matters when choosing a second feature.

Worked example

MI from a contingency table

Over 100 days a signal said "up" on 40 days and "down" on 60. The next-day return was:

Return upReturn down
Signal up3010
Signal down2040

Compute the mutual information between signal XX and next-day direction YY, treating these frequencies as the true probabilities.

Show solution

Marginals. P(X=up)=0.4P(X = \text{up}) = 0.4; P(Y=up)=(30+20)/100=0.5P(Y = \text{up}) = (30 + 20)/100 = 0.5, so H(Y)=1H(Y) = 1 bit.

Conditional entropy. Given signal up, YY is up with probability 30/40=0.7530/40 = 0.75; given signal down, with probability 20/60=1320/60 = \tfrac13:

H(Y∣X)=0.4 h(0.75)+0.6 h(13)=0.4(0.8113)+0.6(0.9183)≈0.8755.H(Y \mid X) = 0.4\, h(0.75) + 0.6\, h(\tfrac13) = 0.4(0.8113) + 0.6(0.9183) \approx 0.8755 .

Mutual information.

I(X;Y)=H(Y)−H(Y∣X)≈1−0.8755=0.1245 bits.I(X; Y) = H(Y) - H(Y \mid X) \approx 1 - 0.8755 = 0.1245 \text{ bits}.

Check with the KL form. The cell (up,up)(\text{up}, \text{up}) contributes 0.30log⁡20.300.4×0.5=0.30log⁡21.5≈0.17550.30\log_2\frac{0.30}{0.4 \times 0.5} = 0.30\log_2 1.5 \approx 0.1755; the other three contribute 0.10log⁡20.5=−0.10.10\log_2 0.5 = -0.1, 0.20log⁡20.200.30≈−0.11700.20\log_2\frac{0.20}{0.30} \approx -0.1170 and 0.40log⁡20.400.30≈0.16600.40\log_2\frac{0.40}{0.30} \approx 0.1660. The sum is 0.12450.1245.

For comparison, coding up as 1 and down as 0, the correlation (phi coefficient) is 0.30−0.4×0.50.4⋅0.6⋅0.5⋅0.5≈0.408\frac{0.30 - 0.4 \times 0.5}{\sqrt{0.4 \cdot 0.6 \cdot 0.5 \cdot 0.5}} \approx 0.408. For two binary variables MI and correlation carry the same information; the difference shows up with more values, as the next example shows.

MI versus correlation

Correlation measures linear association. Mutual information measures any departure from independence.

For jointly Gaussian variables there is a direct translation:

I(X;Y)=−12log⁡2(1−ρ2).I(X; Y) = -\tfrac12\log_2(1 - \rho^2) .

So ρ=0.1\rho = 0.1 is only 0.00720.0072 bits, ρ=0.5\rho = 0.5 is 0.20750.2075 bits and ρ=0.9\rho = 0.9 is 1.1981.198 bits. The weak correlations typical of return prediction carry tiny amounts of information per observation, which is why they need many observations to exploit.

Outside the Gaussian world the two can disagree completely.

Worked example

zero correlation, lots of information

XX is uniform on {−1,0,1}\{-1, 0, 1\} and Y=X2Y = X^2. Compute Corr(X,Y)\text{Corr}(X, Y) and I(X;Y)I(X; Y).

Show solution

Correlation. E[X]=0E[X] = 0 and E[XY]=E[X3]=13(−1+0+1)=0E[XY] = E[X^3] = \tfrac13(-1 + 0 + 1) = 0, so Cov(X,Y)=E[XY]−E[X]E[Y]=0\text{Cov}(X, Y) = E[XY] - E[X]E[Y] = 0. The correlation is zero.

Mutual information. YY is a function of XX, so H(Y∣X)=0H(Y \mid X) = 0 and I(X;Y)=H(Y)I(X; Y) = H(Y). Y=1Y = 1 with probability 23\tfrac23 and Y=0Y = 0 with probability 13\tfrac13, so

I(X;Y)=h(13)≈0.918 bits.I(X; Y) = h(\tfrac13) \approx 0.918 \text{ bits}.

That is the maximum possible here, since I≤H(Y)I \le H(Y). Knowing XX tells you YY exactly, yet a correlation screen would discard XX. In markets, the analogue is a feature that predicts the size of the next move but not its sign, such as a volatility signal against returns: zero correlation with the return, plenty of information about ∣r∣|r| and about the return's distribution.

Estimating MI from data

For discrete data (or continuous data cut into bins) the plug-in estimator replaces probabilities with frequencies:

I^=∑x,yp^(x,y)log⁡2p^(x,y)p^(x) p^(y).\hat I = \sum_{x, y}\hat p(x, y)\log_2\frac{\hat p(x, y)}{\hat p(x)\,\hat p(y)} .

It is biased upward. Sampling noise makes the empirical joint look slightly dependent even when XX and YY are independent, and I^≥0\hat I \ge 0 always, so the errors cannot average out. Under independence, with KXK_X and KYK_Y categories and NN observations,

2Nln⁡2⋅I^  ≈  χ(KX−1)(KY−1)2,E[I^]≈(KX−1)(KY−1)2Nln⁡2 bits.2N\ln 2 \cdot \hat I \;\approx\; \chi^2_{(K_X - 1)(K_Y - 1)}, \qquad E[\hat I] \approx \frac{(K_X - 1)(K_Y - 1)}{2N\ln 2} \text{ bits}.

(This is the G-test of independence.) The bias grows with the number of cells and shrinks only like 1/N1/N:

Bins per variableNNSimulated mean I^\hat I, independent dataFormula
210000.000750.00072
1010000.05940.0584
101000.6860.584

At 10 bins and 1,000 points, pure noise "shows" 0.06 bits, about as much as a Gaussian signal with ρ=0.28\rho = 0.28 carries (0.0590.059 bits). At 100 points the 100 cells are barely populated, the estimate is huge and the asymptotic formula itself breaks down.

What to do about it

  • Use few bins, and equal-count (quantile) bins so that each cell is populated.
  • Subtract the bias (KX−1)(KY−1)/(2Nln⁡2)(K_X - 1)(K_Y - 1)/(2N\ln 2) (the Miller–Madow correction applied to each entropy term gives the same thing).
  • Better, build a null distribution by permutation: shuffle YY relative to XX many times, recompute I^\hat I, and report how far the real value sits above the shuffled ones. This handles small samples and any binning choice.
  • For continuous variables, use a kk-nearest-neighbour estimator (Kraskov–Stögbauer–Grassberger), which avoids binning; scikit-learn's mutual_info_classif and mutual_info_regression use this approach and report nats.
  • Remember that time-series observations are not independent. Overlapping returns or persistent features shrink the effective sample size, which inflates the bias and invalidates naive permutation; permute in blocks.

MI for feature ranking

A filter-style feature screen scores each candidate feature by I^(feature;target)\hat I(\text{feature}; \text{target}) and keeps the top ones. Its advantages over correlation are that it sees nonlinear and non-monotone effects and is unaffected by monotone transforms. The code below, which uses only the standard library, builds a target that depends linearly on one feature and on the absolute value of another, and compares the two screens.

import random
from collections import Counter
from math import log, log2

def quantile_bins(v, k):
    """Map each value to one of k equal-count bins (0..k-1)."""
    order = sorted(range(len(v)), key=v.__getitem__)
    b = [0] * len(v)
    for rank, i in enumerate(order):
        b[i] = rank * k // len(v)
    return b

def mutual_info(xs, ys):
    """Plug-in MI in bits for two discrete sequences."""
    n = len(xs)
    cxy, cx, cy = Counter(zip(xs, ys)), Counter(xs), Counter(ys)
    return sum(c / n * log2(c * n / (cx[x] * cy[y])) for (x, y), c in cxy.items())

def corr(a, b):
    n = len(a)
    ma, mb = sum(a) / n, sum(b) / n
    cov = sum((x - ma) * (y - mb) for x, y in zip(a, b))
    va = sum((x - ma) ** 2 for x in a)
    vb = sum((y - mb) ** 2 for y in b)
    return cov / (va * vb) ** 0.5

random.seed(3)
n = 5000
f_lin = [random.gauss(0, 1) for _ in range(n)]
f_abs = [random.gauss(0, 1) for _ in range(n)]
f_noise = [random.gauss(0, 1) for _ in range(n)]
# Target is up (1) or down (0); it depends linearly on f_lin and on |f_abs|.
y = [int(0.5 * a + (abs(b) - 0.8) + random.gauss(0, 1) > 0)
     for a, b in zip(f_lin, f_abs)]

for name, f in [("f_lin", f_lin), ("f_abs", f_abs), ("f_noise", f_noise)]:
    mi = mutual_info(quantile_bins(f, 10), y)
    print(f"{name:8s} corr={corr(f, y):+.3f}  MI={mi:.4f} bits")
print(f"bias guide (Kx-1)(Ky-1)/(2N ln 2) = {9 / (2 * n * log(2)):.4f} bits")

Output:

f_lin    corr=+0.299  MI=0.0667 bits
f_abs    corr=+0.014  MI=0.1050 bits
f_noise  corr=-0.020  MI=0.0014 bits
bias guide (Kx-1)(Ky-1)/(2N ln 2) = 0.0013 bits

Correlation ranks f_abs alongside pure noise; MI ranks it first. The noise feature's MI sits at the bias level, which is what "no information" looks like for a plug-in estimate.

Limitations of univariate MI ranking

  • Redundancy: two copies of the same feature both score highly. Greedy schemes such as mRMR (maximum relevance, minimum redundancy) pick the next feature by I^(f;y)\hat I(f; y) minus its average MI with features already chosen, approximating the conditional term I(f;y∣chosen)I(f; y \mid \text{chosen}) from the chain rule.
  • Interactions: if y=x1⊕x2y = x_1 \oplus x_2 (exclusive or) with fair independent bits, each feature alone has I=0I = 0 but the pair has I(x1,x2;y)=1I(x_1, x_2; y) = 1 bit. Univariate screens miss this entirely.
  • No direction or size: MI says a relationship exists, not whether it is tradable, monotone or stable over time. It is a screen, not a model.

Knowledge check

Which statement is true for discrete random variables X and Y?

Knowledge check

Two independent features are each cut into 20 quantile bins and you compute the plug-in MI between them from N = 2,000 observations. Roughly what value do you expect?

Knowledge check

Two bits x1,x2x_1, x_2 are fair and independent, and the target is y=x1⊕x2y = x_1 \oplus x_2 (exclusive or). What are I(x1;y)I(x_1; y) and I(x1,x2;y)I(x_1, x_2; y)?

Key takeaways

  • I(X;Y)=H(Y)−H(Y∣X)=D(pXY ∥ pXpY)I(X; Y) = H(Y) - H(Y \mid X) = D(p_{XY} \,\|\, p_X p_Y): symmetric, non-negative, zero exactly at independence.
  • MI captures nonlinear dependence and is invariant to one-to-one transforms; for Gaussians I=−12log⁡2(1−ρ2)I = -\tfrac12\log_2(1 - \rho^2), so small correlations mean very few bits.
  • The plug-in estimator is biased upward by about (KX−1)(KY−1)/(2Nln⁡2)(K_X - 1)(K_Y - 1)/(2N\ln 2) bits under independence; use few quantile bins, bias correction and permutation nulls.
  • For feature selection MI is a good first screen, but it ignores redundancy and interactions; use conditional MI or greedy schemes like mRMR for those.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).