The Math Behind the Methods

Mutual Information as a Tool for Feature and Representation Analysis

Learn what mutual information measures, compute it from a table, use it to screen features, and avoid its estimation traps.

Key takeaways

  • Mutual information I(X; Y) equals the entropy of Y minus the entropy of Y once X is known.
  • It is zero if and only if X and Y are independent, and it is symmetric in the two variables.
  • It detects nonlinear dependence that correlation misses, but it says nothing about direction or cause.
  • A feature can be useless alone and highly informative in combination with another.
  • Sample estimates tend to be biased and sensitive to settings, so compare them against a shuffled baseline.

Mutual information measures how much knowing one variable reduces your uncertainty about another. It is zero exactly when the two are independent, and it picks up any kind of dependence, not just straight-line trends.

That makes it attractive for screening features and for asking what a learned representation retains. The difficulty is that it is easy to define and often hard to estimate from a finite sample.

Three equivalent definitions

Start with entropy, H(Y) = −∑ p(y) log p(y), the average uncertainty about Y. The conditional entropy H(Y | X) is the uncertainty that remains after seeing X, averaged over the values of X.

I(X; Y) = H(Y) − H(Y | X)
        = H(X) + H(Y) − H(X, Y)
        = KL( p(x, y) ‖ p(x) p(y) )

The last form says that mutual information is the KL divergence from the independent version of the world to the actual joint distribution. With base 2 logarithms the unit is bits, and with natural logarithms it is nats.

For discrete variables, I(X; Y) lies between 0 and the smaller of H(X) and H(Y). Some people divide by an entropy to get a normalized score. Say which one, since several conventions exist.

From a joint table

Let X indicate whether a customer opened an email and Y whether they later purchased, in an invented example.

Y = 0 Y = 1 Total
X = 0 0.4 0.1 0.5
X = 1 0.1 0.4 0.5
Total 0.5 0.5 1.0

Under independence every cell would be 0.25.

I = 2 · 0.4 · ln(0.4/0.25)  +  2 · 0.1 · ln(0.1/0.25)
  = 0.376 − 0.183
  ≈ 0.193 nats  ≈ 0.278 bits

Y has 1 bit of entropy here. Knowing X removes about 0.278 of it. Purchases are still quite uncertain, though much less so than before. Nothing here shows that opening the email causes the purchase.

What correlation misses

Let X take the values −1, 0 and 1 with equal probability, and let Y = X². The correlation between X and Y is zero, because the relationship is symmetric. Yet Y is completely determined by X. The mutual information equals H(Y), the entropy of a variable that is 0 with probability 1/3 and 1 with probability 2/3, about 0.918 bits.

Mutual information is also unchanged when you relabel categories or apply an invertible transformation to either variable, such as taking the logarithm of a positive feature. It measures the dependence, not the shape in which it is written.

The price is that the number does not tell you what the relationship looks like. Plot the data as well.

Screening features

A common filter ranks each feature by its mutual information with the target and keeps the top ones. It is cheap and model independent, and it has two blind spots.

Interactions. Let X₁ and X₂ be independent fair bits and Y be 1 when they differ. Each feature alone has zero mutual information with Y. Together they determine it, giving 1 bit. A one-at-a-time filter would discard both.

Redundancy. Ten copies of a strong feature each score highly, but nine add nothing. Methods such as minimum redundancy maximum relevance trade relevance against overlap, using conditional mutual information or an approximation of it.

Choose features inside each training fold. Selecting on the full dataset leaks information about the test labels and inflates scores. An unusually high score is also worth investigating as possible target leakage. For the other families of methods, see filters, wrappers and embedded selection.

Reading a single-feature mutual information score
High, expected Likely useful. Check overlap with other features. High, surprising Suspect leakage or an identifier-like column. Low, alone May still matter through an interaction. Low everywhere Weak signal, or the estimator cannot see it. High, expected Likely useful. Check overlap with other features. High, surprising Suspect leakage or an identifier-like column. Low, alone May still matter through an interaction. Low everywhere Weak signal, or the estimator cannot see it.

The estimation problem

For two categorical variables you can plug observed frequencies into the formula. This plug-in estimate is biased upward on average: random fluctuations look like dependence. The bias grows with the number of cells relative to the number of examples. A customer identifier with a unique value on every row has a plug-in score equal to the whole entropy of the target, while predicting nothing about new customers.

Continuous variables need extra choices. Binning depends on the number and placement of bins. Nearest-neighbor estimators avoid fixed bins but have a neighbor count to choose and are sensitive to feature scaling. In scikit-learn, mutual_info_classif and mutual_info_regression use neighbor-based methods for continuous features, and you should mark which columns are discrete.

A shuffle test shows what the estimator reports when there is truly no relationship.

import numpy as np

def mi(x, y):                          # x, y: integer arrays of shape (n,)
    joint = np.zeros((x.max() + 1, y.max() + 1))
    np.add.at(joint, (x, y), 1)
    p = joint / joint.sum()
    indep = np.outer(p.sum(axis=1), p.sum(axis=0))
    m = p > 0
    return np.sum(p[m] * np.log(p[m] / indep[m]))     # nats

rng = np.random.default_rng(0)
n = 200
y = rng.integers(0, 2, size=n)
x = rng.integers(0, 20, size=n)        # 20 categories, unrelated to y
null = [mi(x, rng.permutation(y)) for _ in range(500)]
print(mi(x, y), np.mean(null), np.quantile(null, 0.95))

The true value here is zero, yet the estimates are clearly positive. Only a score well above the shuffled range deserves attention, and if you screen many features, some will exceed the 95% line by luck.

Conditioning changes the picture

Conditional mutual information, I(X; Y | Z), asks how much X tells you about Y when Z is already known. It is often the question you actually care about when deciding whether to add a feature to a model that has others.

It can be smaller than the unconditional score. If X and Y are related only because both depend on Z, then I(X; Y) is positive while I(X; Y | Z) is zero. A postcode might look informative about a purchase mainly because it tracks income, and add little once income is included.

It can also be larger. In the two-bit example, X₁ alone tells you nothing about Y, but once X₂ is known, X₁ settles Y completely, so I(X₁; Y | X₂) is 1 bit.

The chain rule ties these together.

I(X₁, X₂; Y) = I(X₁; Y) + I(X₂; Y | X₁)
two-bit case:      1     =     0    +    1       (bits)

Estimating the conditional version is harder still, because the data are split across the values of Z. With several conditioning features, most combinations appear once or never. Practical selection methods therefore condition on one chosen feature at a time or let a predictive model do the conditioning. Conditional independence is the special case where the quantity equals zero.

Looking inside representations

Let Z = f(X) be a layer's output. The data processing inequality says I(Y; Z) ≤ I(Y; X): no function of the input alone can create information about the target that the input lacked.

Usable information is a different matter. A network can make information far easier to extract without adding any. This is why many studies train a simple probe, such as a linear classifier, on a layer's activations. Held-out probe accuracy shows what that probe can read. Compare against controls, such as random labels or an untrained network, because a powerful probe can learn a task by itself.

Be careful with claims about the mutual information between inputs and hidden layers. For a deterministic network with continuous inputs, the quantity can be infinite or uninformative, and finite values then come from noise or binning added by the analyst. Debates about "information compression" during training turn partly on this point.

Bounds used in training

Some objectives maximize a lower bound on mutual information between two views of the same item. The InfoNCE loss asks a model to pick the true partner out of K candidates. With a mean loss L in nats, ln K − L is a lower bound on the information, up to sampling error in L.

Such a bound can never exceed ln K, so with 256 candidates it tops out near 5.5 nats even if the real value is larger. A good bound also does not guarantee useful features: the choice of views, the network and the negative examples matter a great deal. Contrastive learning covers the practice.

Reporting it responsibly

State the logarithm base, the estimator, its settings, the sample size and a null baseline. Confirm important findings by a direct test: add or remove the feature and compare model performance on held-out data. Mutual information is a good way to raise questions about your data, and a weak way to settle them alone.

Common questions

Is higher mutual information always better for a feature?

No. The feature may be unavailable at prediction time, duplicate others or encode something you must not use.

Can mutual information be negative?

The true quantity cannot. Some estimators can return slightly negative values on weak relationships, which you should read as indistinguishable from zero.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 26 articles in The Math Behind the Methods →

Latest news on this topic