Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 3 of 9
Multivariate Correlation Analysis, Collinearity & Heatmaps
Features in enterprise datasets rarely exist in isolation; they exhibit complex linear and non-linear interactions. High multicollinearity (when two or more predictors are strongly linearly dependent) inflates the variance of regression coefficients, rendering model weights unstable and uninterpretable. Measuring Pearson linear correlation, Spearman rank correlation, and Variance Inflation Factor (VIF) enables proactive feature pruning.
Multicollinearity Detection via Correlation Matrix & VIF
import pandas as pd
import numpy as np
from statsmodels.stats.outliers_influence import variance_inflation_factor
# Create synthetic real-estate dataset with collinearity
np.random.seed(42)
n = 1000
sqft = np.random.normal(2000, 500, n)
num_rooms = (sqft / 400).astype(int) + np.random.choice([0, 1], size=n)
# Severe collinearity: total_sqft and living_area_sqft are almost identical
living_area = sqft * 0.95 + np.random.normal(0, 10, n)
lot_size = np.random.exponential(5000, n)
X_data = pd.DataFrame({
'sqft': sqft,
'num_rooms': num_rooms,
'living_area': living_area,
'lot_size': lot_size
})
# 1. PEARSON (Linear) vs SPEARMAN (Monotonic non-linear) CORRELATION
pearson_corr = X_data.corr(method='pearson')
spearman_corr = X_data.corr(method='spearman')
print("=== PEARSON CORRELATION MATRIX ===")
print(pearson_corr.round(3))
# 2. VARIANCE INFLATION FACTOR (VIF) CALCULATION
# VIF = 1 / (1 - R_i^2) where R_i^2 is the R^2 from regressing feature i on all others
vif_report = []
for i, col in enumerate(X_data.columns):
vif_score = variance_inflation_factor(X_data.values, i)
status = 'Severe Collinearity (Drop/Combine)' if vif_score > 10.0 else 'Moderate' if vif_score > 5.0 else 'Safe'
vif_report.append({'feature': col, 'VIF': f"{vif_score:.2f}", 'status': status})
print("\n=== VARIANCE INFLATION FACTOR (VIF) AUDIT ===")
print(pd.DataFrame(vif_report).to_string())Pro Tip: Spearman vs Pearson for Non-Linear Monotonicity
Pearson correlation only captures strict linear relationships (y = mx + b). If a relationship is non-linear but monotonic (e.g., y = x³ or logarithmic utility), Pearson will underestimate correlation while Spearman rank correlation will score a perfect 1.0. Always inspect Spearman correlation when features have non-Gaussian distributions.
MlCorrelationAnalysis Visual Representation
Hands-On Challenge: Automated Collinear Feature Pruner
Write a function `prune_collinear_features(df, threshold=0.85)` that computes the absolute pairwise correlation matrix, identifies feature pairs exceeding the threshold, and drops the feature with the lower correlation to the target variable.
Quick Quiz & Key Concept Checks
Common Pitfall: Assuming Zero Correlation Implies Independence
A Pearson correlation of zero means there is no linear relationship, NOT that the features are independent. For example, if y = x² where x is uniformly distributed around zero, Pearson correlation is exactly 0.0, yet y is 100% deterministically dependent on x. Always inspect scatter plots or compute Mutual Information.