Moving Beyond Correlation to Causation
Correlation: X and Y tend to move together
Causation: Changing X directly changes Y
Correlation can arise from:
For each unit i with treatment T ∈ {0, 1}:
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)]$$
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.
A confounder Z is a variable that:
Example: Age confounds the relationship between exercise and health.
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.
| Method | Approach |
|---|---|
| Randomization | Break link between confounder and treatment |
| Conditioning | Control for confounders in regression |
| Matching | Compare similar treated/control units |
| Instrumental Variables | Find variable affecting T but not Y directly |
Idea: Match treated and control units with similar propensity to be treated.
Propensity Score: \(e(X) = P(T=1|X)\)
Steps:
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.
Idea: Find a variable Z that affects T but only affects Y through T.
Requirements:
Example: Distance to college as IV for education's effect on earnings.
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]$$
Visual representation of causal relationships:
X ← Z → Y
Z is a confounder. Conditioning on Z blocks the path.
Example: Summer → Ice cream, Summer → Drowning
X → Z → Y
Z is a mediator. Conditioning on Z blocks the causal path!
Example: Education → Job → Income
X → Z ← Y
Conditioning on Z OPENS a spurious path!
Example: Talent → Celebrity ← Beauty (conditioning on celebrity creates correlation)
See how confounding creates spurious correlations:
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)")
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)")
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)
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.
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.