🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Causal Inference — Moving Beyond Correlation

Advanced TopicsCausal Inference🟢 Free Lesson

Advanced Topics

Causal Inference — Beyond Correlation to Causation

Master causal inference methods to move beyond correlation and understand true cause-and-effect relationships in data. Essential for A/B testing and policy evaluation.

  • Do-Calculus — Pearl's framework for causal reasoning
  • Instrumental Variables — Addressing endogeneity in observational data
  • Difference-in-Differences — Estimating causal effects from natural experiments

"Correlation does not imply causation, but it sure does hint."

Causal Inference — Complete Guide

Causal inference goes beyond correlation to answer "what if" questions. Essential for treatment effects and decision-making.


Correlation vs Causation

Correlation vs Causation Diagram

Correlation vs CausationCorrelation ≈  CausationXY?Causation: X → YXYConfounding ExampleIce CreamDrowningHotWeather

DAGs (Directed Acyclic Graphs)

Causal DAG Examples

Common Causal DAG StructuresFork (Confounder)ZXYZ confounds X→YChain (Mediator)XMYX→M→Y (M mediates)ColliderXYZZ is collider (X→Z←Y)Fork: Z causes both X and Y | Chain: X causes M causes Y | Collider: X and Y both cause Z

Methods

Observational Methods:

  • Propensity Score Matching
  • Instrumental Variables
  • Difference-in-Differences
  • Regression Discontinuity
  • Double Machine Learning

Uplift Modeling:

  • Predict treatment effect, not outcome
  • Causal Forest
  • Meta-learners (T-learner, S-learner, X-learner)

Potential Outcomes Framework

Potential Outcomes Framework (Rubin Causal Model)Unit iY_i(1): Potential outcome under treatmentY_i(0): Potential outcome under controlIndividual Treatment Effectτ_i = Y_i(1) - Y_i(0)Fundamental Problem: Only one is observed!Average Treatment Effect (ATE)ATE = E[Y(1) - Y(0)] = E[τ_i]ATE is the causal effect we want to estimate

Selection Bias, Worked Through Numbers

A coupon campaign makes the arithmetic concrete. Of 1,000 users, 300 open the coupon and 700 do not; conversion is 42% among those who opened it and 28% among those who did not, so the campaign dashboard reports a lift of 14 percentage points. Opening a coupon is self-selected behaviour, though: people who open it were already more engaged. Split the same population by recent activity and the story collapses. Among users with three or more sessions in the previous week, conversion is 46% for the treated and 44% for the untreated — a gap of two points. The 14-point headline was comparing two different kinds of person rather than two versions of the same person.

Matching every treated user to a control with a nearly identical propensity score repairs part of that gap. On this dataset the matched estimate is 2.4 percentage points with a 95% interval running from 0.6 to 4.2, roughly six times smaller than the number on the dashboard and still distinguishable from zero. Any causal claim you publish should carry an interval like that one, because a point estimate without uncertainty is a coin toss with extra steps.

Propensity Score Matching Step by Step

Fit a logistic regression for the probability of treatment using pre-treatment covariates only, then check the machinery before believing the estimate.

  • No post-treatment variables. Anything measured after the coupon arrived is a mediator or a collider, and conditioning on it reintroduces the bias you were trying to remove.
  • Common support. Plot the score distributions for treated and control units and drop units outside the 0.05 to 0.95 range; the model is extrapolating there, so no honest match exists.
  • Caliper matching. Match nearest neighbour within 0.2 standard deviations of the logit of the score. The caliper prevents matches that are technically closest but still far apart.
  • Balance, not significance. Compare standardized mean differences before and after matching. Sessions in the last week starts at an SMD of 0.83 and lands at 0.04 after matching; anything still above 0.10 means the match failed and the effect estimate should not be reported.
  • Trim extreme weights. If you prefer weighting to matching, treated units carry weight one divided by the score and controls carry one divided by one minus the score, so a unit scored at 0.99 receives a weight of 100. Trim at the first and ninety-ninth percentiles before computing anything.

Instrumental Variables and Difference-in-Differences

When randomization is impossible, two designs do most of the work. An instrument is a variable that moves the treatment without touching the outcome directly: relevance is checked with a first-stage F statistic that must sit above 10, because weak instruments push the estimate back toward the confounded OLS answer, and the exclusion restriction — that the instrument affects the outcome only through the treatment — is argued from domain knowledge and can never be tested.

Difference-in-differences instead compares changes. Pilot region sales rise from 90 to 117 (+27) while the control region rises from 100 to 112 (+12), so the effect is 27 − 12 = 15 units of lift, the difference of the two differences. The design lives or dies on parallel trends: if the two regions grew at similar rates in the periods before the rollout, the control's growth is a credible stand-in for what the pilot would have done untreated. Run a placebo by treating an earlier pre-launch date as the start of the intervention; a coefficient near zero, say 0.3 units with an interval spanning zero, is what you want to see before reporting the real number.

MethodCore assumptionWhat the data must containBias when the assumption breaks
Randomized trialRandom assignmentAbility to randomize unitsNon-compliance shrinks the estimate toward zero
Propensity matchingNo unmeasured confounding plus overlapRich pre-treatment covariatesA missing driver leaves residual confounding
Instrumental variableRelevance and exclusionOne valid instrumentWeak instrument biases toward OLS
Difference-in-differencesParallel trendsPanel observations before and afterA differential shock masquerades as an effect
Regression discontinuityNo manipulation at the cutoffA sharp eligibility thresholdSorting at the cutoff breaks local validity
Double machine learningNuisance models are consistentHigh-dimensional confoundersAn overfit nuisance model inflates variance
python
import pandas as pd
import statsmodels.formula.api as smf

# panel with one row per region per week
did = df.copy()
did["period"] = (did["week"] >= "2025-06-01").astype(int)
did["treated"] = (did["region"] == "pilot").astype(int)
did["post_treatment"] = did["period"] * did["treated"]

model = smf.ols("sales ~ treated + period + post_treatment", data=did).fit(
    cov_type="cluster", cov_kwds={"groups": did["region"]}
)
effect = model.params["post_treatment"]
low, high = model.conf_int().loc["post_treatment"]
print(f"DiD effect {effect:.2f} units, 95% CI [{low:.2f}, {high:.2f}]")

# placebo on pre-launch weeks only: a real effect should be near zero here
pre = did[did["period"] == 0].copy()
pre["fake_start"] = (pre["week"] >= "2025-04-06").astype(int)
pre["fake_interact"] = pre["fake_start"] * pre["treated"]
placebo = smf.ols("sales ~ treated + fake_start + fake_interact", data=pre).fit()
print("placebo:", round(placebo.params["fake_interact"], 3))
python
import numpy as np
from sklearn.linear_model import LogisticRegression

pre_cols = ["sessions_7d", "orders_12m", "email_open_rate", "device_type"]
lr = LogisticRegression(max_iter=1000).fit(df[pre_cols], df["treated"])
df["ps"] = lr.predict_proba(df[pre_cols])[:, 1]

# common support: discard units the model scores outside the overlap band
support = df[(df["ps"] >= 0.05) & (df["ps"] <= 0.95)]
treated = support[support["treated"] == 1]
control = support[support["treated"] == 0]

logit_c = np.log(control["ps"] / (1 - control["ps"]))
logit_t = np.log(treated["ps"] / (1 - treated["ps"]))
caliper = 0.2 * logit_t.std()

matched_rows = []
for _, p in treated["ps"].items():
    gap = np.abs(np.log(p / (1 - p)) - logit_c.to_numpy())
    ok = np.flatnonzero(gap <= caliper)
    if ok.size:
        matched_rows.append(control.iloc[ok[np.argmin(gap[ok])]])

matched = pd.DataFrame(matched_rows)
ate = treated["converted"].mean() - matched["converted"].mean()

def smd(a, b):
    return (a.mean() - b.mean()) / np.sqrt((a.var() + b.var()) / 2)

print(f"matched ATE {ate * 100:.1f} pp")
print("balance SMD:", round(smd(treated["sessions_7d"], matched["sessions_7d"]), 3))

Both scripts print a number you would be willing to defend: an effect with an interval, a placebo coefficient near zero, and a balance statistic that says the two groups really are comparable after matching.


Key Takeaways


What to Learn Next

-> ML Ethics — Fairness, Bias, Interpretability and Responsible AI Learn about ml ethics — fairness, bias, interpretability and responsible ai.

-> A/B Testing for ML — Experiment Design and Statistical Rigor Learn about a/b testing for ml — experiment design and statistical rigor.

-> Model Evaluation — Metrics, Cross-Validation and Selection Learn about model evaluation — metrics, cross-validation and selection.

-> ML Research Methods — Reading Papers and Reproducibility Learn about ml research methods — reading papers and reproducibility.

-> ML System Design — Architecture and Production Patterns Learn about ml system design — architecture and production patterns.

-> Model Interpretability — SHAP, LIME and Explainable AI Learn about model interpretability — shap, lime and explainable ai.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-17

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement