Machine Learning | Causal Inference

Moving Beyond Correlation to Causation

Table of Contents
  1. Correlation vs Causation
  2. Potential Outcomes Framework
  3. Confounding Variables
  4. Causal Methods
  5. Causal Graphs (DAGs)
  6. Interactive Visualization
  7. Code Examples
  8. Interview Questions

1. Correlation vs Causation

The Fundamental Problem

Correlation: X and Y tend to move together

Causation: Changing X directly changes Y

Correlation can arise from:

  • X causes Y: Smoking → Cancer
  • Y causes X: Reverse causation
  • Z causes both: Confounding (Ice cream sales ↔ Drowning, both caused by Summer)
  • Chance: Spurious correlation
Why This Matters in ML
  • Prediction: Correlation is sufficient
  • Intervention: Need causation! "If we change X, what happens to Y?"
  • Recommendation systems: Does showing product X cause purchase Y?
  • Policy decisions: Will this intervention actually help?

2. Potential Outcomes Framework

Rubin Causal Model

For each unit i with treatment T ∈ {0, 1}:

  • \(Y_i(1)\): Outcome if treated
  • \(Y_i(0)\): Outcome if not treated

Individual Treatment Effect: \(\tau_i = Y_i(1) - Y_i(0)\)

Average Treatment Effect (ATE):

$$ATE = E[Y(1) - Y(0)] = E[Y(1)] - E[Y(0)]$$

The Fundamental Problem of Causal Inference

We can never observe both \(Y_i(1)\) and \(Y_i(0)\) for the same unit!

We observe: \(Y_i = T_i \cdot Y_i(1) + (1-T_i) \cdot Y_i(0)\)

Solution: Use groups to estimate what we can't observe individually.

3. Confounding Variables

What is Confounding?

A confounder Z is a variable that:

  1. Affects the treatment (X)
  2. Affects the outcome (Y)
  3. Is NOT on the causal path from X to Y

Example: Age confounds the relationship between exercise and health.

Why Confounding Breaks Inference

Naïve comparison:

\(E[Y|T=1] - E[Y|T=0]\)

= ATE + Selection Bias

Selection bias occurs when treatment assignment is related to potential outcomes.

Handling Confounders
MethodApproach
RandomizationBreak link between confounder and treatment
ConditioningControl for confounders in regression
MatchingCompare similar treated/control units
Instrumental VariablesFind variable affecting T but not Y directly

4. Causal Methods

Propensity Score Matching

Idea: Match treated and control units with similar propensity to be treated.

Propensity Score: \(e(X) = P(T=1|X)\)

Steps:

  1. Estimate propensity scores (logistic regression)
  2. Match treated to control with similar scores
  3. Estimate ATE from matched sample
Difference-in-Differences

Idea: Compare changes over time between treated and control groups.

$$\tau_{DiD} = (Y_{T,after} - Y_{T,before}) - (Y_{C,after} - Y_{C,before})$$

Assumption: Parallel trends - groups would have changed similarly without treatment.

Instrumental Variables

Idea: Find a variable Z that affects T but only affects Y through T.

Requirements:

  • Relevance: Z affects T
  • Exclusion: Z doesn't directly affect Y
  • Independence: Z is as good as random

Example: Distance to college as IV for education's effect on earnings.

Regression Discontinuity

Idea: Exploit arbitrary cutoffs in treatment assignment.

Example: Scholarship given to students with GPA > 3.5

Compare students just above vs just below cutoff - they're essentially identical except for treatment.

$$\tau_{RD} = \lim_{x \to c^+} E[Y|X=x] - \lim_{x \to c^-} E[Y|X=x]$$

5. Causal Graphs (DAGs)

Directed Acyclic Graphs

Visual representation of causal relationships:

  • Nodes: Variables
  • Arrows: Causal effects (X → Y means X causes Y)
  • No cycles: Acyclic (no feedback loops)
Fork (Common Cause)

X ← Z → Y

Z is a confounder. Conditioning on Z blocks the path.

Example: Summer → Ice cream, Summer → Drowning

Chain (Mediation)

X → Z → Y

Z is a mediator. Conditioning on Z blocks the causal path!

Example: Education → Job → Income

Collider

X → Z ← Y

Conditioning on Z OPENS a spurious path!

Example: Talent → Celebrity ← Beauty (conditioning on celebrity creates correlation)

Key Rules for DAGs
  1. Block backdoor paths: Control for confounders (forks)
  2. Don't condition on mediators: Would remove part of causal effect
  3. Don't condition on colliders: Opens spurious paths
  4. Don't condition on descendants of colliders

6. Interactive Visualization

Confounding and Selection Bias

See how confounding creates spurious correlations:

7. Code Examples

Propensity Score Matching

import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import NearestNeighbors

def propensity_score_matching(df, treatment_col, outcome_col, covariates):
    """
    Estimate ATE using propensity score matching
    """
    # Step 1: Estimate propensity scores
    X = df[covariates]
    T = df[treatment_col]

    lr = LogisticRegression()
    lr.fit(X, T)
    propensity_scores = lr.predict_proba(X)[:, 1]
    df['propensity'] = propensity_scores

    # Step 2: Match treated to control
    treated = df[df[treatment_col] == 1]
    control = df[df[treatment_col] == 0]

    nn = NearestNeighbors(n_neighbors=1)
    nn.fit(control[['propensity']])
    distances, indices = nn.kneighbors(treated[['propensity']])

    # Step 3: Get matched control outcomes
    matched_control = control.iloc[indices.flatten()]

    # Step 4: Estimate ATE
    ate = treated[outcome_col].mean() - matched_control[outcome_col].mean()

    return ate, propensity_scores

# Example usage
np.random.seed(42)
n = 1000
confounder = np.random.normal(0, 1, n)
treatment = (np.random.random(n) < 1/(1 + np.exp(-confounder))).astype(int)
outcome = 0.5 * treatment + 0.8 * confounder + np.random.normal(0, 0.5, n)

df = pd.DataFrame({
    'treatment': treatment,
    'outcome': outcome,
    'confounder': confounder
})

ate, _ = propensity_score_matching(df, 'treatment', 'outcome', ['confounder'])
print(f"Estimated ATE: {ate:.3f} (True: 0.5)")

Difference-in-Differences

import statsmodels.api as sm

def difference_in_differences(df, group_col, time_col, outcome_col):
    """
    Estimate treatment effect using DiD
    """
    # Create interaction term
    df['post_treatment'] = (df[time_col] == 1).astype(int)
    df['treated_post'] = df[group_col] * df['post_treatment']

    # Regression: Y = β0 + β1*treated + β2*post + β3*treated*post
    X = df[[group_col, 'post_treatment', 'treated_post']]
    X = sm.add_constant(X)
    y = df[outcome_col]

    model = sm.OLS(y, X).fit()

    # β3 is the DiD estimate
    did_estimate = model.params['treated_post']
    did_se = model.bse['treated_post']

    return did_estimate, did_se, model

# Example: Effect of policy on some outcome
# Pre-treatment: treated and control groups
# Post-treatment: only treated group got intervention
df = pd.DataFrame({
    'group': [0]*50 + [1]*50 + [0]*50 + [1]*50,
    'time': [0]*100 + [1]*100,
    'outcome': np.concatenate([
        np.random.normal(10, 2, 50),   # Control, pre
        np.random.normal(12, 2, 50),   # Treated, pre
        np.random.normal(11, 2, 50),   # Control, post (+1 natural trend)
        np.random.normal(16, 2, 50)    # Treated, post (+3 treatment + 1 trend)
    ])
})

estimate, se, model = difference_in_differences(df, 'group', 'time', 'outcome')
print(f"DiD Estimate: {estimate:.3f} ± {1.96*se:.3f} (True: 3.0)")

Using DoWhy Library

import dowhy
from dowhy import CausalModel

# Create causal model from data and graph
model = CausalModel(
    data=df,
    treatment='treatment',
    outcome='outcome',
    common_causes=['age', 'income'],  # Confounders
    instruments=['distance_to_store']  # Optional IV
)

# Visualize the causal graph
model.view_model()

# Identify causal effect
identified = model.identify_effect()

# Estimate causal effect
estimate = model.estimate_effect(
    identified,
    method_name="backdoor.propensity_score_matching"
)
print(f"Causal Estimate: {estimate.value}")

# Refutation tests
refute = model.refute_estimate(
    identified, estimate,
    method_name="placebo_treatment_refuter"
)
print(refute)

8. Interview Questions & Answers

  1. Run an A/B test: Randomization breaks confounding
  2. If not possible, use observational methods:
    • Control for confounders (if you know them all)
    • Find a natural experiment or instrumental variable
    • Use regression discontinuity if there's a cutoff
  3. Check temporal precedence: Cause must precede effect
  4. Conduct sensitivity analysis: How strong would unmeasured confounding need to be to explain the result?

Simpson's Paradox: A trend that appears in aggregate data reverses when data is split by a confounding variable.

Classic Example: UC Berkeley admissions appeared to favor men overall, but favored women in each department. Women applied to more competitive departments!

Key insight: The right answer depends on the causal structure. Should you condition on department or not? Depends on whether you're asking about discrimination in admissions decisions vs overall outcomes.

  • ATE (Average Treatment Effect): E[Y(1) - Y(0)] - average effect across entire population
  • ATT (Average Treatment on Treated): E[Y(1) - Y(0) | T=1] - effect only among those who were treated
  • CATE (Conditional ATE): E[Y(1) - Y(0) | X=x] - heterogeneous treatment effects by subgroup

When they differ: When treatment effect varies and treatment assignment is non-random. E.g., if sicker patients get treatment AND treatment helps sick patients more, ATT > ATE.

Best Practices
  • Draw causal graph before analysis
  • Think about unmeasured confounders
  • Use multiple methods as sensitivity check
  • Prefer experiments when possible
Common Mistakes
  • Conditioning on mediators
  • Conditioning on colliders
  • Assuming all confounders measured
  • Confusing prediction with causal inference