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 saves you about :
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:
Properties
- Symmetric: .
- Non-negative, and zero exactly at independence: it is a KL divergence, so , with if and only if everywhere.
- Bounded: . Equality means is a function of .
- Self-information: .
- Invariant to relabelling: for one-to-one maps , . 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 is a Markov chain (for example is computed from alone), then . No transformation of a signal can create information about the target that the signal did not contain.
- Chain rule: . The second term is what adds once you already have , 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 up | Return down | |
|---|---|---|
| Signal up | 30 | 10 |
| Signal down | 20 | 40 |
Compute the mutual information between signal and next-day direction , treating these frequencies as the true probabilities.
Show solutionHide solution
Marginals. ; , so bit.
Conditional entropy. Given signal up, is up with probability ; given signal down, with probability :
Mutual information.
Check with the KL form. The cell contributes ; the other three contribute , and . The sum is .
For comparison, coding up as 1 and down as 0, the correlation (phi coefficient) is . 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:
So is only bits, is bits and is 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
is uniform on and . Compute and .
Show solutionHide solution
Correlation. and , so . The correlation is zero.
Mutual information. is a function of , so and . with probability and with probability , so
That is the maximum possible here, since . Knowing tells you exactly, yet a correlation screen would discard . 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 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:
It is biased upward. Sampling noise makes the empirical joint look slightly dependent even when and are independent, and always, so the errors cannot average out. Under independence, with and categories and observations,
(This is the G-test of independence.) The bias grows with the number of cells and shrinks only like :
| Bins per variable | Simulated mean , independent data | Formula | |
|---|---|---|---|
| 2 | 1000 | 0.00075 | 0.00072 |
| 10 | 1000 | 0.0594 | 0.0584 |
| 10 | 100 | 0.686 | 0.584 |
At 10 bins and 1,000 points, pure noise "shows" 0.06 bits, about as much as a Gaussian signal with carries ( 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 (the Miller–Madow correction applied to each entropy term gives the same thing).
- Better, build a null distribution by permutation: shuffle relative to many times, recompute , 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 -nearest-neighbour estimator (Kraskov–Stögbauer–Grassberger), which avoids binning; scikit-learn's
mutual_info_classifandmutual_info_regressionuse 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 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 minus its average MI with features already chosen, approximating the conditional term from the chain rule.
- Interactions: if (exclusive or) with fair independent bits, each feature alone has but the pair has 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 are fair and independent, and the target is (exclusive or). What are and ?
Key takeaways
- : symmetric, non-negative, zero exactly at independence.
- MI captures nonlinear dependence and is invariant to one-to-one transforms; for Gaussians , so small correlations mean very few bits.
- The plug-in estimator is biased upward by about 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).