xbe.at Work with me

Machine learning / Advanced ML topics

Understanding Mutual Information in Machine Learning with Python

9 min read7 sectionsCC0

Contents
  1. The Intuition and Mathematical Foundation
  2. Estimating Mutual Information from Data
  3. Mutual Information vs. Correlation
  4. Feature Selection with Mutual Information
  5. Evaluating Clustering with Normalized Mutual Information
  6. Common Pitfalls
  7. Key Takeaways

Mutual Information (MI) is a fundamental concept in information theory that quantifies the amount of information obtained about one random variable through observing another. Unlike correlation, which only captures linear dependencies, MI measures the general statistical dependence between two variables, regardless of whether the relationship is linear, non-linear, or complex. In machine learning, this makes it an indispensable tool for feature selection, dimensionality reduction, and model evaluation, particularly when dealing with high-dimensional data where simple metrics might miss critical interactions.

You should reach for Mutual Information when you need to understand the strength of the relationship between features and a target variable without assuming a specific functional form. It is especially valuable in pre-processing stages to filter out redundant features or in clustering evaluation to assess how well predicted labels align with ground truth. While correlation coefficients like Pearson’s r are computationally cheap and intuitive for linear systems, they fail to detect non-linear patterns, such as quadratic or periodic relationships. MI fills this gap by providing a symmetric, non-negative measure of dependency that is invariant to monotonic transformations, making it a robust choice for exploratory data analysis and feature engineering.

The Intuition and Mathematical Foundation

At its core, Mutual Information measures the reduction in uncertainty about one variable given knowledge of another. If knowing X tells you nothing about Y, the MI is zero. If knowing X completely determines Y, the MI is equal to the entropy of Y. Mathematically, MI is defined as the Kullback-Leibler divergence between the joint distribution P(X,Y) and the product of the marginal distributions P(X)P(Y). This divergence measures how much the joint distribution differs from what it would be if the variables were independent.

The formula for discrete variables is:

I(X;Y) = \sum_{x \in X} \sum_{y \in Y} p(x,y) \log \left( \frac{p(x,y)}{p(x)p(y)} \right)

For continuous variables, the summation becomes an integral. A key property of MI is symmetry: I(X;Y) = I(Y;X). This means the information X provides about Y is identical to the information Y provides about X. Furthermore, MI is related to entropy H by the equation I(X;Y) = H(X) - H(X|Y), where H(X|Y) is the conditional entropy. This relationship highlights that MI is essentially the "shared" information between two variables.

Estimating Mutual Information from Data

Calculating MI exactly requires knowing the true probability distributions, which is rarely possible in practice. Instead, we estimate it from data samples. For discrete data, we can count frequencies. For continuous data, common estimation methods include binning (histogram-based), kernel density estimation (KDE), and k-nearest neighbors (kNN).

Binning is the simplest approach but suffers from bias due to bin size selection. If bins are too wide, information is lost; if too narrow, the estimator becomes noisy. KDE offers a smoother alternative but can be computationally expensive and sensitive to bandwidth selection. The kNN estimator, often based on the KSG (Kraskov-Stögbauer-Grassberger) algorithm, is generally considered more robust for continuous variables as it adapts to the local density of the data.

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mutual_info_score
from sklearn.neighbors import KernelDensity

# Generate synthetic data with a non-linear relationship
np.random.seed(42)
n_samples = 1000
x = np.random.uniform(-1, 1, n_samples)
y = x**2 + np.random.normal(0, 0.1, n_samples)

# Method 1: Binning (using sklearn's mutual_info_score which handles discretization internally)
# Note: mutual_info_score expects discrete labels, so we discretize x and y first
from sklearn.preprocessing import KBinsDiscretizer

discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')
x_binned = discretizer.fit_transform(x.reshape(-1, 1)).flatten()
y_binned = discretizer.fit_transform(y.reshape(-1, 1)).flatten()

mi_binned = mutual_info_score(x_binned, y_binned)

# Method 2: KDE-based estimation
def mi_kde(x, y, bandwidth=0.1):
    # Stack data for joint density
    xy = np.vstack([x, y]).T
    
    # Fit joint density
    kde_joint = KernelDensity(bandwidth=bandwidth).fit(xy)
    # Fit marginal densities
    kde_x = KernelDensity(bandwidth=bandwidth).fit(x.reshape(-1, 1))
    kde_y = KernelDensity(bandwidth=bandwidth).fit(y.reshape(-1, 1))
    
    # Calculate log probabilities
    log_p_joint = kde_joint.score_samples(xy)
    log_p_x = kde_x.score_samples(x.reshape(-1, 1))
    log_p_y = kde_y.score_samples(y.reshape(-1, 1))
    
    # MI = E[log(P(X,Y) / (P(X)P(Y)))] = E[log P(X,Y) - log P(X) - log P(Y)]
    mi = np.mean(log_p_joint - log_p_x - log_p_y)
    return mi

mi_kde_est = mi_kde(x, y)

print(f"MI (Binning): {mi_binned:.4f}")
print(f"MI (KDE): {mi_kde_est:.4f}")
MI (Binning): 0.8329
MI (KDE): 0.8201

The code above demonstrates two estimation techniques. The binning method discretizes the continuous variables into 10 bins before calculating MI. The KDE method estimates the probability densities directly. You will notice that the values differ slightly. Binning can be biased if the bin edges do not align well with the data distribution, while KDE requires careful tuning of the bandwidth parameter. For most practical applications in scikit-learn, the built-in mutual_info_score or mutual_info_regression functions use optimized estimators that are more reliable than manual implementations.

Mutual Information vs. Correlation

The primary advantage of MI over correlation is its ability to capture non-linear dependencies. Pearson correlation measures the strength of a linear relationship. If two variables are related by a parabola, the Pearson correlation might be close to zero, misleadingly suggesting independence. MI, however, will be high because knowing x significantly reduces the uncertainty about y.

Consider a scenario where y = x^2. The correlation coefficient r will be approximately zero because the positive and negative slopes cancel out. However, the mutual information will be substantial because the value of x strongly predicts the magnitude of y. This distinction is critical in feature selection. A feature with low correlation but high MI might still be highly predictive, whereas a feature with high correlation but low MI (rare, but possible with outliers) might be misleading.

# Visualizing the difference
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

# Linear relationship
x_lin = np.random.normal(0, 1, 1000)
y_lin = 2 * x_lin + np.random.normal(0, 0.5, 1000)

# Non-linear relationship
x_nl = np.random.uniform(-1, 1, 1000)
y_nl = x_nl**2 + np.random.normal(0, 0.1, 1000)

for ax, x, y, title in zip(axes, [x_lin, x_nl], [y_lin, y_nl], ['Linear', 'Non-linear']):
    ax.scatter(x, y, alpha=0.5)
    ax.set_title(title)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    
    corr = np.corrcoef(x, y)[0, 1]
    # Discretize for MI calculation
    disc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')
    x_b = disc.fit_transform(x.reshape(-1, 1)).flatten()
    y_b = disc.fit_transform(y.reshape(-1, 1)).flatten()
    mi = mutual_info_score(x_b, y_b)
    
    ax.text(0.05, 0.95, f'Corr: {corr:.2f}\nMI: {mi:.2f}', 
            transform=ax.transAxes, va='top')

plt.tight_layout()
plt.show()
Figure drawn by the code above

In the output plots, you will observe that for the linear case, both correlation and MI are high. For the non-linear case, correlation is near zero, but MI remains high. This confirms that MI is a more general measure of dependency. When selecting features, relying solely on correlation can lead to discarding useful non-linear predictors.

Feature Selection with Mutual Information

In supervised learning, MI is widely used for feature selection. The goal is to select features that have high MI with the target variable Y but low MI with other selected features X_{selected} to avoid redundancy. This is often implemented using the Minimum Redundancy Maximum Relevance (mRMR) criterion.

Scikit-learn provides mutual_info_classif for classification and mutual_info_regression for regression. These functions estimate the MI between each feature and the target. Features with higher scores are considered more informative.

from sklearn.datasets import load_iris
from sklearn.feature_selection import mutual_info_classif
import pandas as pd

# Load dataset
iris = load_iris()
X, y = iris.data, iris.target

# Calculate MI scores
mi_scores = mutual_info_classif(X, y)

# Create a dataframe for analysis
feature_mi = pd.DataFrame({
    'feature': iris.feature_names,
    'mi_score': mi_scores
})
feature_mi = feature_mi.sort_values('mi_score', ascending=False)

print("Features ranked by Mutual Information:")
print(feature_mi)
Features ranked by Mutual Information:
             feature  mi_score
3   petal width (cm)  0.989960
2  petal length (cm)  0.983746
0  sepal length (cm)  0.500988
1   sepal width (cm)  0.232141

The output ranks the features based on their predictive power. In the Iris dataset, petal length and width typically have higher MI scores than sepal measurements, reflecting their stronger association with the species class. This ranking helps in reducing the dimensionality of the dataset while preserving the most relevant information.

Evaluating Clustering with Normalized Mutual Information

Unsupervised learning tasks like clustering lack ground truth labels, making evaluation difficult. Normalized Mutual Information (NMI) and Adjusted Mutual Information (AMI) are standard metrics for comparing clustering results against true labels. NMI normalizes the MI score to a range of [0, 1], where 1 indicates perfect agreement and 0 indicates independence. AMI adjusts for chance, ensuring that the score is zero for random label assignments.

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import adjusted_mutual_info_score, normalized_mutual_info_score

# Generate synthetic data
X, true_labels = make_blobs(n_samples=300, centers=4, random_state=42)

# Perform clustering
kmeans = KMeans(n_clusters=4, random_state=42)
predicted_labels = kmeans.fit_predict(X)

# Calculate metrics
ami = adjusted_mutual_info_score(true_labels, predicted_labels)
nmi = normalized_mutual_info_score(true_labels, predicted_labels)

print(f"Adjusted Mutual Information: {ami:.4f}")
print(f"Normalized Mutual Information: {nmi:.4f}")
Adjusted Mutual Information: 0.9871
Normalized Mutual Information: 0.9872

High AMI and NMI scores indicate that the clustering algorithm has successfully recovered the underlying structure of the data. These metrics are preferred over simple accuracy because they account for the permutation invariance of cluster labels (i.e., cluster 1 in prediction might correspond to cluster 3 in truth).

Common Pitfalls

  1. Sample Size Sensitivity: MI estimators are biased, especially with small sample sizes. The estimated MI tends to be higher than the true MI because the estimator overfits the noise in the data. Always use large datasets or bias-corrected estimators when possible.
  2. Discretization Bias: When using binning for continuous variables, the choice of bin number and strategy (uniform vs. quantile) significantly impacts the result. There is no universal "best" binning strategy; it often requires experimentation.
  3. Computational Cost: Calculating MI for high-dimensional data can be expensive. For very large datasets, consider using approximate methods or applying MI only after initial dimensionality reduction.
  4. Interpretation: MI does not indicate the direction of the relationship. A high MI value tells you that variables are dependent, but not whether one causes the other or if the relationship is positive or negative.

Key Takeaways

  • Mutual Information measures general statistical dependence, capturing both linear and non-linear relationships.
  • It is symmetric and non-negative, making it a robust metric for comparing variable relationships.
  • Use MI for feature selection when relationships are expected to be non-linear or complex.
  • For continuous data, prefer kNN-based or KDE-based estimators over simple binning to reduce bias.
  • In clustering evaluation, use Adjusted Mutual Information (AMI) to account for chance agreement.
  • Be cautious of small sample sizes and discretization choices, as they can introduce significant bias in MI estimates.

Keep going

More in Advanced ML topics

All of them