Mutual Information for Feature Selection
Which features of a dataset are worth keeping? A feature is useful if it tells us something about the target, and mutual information measures exactly that, including nonlinear relationships that correlation misses. This lesson ranks features by mutual information, shows its blind spot (redundancy), and fixes it with a greedy criterion. The Feature Selection lesson shows the scikit-learn workflow.
Ranking by relevance
For a discrete feature, comes from a contingency table (Mutual Information). For continuous features, scikit-learn estimates it with nearest neighbours.
import numpy as np
from sklearn.feature_selection import mutual_info_regression, f_regression
rng = np.random.default_rng(0)
n = 2000
X = rng.uniform(-2, 2, (n, 4))
y = X[:, 0] + X[:, 1]**2 + 0.3 * rng.normal(size=n) # x0 linear, x1 quadratic, x2 and x3 irrelevant
mi = mutual_info_regression(X, y, random_state=0)
F, _ = f_regression(X, y)
for j in range(4):
print(f"x{j}: mutual information {mi[j]:.3f} nats linear F-statistic {F[j]:8.1f}")x0: mutual information 0.482 nats linear F-statistic 1927.7
x1: mutual information 0.427 nats linear F-statistic 1.9
x2: mutual information 0.026 nats linear F-statistic 0.2
x3: mutual information 0.002 nats linear F-statistic 0.1
The F-test, based on linear correlation, misses entirely, because is uncorrelated with on a symmetric range. Mutual information finds it.
Redundancy
Ranking by alone happily picks several copies of the same information. If and a noisy copy of it are both relevant, the second adds almost nothing once the first is chosen. What matters is the conditional mutual information .
Greedy selection with mRMR
The minimum-redundancy maximum-relevance (mRMR) heuristic picks features one at a time, scoring each candidate by relevance minus average redundancy with the features already chosen:
import numpy as np
from sklearn.metrics import mutual_info_score
def disc(v, bins=8):
return np.digitize(v, np.quantile(v, np.linspace(0, 1, bins + 1)[1:-1]))
rng = np.random.default_rng(1)
n = 5000
a = rng.normal(size=n); b = rng.normal(size=n)
X = np.column_stack([a, a + 0.1 * rng.normal(size=n), a + 0.2 * rng.normal(size=n), b, rng.normal(size=n)])
y = disc(a + 0.6 * b, 4)
names = ["a", "a copy 1", "a copy 2", "b", "noise"]
D = np.column_stack([disc(X[:, j]) for j in range(X.shape[1])])
rel = np.array([mutual_info_score(D[:, j], y) for j in range(X.shape[1])])
print("relevance ranking, top 3:", [names[j] for j in np.argsort(-rel)[:3]])
chosen = [int(np.argmax(rel))]
while len(chosen) < 3:
scores = {j: rel[j] - np.mean([mutual_info_score(D[:, j], D[:, k]) for k in chosen])
for j in range(X.shape[1]) if j not in chosen}
chosen.append(max(scores, key=scores.get))
print("mRMR selection, 3 picks: ", [names[j] for j in chosen])relevance ranking, top 3: ['a', 'a copy 1', 'a copy 2']
mRMR selection, 3 picks: ['a', 'b', 'noise']
Plain relevance ranking takes and two near-copies of it, so it misses . mRMR takes right after . Its third pick is the noise column: once and are in, no candidate adds information, and the least redundant one wins. Stop adding features when the best score drops close to zero.
Synergy: features that only help together
The opposite of redundancy also happens: (XOR). Each feature alone has zero mutual information with , but together they determine it. Greedy methods based on single-feature scores cannot see this (Mutual Information, exercise 2).
import numpy as np
from sklearn.metrics import mutual_info_score
rng = np.random.default_rng(2)
x1, x2 = rng.integers(0, 2, 10_000), rng.integers(0, 2, 10_000)
y = x1 ^ x2
pair = 2 * x1 + x2
for name, f in [("x1", x1), ("x2", x2), ("(x1, x2)", pair)]:
print(f"I({name}; y) = {mutual_info_score(f, y) / np.log(2):.4f} bits")I(x1; y) = 0.0000 bits
I(x2; y) = 0.0001 bits
I((x1, x2); y) = 0.9999 bits
In software
sklearn.feature_selection.mutual_info_classifandmutual_info_regressionestimate relevance for continuous and discrete features; combine withSelectKBest.- Estimates are noisy for small samples and depend on
n_neighbors; fixrandom_stateand compare features on the same footing. - Model-based importance (permutation importance, SHAP) captures interactions that pairwise mutual information misses, at a higher cost.
Exercises
Exercise 1: Correlation vs MI
is uniform on and . What is their correlation, and is their mutual information zero?
Answer
Correlation 0; mutual information positive.
Solution
By symmetry the covariance is zero, but is a function of , so they are strongly dependent.
Exercise 2: Duplicate features
You add an exact copy of the best feature. How do relevance ranking and mRMR treat it?
Answer
Ranking puts it second; mRMR gives it a low score.
Solution
Its relevance equals the original's, but its redundancy with the original is maximal, .
Exercise 3: Discrete MI (code)
For x = [0, 0, 1, 1, 2, 2, 0, 1] and y = [0, 0, 1, 1, 1, 1, 0, 1], compute in bits.
Answer
About 0.954 bits, all of .
Solution
import numpy as np
from sklearn.metrics import mutual_info_score
x = [0, 0, 1, 1, 2, 2, 0, 1]; y = [0, 0, 1, 1, 1, 1, 0, 1]
print(round(mutual_info_score(x, y) / np.log(2), 4))0.9544
is a function of ( exactly when ), so .
Test yourself
Why can mutual information find features that a linear F-test misses?
- It detects any statistical dependence, not just linear correlation
- It is faster
- It uses labels while the F-test does not
- It always returns larger numbers
What problem does mRMR address?
- Selecting several features that carry the same information
- Missing values
- Feature scaling
- Class imbalance
For Y = X1 XOR X2 with independent fair bits, is…
- 0
- 1 bit
- 0.5 bits
- 2 bits