Chapter 14 of 42 · ~18 min read & lab+65 XP
Chapter 14 · Machine Learning

Collinearity & Multicollinearity Explained: Correlation Matrix, VIF & Dummy Variable Trap

Why redundant features flip regression weight signs and explode standard errors, how to compute VIF, and how Ridge/Lasso/PCA fix it

What Is It?

Collinearity occurs when two input features move in lockstep (like height in cm and height in inches), while Multicollinearity happens when one feature can be predicted accurately from a combination of two or more other features.

Why Is It Required?

In Linear and Logistic Regression, multicollinearity makes learned weights wildly unstable, flips coefficient signs (saying bigger houses cost less!), and destroys statistical significance — even when overall accuracy looks fine.

Everyday Analogy: Two people pushing a car together at the exact same time: you know the car moved 10 feet, so total prediction is fine, but you cannot tell whether Person A pushed +100 and Person B pulled −90!
Why ML Engineers & Data Scientists Actually Need This

Multicollinearity is the #1 reason Linear/Logistic Regression coefficients look nonsensical to business stakeholders.

ML / AI Engineer

Perfect multicollinearity makes XᵀX singular (non-invertible), crashing unregularized closed-form OLS solvers.

Data Scientist

Whenever you report feature weights ('each extra bedroom adds $25k'), checking VIF first prevents embarrassing sign-flip errors.

Interview & Debug Edge

Top Data Science interview question: 'Does multicollinearity hurt predictions, or interpretability? How do you detect 3-way multicollinearity that a correlation heatmap misses?'

Step 0 · Test Your Gut Before Any Math!

Feature C equals Feature A + Feature B, yet pairwise correlations corr(A, C) and corr(B, C) are only 0.70. Which diagnostic catches this hidden 3-way multicollinearity?

What You Will Master in This Chapter
  • Distinguish pairwise Collinearity (2 correlated columns) from Multicollinearity (3+ columns forming a hidden linear combination).
  • Compute and interpret the Variance Inflation Factor (VIF = 1 / (1 − R_j²)) using standard thresholds (<5 safe, 5–10 caution, >10 severe).
  • Recognize the One-Hot Dummy Variable Trap as a special case of perfect multicollinearity.
  • Know which models suffer (OLS Linear/Logistic Regression) vs. which are mostly unaffected in prediction (Ridge, Lasso, Random Forests, XGBoost).
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
VIFj=11−Rj2\text{VIF}_j = \frac{1}{1 - R_j^2}Say aloud:“Variance Inflation Factor for feature j”
Plain-English Meaning
Measures how much the variance of weight w_j is inflated by redundancy with other features.
Everyday Example
If R_j² = 0.90, VIF = 1 / 0.10 = 10 (severe multicollinearity!).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

When two features carry the same information, OLS Linear Regression has infinitely many ways to split the credit between them (+10 and 0, or +1,000 and -990). Tiny noise in your training sample picks a wild arbitrary split — predictions stay accurate, but individual weights become garbage!

1. Collinearity vs. Multicollinearity & The Dummy Variable Trap

Everyday Story First (Zero Math Yet!)

Suppose a dataset has salary_usd and salary_eur, or One-Hot columns is_male and is_female alongside an intercept 1. Because is_male + is_female = 1 on every row, one column is 100% redundant!

  • Collinearity: Two features are strongly correlated (∣r∣>0.85|r| > 0.85). Caught by a correlation matrix.
  • Multicollinearity: One feature is a linear combination of 2 or more other features (e.g., total_spend = food_spend + rent_spend + fun_spend). Pairwise correlations can look moderate while VIF explodes to ∞\infty!
  • Dummy Variable Trap: Including all KK One-Hot columns plus an intercept creates exact multicollinearity. Fix: set drop_first=True for unregularized OLS.

2. How to Detect & Fix Multicollinearity

VIF Thresholds

  • VIF = 1: Zero correlation with other features.
  • VIF 1–5: Moderate, usually harmless.
  • VIF > 5–10: High multicollinearity — take action if interpreting coefficients!

4 Proven Fixes

  1. Drop or Combine Redundant Columns: Keep sqft and drop square_meters, or create a single ratio/sum.
  2. Use Ridge (L2) Regularization: Adds +λI+\lambda I to X⊤XX^\top X, splitting weights smoothly across correlated features (next chapter!).
  3. Use Lasso (L1) or ElasticNet: Automatically zeros out redundant duplicates.
  4. Apply PCA: Rotates correlated columns into 100% orthogonal (VIF = 1) principal components.
Animated Mini-Lab · Slide λ to Watch Lasso (L1) Snap Noisy Weights to Exact 0.00!
L1 Diamond → Hits Axis (w₂ = 0!)L2 Circle → Smooth Shrink (w₂ ≠ 0)
SqFt (Strong)
Ridge: 1.82
Lasso: 2.80
Location (Med)
Ridge: 0.82
Lasso: 0.60
Paint Color (Noise)
Ridge: 0.32
Lasso: 0.00 (ZERO!)
Day Listed (Noise)
Ridge: 0.14
Lasso: 0.00 (ZERO!)
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Predictions are almost completely unaffected because trees just pick one of the correlated columns at each split. However, feature importance gets diluted/split across the correlated duplicates!

Interactive Visual Lab
Lab Challenge: See how L2 Ridge regularization stabilizes weights when features are correlated.
Interactive Animation • Regularization Paths

Sweep λ from 0 → 3: Watch Lasso Drop Noisy Weights to Exact Zero

Toggle Lasso (L1 Sparsity) vs. Ridge (L2 Smooth Shrinkage) while the path sweeps live!

Regularization Strength λ (0.0 → 3.0)
0%
λ = 0.00 | Zeros: 0
At λ = 0.00: exact zero weights = 0 / 4. Lasso's sharp L1 diamond corners delete weak/noisy features completely!
Intuition Takeaway: Use VIF (1 / (1 − R_j²)) to catch hidden multi-feature redundancy, drop duplicate columns or apply drop_first=True for OLS, or switch to Ridge/ElasticNet (coming up next!).
Production NumPy & PyTorch Code Patterns
import numpy as np

# Compute VIF (Variance Inflation Factor) From Scratch for Every Feature
rng = np.random.default_rng(0)
N = 200
x1 = rng.normal(size=N)
x2 = rng.normal(size=N)
x3 = 0.9 * x1 + 0.4 * x2 + rng.normal(scale=0.05, size=N)  # multicollinear combo!
X = np.column_stack([x1, x2, x3])

def compute_vif(X_mat: np.ndarray) -> list[float]:
    vifs = []
    for j in range(X_mat.shape[1]):
        y_j = X_mat[:, j]
        X_other = np.column_stack([np.ones(len(y_j)), np.delete(X_mat, j, axis=1)])
        beta, *_ = np.linalg.lstsq(X_other, y_j, rcond=None)
        pred = X_other @ beta
        r2 = 1.0 - np.sum((y_j - pred) ** 2) / np.sum((y_j - y_j.mean()) ** 2)
        vifs.append(round(float(1.0 / max(1e-9, 1.0 - r2)), 2))
    return vifs

for name, vif in zip(["x1", "x2", "x3 (combo!)"], compute_vif(X)):
    print(f"{name:12s} | VIF = {vif}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Claiming that multicollinearity always ruins test-set prediction accuracy.
Best Practice: Clarify that multicollinearity primarily destroys coefficient stability & interpretability (inflating standard errors), while overall predictions can remain accurate if train and test share the same feature correlation.
Chapter Mastery Check (+65 XP)
Score: 0 / 1
1Feature j has R_j² = 0.90 when regressed on the other input features. What is its VIF, and what does it indicate?

Apply What You Learned — Solve Matching Coding Problems