TExcelTAD
Home › Information Theory › Mutual Information for Feature Selection

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, I(Xj;Y)I(X_j; Y) comes from a contingency table (Mutual Information). For continuous features, scikit-learn estimates it with nearest neighbours.

python · try it yourself
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 x1x_1 entirely, because x12x_1^2 is uncorrelated with x1x_1 on a symmetric range. Mutual information finds it.

Redundancy

Ranking by I(Xj;Y)I(X_j; Y) alone happily picks several copies of the same information. If x0x_0 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 I(Xj;Y∣Xselected)I(X_j; Y \mid X_{\text{selected}}).

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:

score(j)=I(Xj;Y)−1∣S∣∑k∈SI(Xj;Xk)\text{score}(j) = I(X_j; Y) - \frac{1}{|S|}\sum_{k \in S} I(X_j; X_k)
python · try it yourself
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 aa and two near-copies of it, so it misses bb. mRMR takes bb right after aa. Its third pick is the noise column: once aa and bb 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: Y=X1⊕X2Y = X_1 \oplus X_2 (XOR). Each feature alone has zero mutual information with YY, but together they determine it. Greedy methods based on single-feature scores cannot see this (Mutual Information, exercise 2).

python · try it yourself
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_classif and mutual_info_regression estimate relevance for continuous and discrete features; combine with SelectKBest.
  • Estimates are noisy for small samples and depend on n_neighbors; fix random_state and 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

XX is uniform on [−1,1][-1, 1] and Y=∣X∣Y = |X|. What is their correlation, and is their mutual information zero?

Answer

Correlation 0; mutual information positive.

Solution

By symmetry the covariance is zero, but YY is a function of XX, 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, I(X;X)=H(X)I(X; X) = H(X).

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 I(X;Y)I(X; Y) in bits.

Answer

About 0.954 bits, all of H(Y)H(Y).

Solution
python · try it yourself
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

YY is a function of XX (Y=0Y = 0 exactly when X=0X = 0), so I(X;Y)=H(Y)=H2(38)I(X; Y) = H(Y) = H_2(\frac{3}{8}).

Test yourself

Why can mutual information find features that a linear F-test misses?

  1. It detects any statistical dependence, not just linear correlation
  2. It is faster
  3. It uses labels while the F-test does not
  4. It always returns larger numbers

What problem does mRMR address?

  1. Selecting several features that carry the same information
  2. Missing values
  3. Feature scaling
  4. Class imbalance

For Y = X1 XOR X2 with independent fair bits, I(X1;Y)I(X_1; Y) is…

  1. 0
  2. 1 bit
  3. 0.5 bits
  4. 2 bits