<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajay Deshpande on Medium]]></title>
        <description><![CDATA[Stories by Ajay Deshpande on Medium]]></description>
        <link>https://medium.com/@ajay-deshpande?source=rss-4773ba74150b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hY4ZtCOc-ErId-Vs</url>
            <title>Stories by Ajay Deshpande on Medium</title>
            <link>https://medium.com/@ajay-deshpande?source=rss-4773ba74150b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:23:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajay-deshpande/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Marketing Model to Targeting the “Right” People]]></title>
            <link>https://ajay-deshpande.medium.com/marketing-model-to-targeting-the-right-people-06d15d248a0b?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/06d15d248a0b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[uplift-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 02:38:32 GMT</pubDate>
            <atom:updated>2026-06-29T02:38:32.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>The customers most likely to buy are often the worst people to market to.</h3><p>Here’s a scenario that plays out every day at e-commerce companies.</p><p>A data scientist builds a conversion model. It’s accurate — 85% AUC, stakeholders are impressed. The marketing team uses it to target the top 20% of customers most likely to purchase. Email campaign goes out. Conversion rate looks great. Everyone celebrates.</p><p>But here’s what nobody checked: how many of those customers would have bought anyway?</p><h3>The Problem With Response Models</h3><p>Standard ML models answer the question: <em>who will convert?</em></p><p>That sounds like the right question. It isn’t.</p><p>The right question is: <em>who will convert </em><strong><em>because</em></strong><em> of our campaign?</em></p><p>These are fundamentally different. A customer who buys every week regardless of whether you email them contributes nothing incremental when you target them. You’ve spent budget, potentially annoyed them, and claimed credit for a conversion that was going to happen anyway.</p><p>Worse — there’s a segment of customers who are actually deterred by marketing. Email them and they convert <em>less</em>. A standard response model would happily rank these people highly, because they have strong purchase history. You’d be paying to destroy revenue.</p><p>Uplift modeling is the framework that separates these groups.</p><h3>What Uplift Modeling Actually Measures</h3><p>The core quantity is the <strong>Conditional Average Treatment Effect</strong> (CATE):</p><blockquote>τ(x) = E[Y(1) − Y(0) | X = x]</blockquote><p>In plain English: for a customer with features x, what is the causal effect of sending them an email on whether they purchase?</p><p>This is a fundamentally causal question, not a predictive one. We’re not asking what <em>will</em> happen — we’re asking what <em>would</em> happen if we intervene, versus if we don’t.</p><p>The reason this is hard is called the <strong>fundamental problem of causal inference</strong>: we can never observe both outcomes for the same customer. We either send them the email or we don’t. We never get to see the counterfactual.</p><p>Uplift modeling solves this by learning the treatment effect from a randomized experiment — where we <em>can</em> estimate the counterfactual at the population level.</p><h3>The Dataset: A Real Marketing Experiment</h3><p>To build this, I used the <strong>Hillstrom E-Mail Marketing dataset</strong> — 64,000 customers from a real e-commerce randomized controlled trial. Customers were randomly assigned to receive a men’s catalog email, a women’s catalog email, or no email at all.</p><p>Random assignment is key. It means the treatment and control groups are statistically identical on everything we can’t measure — motivation, browsing behavior, intent to buy. Any difference in outcomes between the groups is causally attributable to the email.</p><p>The raw numbers looked modest: sending an email improved conversion by about 0.5 percentage points overall. But that average hides enormous heterogeneity. Some customers responded strongly. Others didn’t respond at all. A meaningful group responded negatively.</p><p>The goal was to find the responders.</p><h3>The Approach: Meta-Learners</h3><p>Meta-learners are a class of methods that estimate individual-level treatment effects by wrapping standard ML models. I implemented three:</p><p><strong>S-Learner</strong> trains a single model with treatment as just another feature. Simple, but the treatment signal can get regularized away — the model may not give the email variable enough weight.</p><p><strong>T-Learner</strong> trains completely separate models on the treated and control populations, then subtracts their predictions. More flexible, but needs sufficient data in both arms.</p><p><strong>X-Learner</strong> is the most sophisticated. It computes “pseudo-outcomes” — estimates of what each individual’s treatment effect was based on their observed outcome and the counterfactual predicted by the opposite arm’s model. These pseudo-outcomes are then modeled directly. It’s designed to perform well when the treatment and control arms are imbalanced.</p><p>All three used XGBoost regressors as base models, tracked with MLflow on Databricks.</p><h3>What We Found</h3><p>The ATE sanity check passed immediately — all three learners recovered the raw ATE of 0.00495 within 0.00003. That’s strong internal validity.</p><p>For ranking quality, I used <strong>Qini curves</strong> — the uplift modeling equivalent of ROC curves. Instead of ranking by predicted conversion probability, you rank by predicted treatment effect and measure how much actual incremental conversion you capture as you target more people. A model that perfectly identifies Persuadables would curve sharply upward. Random targeting is a straight diagonal.</p><p>T-Learner won with an AUUC of 30.0, versus 20.7 for X-Learner and 15.1 for S-Learner. With balanced treatment arms and near-perfect overlap (the propensity model had an AUC of 0.49 — essentially random, as expected from a well-run RCT), T-Learner’s simpler two-model approach was more efficient than X-Learner’s propensity weighting.</p><p>The real insight came from customer segmentation. Using predicted CATE and baseline conversion probability, every customer was classified into one of four groups:</p><p>SegmentWhat It Means<strong>Persuadables</strong>Email causes conversion. Target these.<strong>Sure Things</strong>Convert anyway. Wasted spend.<strong>Lost Causes</strong>Won’t convert regardless. Skip.<strong>Sleeping Dogs</strong>Email hurts conversion. Actively avoid.</p><p><strong>Sleeping Dogs had the highest observed conversion rate of any segment — 0.875%.</strong> A response model would have ranked them at the top of the targeting list. Uplift modeling identified them as the group to protect.</p><h3>The Business Case</h3><p>Same budget. 16,715 emails. Two strategies.</p><p>Random targeting generated <strong>$5,988 in incremental spend</strong>.</p><p>Targeting Persuadables generated <strong>$32,534 in incremental spend</strong>.</p><p>That’s a <strong>5.4× revenue multiplier</strong> from one modeling decision.</p><p>No new data. No additional budget. Just asking the right question.</p><h3>Why This Matters Beyond Marketing</h3><p>The same framework applies anywhere you’re deciding whether to intervene:</p><ul><li><strong>Credit risk</strong>: does offering a credit limit increase cause default, or do risky customers self-select into requesting increases?</li><li><strong>Healthcare</strong>: which patients benefit from a specific treatment, and which might be harmed?</li><li><strong>Retention</strong>: does sending a discount cause customers to stay, or does it train them to churn and wait for offers?</li></ul><p>In each case, the question isn’t <em>who has the outcome we want</em> — it’s <em>whose outcome changes because of us</em>.</p><p>That distinction is the difference between correlation and causation. And in a world where ML is used to make interventions, not just predictions, it’s the only question worth asking.</p><p><em>Built on Databricks with Delta Lake, MLflow, econml, and XGBoost. Dataset: Hillstrom E-Mail Marketing (2008). </em><a href="https://github.com/Ajay-Deshpande/uplift-marketing-causal-ml/tree/master"><em>Full code and notebooks on GitHub</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06d15d248a0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production Churn Pipeline on Databricks: MLflow, SHAP, and Drift Detection]]></title>
            <link>https://ajay-deshpande.medium.com/building-a-production-churn-pipeline-on-databricks-mlflow-shap-and-drift-detection-649e6aa5dc6f?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/649e6aa5dc6f</guid>
            <category><![CDATA[machine-learning-pipeline]]></category>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Sun, 21 Jun 2026 21:58:29 GMT</pubDate>
            <atom:updated>2026-06-21T22:02:15.824Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An end-to-end customer churn system built the way a real ML team would ship one — not just a model, but the full lifecycle around it.</em></p><p>Most churn prediction portfolios stop at “trained a model, got 0.85 AUC.” That’s the easy 20%. The other 80% — what actually separates a notebook experiment from a production system — is everything <em>around</em> the model: tracking experiments systematically, gating deployment on data the model has never seen, explaining predictions to non-technical stakeholders, and knowing when the model has gone stale.</p><p>I wanted a portfolio project that demonstrated that 80%. So I built <a href="https://github.com/Ajay-Deshpande/churn-ops"><strong>churn-ops</strong></a> — a seven-stage pipeline on Databricks covering ingestion, feature engineering, experiment tracking, model registry, explainability, drift monitoring, and scheduled batch scoring, wired together with MLflow.</p><h3>The brief</h3><p>I used the <a href="https://www.kaggle.com/datasets/blastchar/telco-customer-churn">IBM Telco Customer Churn dataset</a> — 7,043 customers, 21 features, a 26.5% churn rate. Deliberately unglamorous data, because the interesting work was never going to be in the dataset. The non-negotiables:</p><ul><li>Every model gets tracked, not just the winner</li><li>A model only ships after passing a validation gate on unseen data</li><li>Predictions need to be explainable to a non-technical stakeholder</li><li>The pipeline needs to detect staleness and respond to it</li></ul><h3>Ingestion and feature engineering</h3><p>Data lands via kagglehub, gets validated for nulls and schema drift, and is written to Delta tables — with the ingestion step itself logged as an MLflow run. Easy to skip, easy to regret: six months into a real project, &quot;which data version trained this model?&quot; is a question you will get asked.</p><p>Five engineered features sit on top of the raw columns: tenure buckets (churn risk is sharply non-linear in tenure), ordinal contract encoding (contract length tracks switching cost monotonically), an add-on engagement count, and a charge-increase ratio that flags customers whose current bill exceeds their historical average — a known churn trigger.</p><p>The split was stratified 70/15/15 on churn. With a 26.5% base rate, an unstratified split can leave the test set with a meaningfully different churn rate than what the model trained against, quietly distorting every metric comparison downstream.</p><h3>Four models, one fair comparison</h3><p>I trained Logistic Regression, Random Forest, XGBoost, and LightGBM, each tuned via RandomizedSearchCV with stratified 3-fold CV, every run logged to MLflow with hyperparameters, metrics, and artifacts.</p><p>Model Val ROC-AUC Val PR-AUC <strong>LightGBM</strong> <strong>0.8510</strong> 0.6515 XGBoost 0.8480 0.6431 Logistic Regression 0.8470 0.6338 Random Forest 0.8448 0.6417</p><p>LightGBM won, but barely — all four landed within 0.006 ROC-AUC of each other. That closeness is itself informative: it meant the choice of <em>which</em> model to ship mattered less than getting the validation and deployment machinery right, which was rather the point.</p><p>I demoed mlflow.autolog() briefly for fast exploration, then switched to manual logging for the systematic comparison — autolog&#39;s metric names aren&#39;t consistent across sklearn, XGBoost, and LightGBM, and I wanted one clean comparison table.</p><h3>Validation gate and the registry pattern</h3><p>The winning model gets found by querying the MLflow experiment directly — not reused from an in-memory variable — mirroring how a real promotion stage runs independently of the training session, often hours or days later. Before promotion, the candidate is scored on the held-out test set for the first and only time, gated at test_roc_auc &gt;= 0.80. LightGBM passed at <strong>0.8373</strong>, a small, healthy gap down from its 0.8510 validation score with no overfitting red flags.</p><p>In a fully provisioned production environment, this is exactly where you’d register the model in Unity Catalog and tag it with @challenger, then promote to @champion once it clears the gate — the same alias swap lets a model-serving endpoint pick up the new version with zero downtime and zero client-side changes, since the API always resolves whichever version currently holds the @champion alias. I implemented the same validation-gate and promotion logic here using MLflow run tags and a lightweight pointer reference, so swapping in a live registry endpoint is a small, mechanical change rather than a redesign.</p><h3>Making predictions explainable</h3><p>A retention team doesn’t want to know that contract_encoded has high feature importance on average — they want to know why <em>this specific customer</em> was flagged. I used SHAP&#39;s TreeExplainer for exact Shapley values on the LightGBM champion: a global beeswarm across the full test set, and three local waterfall explanations — highest-risk customer, lowest-risk customer, and a borderline case where the model&#39;s predicted probability landed exactly at 0.500 (and got it wrong, a genuinely useful uncertainty example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*r8pFCz_P9L-HQPwhpmBlxw.png" /></figure><p>Top features by mean |SHAP| value:</p><ol><li>contract_encoded — 0.776</li><li>tenure — 0.376</li><li>OnlineSecurity_No — 0.250</li><li>InternetService_Fiber optic — 0.177</li></ol><p>The top two features alone outweigh the next six combined — not just a modeling footnote, but an actionable recommendation. A retention strategy targeting <em>new, month-to-month customers</em> specifically addresses both dominant churn drivers in one motion.</p><h3>Manufacturing drift on purpose</h3><p>Real data drift is slow and rare — a bad thing to test a monitoring pipeline against. So I simulated a “six months later” scenario on a fresh copy of the training data: a 15% pricing increase, a promo-driven shift toward shorter tenure, and a mix shift toward month-to-month contracts. This mirrors the synthetic-injection pattern used by Evidently AI and Databricks’ own MLOps references to validate monitoring logic before it’s needed for real.</p><p>PSI and a Kolmogorov-Smirnov test on each numeric feature caught it cleanly:</p><p>Feature PSI Flag charge_increase_ratio 4.330 SEVERE MonthlyCharges 1.009 SEVERE tenure 0.192 MODERATE contract_encoded 0.058 OK</p><p>This triggered an automatic retrain on the combined original-plus-drifted data:</p><p>Model ROC-AUC, reference test ROC-AUC, drift batch v1 (pre-drift champion) 0.8373 0.8469 v2 (retrained) 0.8375 <strong>0.9327</strong></p><p>v2 gained +0.086 ROC-AUC on the drifted population with essentially zero regression on the original test set — the textbook signature of a successful retrain — and promoted itself to champion automatically, with full lineage preserved back to v1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzXehIHJxRUEmksJ_LTZcQ.png" /></figure><p>One nuance worth flagging: v1 actually performed <em>slightly better</em> on the drift batch than on its own reference test set, despite PSI screaming “severe drift.” PSI is a population-stability signal, not a performance signal — it tells you the input distribution moved, not that the model necessarily got worse. The explicit before/after performance comparison is what actually justified the retrain decision here, not the PSI flag in isolation.</p><h3>The part that ships value</h3><p>Everything before this stage builds and maintains a model. The batch scoring notebook is the only one that uses it — reading the champion reference fresh on every execution (so a new promotion from the drift stage is picked up with zero code changes), scoring customers, bucketing them into High/Medium/Low risk tiers, and writing predictions to Delta with full lineage.</p><p>This notebook is also wired into a scheduled Databricks job — seven tasks chained with proper dependencies (SHAP and drift detection run in parallel, since both only depend on a champion existing; batch scoring waits on both). Currently paused, since this is a portfolio demonstration rather than a live system, but fully configured for a daily run.</p><h3>What I’d take into a real project</h3><p>The close four-way model comparison was more informative than a clear winner would have been — it meant the project’s narrative couldn’t lean on “I found the best algorithm,” and had to lean on the lifecycle around the algorithm instead, which was the actual goal from the start.</p><p>Synthetic drift injection is a legitimate engineering choice, not a shortcut. The production pattern used by tools built for exactly this problem is to inject drift deliberately so you can prove your monitoring works <em>before</em> you need it to work for real.</p><p>Full code, all seven notebooks, the job configuration, and the project writeup are in the repo: <a href="https://github.com/Ajay-Deshpande/churn-ops"><strong>github.com/Ajay-Deshpande/churn-ops</strong></a>.</p><p><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418">If causal inference is more your interest, I also wrote about A/B testing, DiD, PSM, and Double ML — check it out.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649e6aa5dc6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Causal Inference at Scale: A Comparative Study with DoWhy and EconML]]></title>
            <link>https://ajay-deshpande.medium.com/causal-inference-at-scale-a-comparative-study-with-dowhy-and-econml-64a8f6cdbb73?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a8f6cdbb73</guid>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Sun, 14 Jun 2026 00:11:56 GMT</pubDate>
            <atom:updated>2026-06-14T00:11:56.511Z</atom:updated>
            <content:encoded><![CDATA[<p>This is Part 9 — the capstone — of the Applied Causal Inference series.<br><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers the framing and basics</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 — covers Difference-in-Differences</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9">Part 4 — covers Propensity Score Matching</a><br><a href="https://medium.com/@ajay-deshpande/inverse-probability-weighting-reweighting-instead-of-discarding-fb37c42abdee">Part 5 — covers Inverse Probability Weighting</a><br><a href="https://ajay-deshpande.medium.com/synthetic-control-building-a-counterfactual-state-439999eb4583">Part 6 — Synthetic Control: Building a Counterfactual State</a><br><a href="https://ajay-deshpande.medium.com/regression-discontinuity-the-value-of-a-threshold-14ca410b6da0">Part 7 — Regression Discontinuity: The value of a Threshold</a><br><a href="https://ajay-deshpande.medium.com/double-ml-partialling-out-confounders-with-gradient-boosting-91affa996dca">Part 8 — Double ML: Partialling Out Confounders with Gradient Boosting</a></p><p>This part is different: one dataset, two questions, seven methods, compared side by side.</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/Causal%20Inference%20Capstone.py"><em>Full notebook</em></a></p><p>- -</p><p><strong>What this phase actually produced</strong></p><p>Every prior phase in this series picked one method, one estimand, one dataset, and reported one number. This phase breaks that format on purpose.</p><p>The dataset: 401(k) eligibility, n = 9,915, from Chernozhukov et al. (2018) — the paper that introduced the Double ML method used in Phase 8 of this series. Treatment is employer-provided 401(k) eligibility. Outcome is net total financial assets.</p><p>Two questions, answered simultaneously: the average effect across the whole population (ATE), and the average effect on people who are actually eligible (ATT).</p><p>Seven methods, compared: DoWhy’s backdoor regression, EconML’s LinearDML and NonParamDML, CausalForest, and three MetaLearners (S, T, X).</p><p>The naive comparison — just take the mean difference in assets between eligible and ineligible workers — gives $19,559. The benchmark from the original paper is approximately $9,000. The naive number is more than double the truth. Across the seven methods, the mean ATE is $7,594 (84% of benchmark) and the mean ATT is $9,166. Six of the seven methods land within $874 of each other for ATE. The seventh — DoWhy’s backdoor regression — gives $5,028, and the reason why is the most interesting result in this phase.</p><p>These are the honest results.</p><p>- -</p><p><strong>The dataset, and why this one</strong></p><p>The 401(k) dataset has three properties that make it the right choice for a capstone, all absent from LaLonde (used in Phases 3 through 7).</p><p>It is large. 9,915 observations versus LaLonde’s 614. Large enough that heterogeneous effect estimation — CausalForest, the new method in this phase — is credible rather than noise.</p><p>It has genuine overlap. A logistic propensity model on the seven covariates gives AUC = 0.699 and an effective sample size of 86.0% after weighting. Compare to LaLonde’s CPS-3 control group: AUC = 0.916, ESS = 41.9%. Every method in this phase operates on a population where treated and control units genuinely resemble each other.</p><p>It has a known answer. Chernozhukov et al. (2018) report an ATE around $9,000. This gives every method in this phase something concrete to be measured against, the way LaLonde’s RCT benchmark of $1,794 anchored Phases 3 through 7.</p><p>Income is the dominant confounder. The standardised mean difference for income between eligible and ineligible workers is 0.620 — by far the largest imbalance of the seven covariates. Education (0.314), two-earner status (0.340), and IRA participation (0.278) also exceed the 0.1 threshold that signals meaningful imbalance. Higher-income workers are more likely to have access to an employer-sponsored plan, and higher-income workers save more regardless. This is the confound every method in this phase has to remove.</p><p>- -</p><p><strong>Two questions</strong></p><p>ATE: what is the effect of 401(k) eligibility on financial assets for a randomly drawn person in this population? This is the question a policymaker asks when considering making eligibility universal — the relevant counterfactual is the whole population.</p><p>ATT: what is the effect for workers who are actually eligible? This is the question an employer asks when deciding whether to keep offering a plan — the relevant counterfactual is their existing eligible workforce.</p><p>These should differ, and in this data they do. Eligible workers are higher-income on average. Higher income means more capacity to convert “you’re now eligible to save in this account” into actual additional savings. The mean ATT minus ATE gap across the six non-DoWhy methods is $1,572. ATT exceeds ATE in every one of those six. The seventh — DoWhy — reports them as identical, and that’s a finding in itself, not an oversight.</p><p>- -</p><p><strong>What works, what doesn’t, and why</strong></p><p>Before estimating anything, every method used across this series — plus the two new to this phase — was checked against this dataset.</p><p>A/B testing doesn’t apply. Eligibility isn’t randomly assigned; it’s correlated with income, employer size, and industry. No randomization occurred.</p><p>Difference-in-Differences doesn’t apply. This is a single cross-section. DiD needs a pre-treatment period and a control group observed before and after — there’s no time dimension here.</p><p>Synthetic Control doesn’t apply. It needs a panel of donor units — states, firms, regions — to construct a weighted counterfactual. This is individual-level survey data; there’s no donor panel.</p><p>Regression Discontinuity doesn’t apply. RDD needs a continuous running variable with a threshold that determines treatment. 401(k) eligibility is an employer-level binary decision, not a score cutoff.</p><p>Propensity Score Matching applies marginally. Overlap is much better here than in LaLonde (AUC 0.699 vs 0.916), but with seven continuous covariates, nearest-neighbor matching in high-dimensional space produces lower-quality matches than reweighting or residualisation approaches. At larger scales — hundreds of thousands of observations — PSM becomes computationally impractical and match quality degrades further. Not implemented here; DML and CausalForest dominate it on this data.</p><p>Inverse Probability Weighting applies, and is used as DoWhy’s baseline adjustment. ESS of 86% means reweighting doesn’t collapse the effective sample the way it did with LaLonde’s CPS controls.</p><p>DML, CausalForest, and the MetaLearners all apply — large N, a continuous skewed outcome, and nonlinear confounding by income are exactly the conditions these methods are built for. CausalForest in particular needs enough observations per region of covariate space to estimate local effects reliably; LaLonde’s n=614 was too small for this, n=9,915 is not.</p><p>DoWhy’s backdoor approach applies and is the conceptual anchor: a directed acyclic graph declares all seven covariates as confounders of both eligibility and assets, the backdoor criterion identifies the adjustment set, and the resulting estimate is refutation-tested.</p><p>- -</p><p><strong>DoWhy: the identification was right, the estimator wasn’t</strong></p><p>DoWhy’s backdoor estimator returned $5,028 for ATE — and $5,028 for ATT as well, identical to four decimal places. Three refutation tests were then run on this estimate.</p><p>A placebo treatment test replaces the real treatment variable with a randomly permuted one and re-estimates. If the method is finding a real signal, this should collapse toward zero. It did: from $5,028 to $249.</p><p>A random common cause test adds an irrelevant random variable as an additional confounder and re-estimates. A robust method shouldn’t move much. It didn’t: $5,026, essentially unchanged.</p><p>A data subset test re-estimates on 80% of the data. The result was $5,028 — identical to the full-sample estimate.</p><p>All three passed. The identification strategy — condition on these seven covariates to block the backdoor paths from eligibility to assets — is sound.</p><p>And yet $5,028 is the lowest of all seven ATE estimates, recovering 56% of the $9,000 benchmark, well below DML’s 91%. Here’s why. DoWhy’s backdoor estimator in this configuration is linear regression: one coefficient on the treatment variable, assumed to be the same number for everyone. Income’s relationship to both eligibility and assets is not linear — a linear model can only partially capture it, and the unexplained nonlinearity gets absorbed into the treatment coefficient, pulling it toward zero. This is also exactly why ATE and ATT come out identical: a single linear coefficient has no way to represent two different population averages. There is only one number to give, so the same number gets given for both questions.</p><p>The refutation tests checked whether the <em>*adjustment set*</em> was correct. They are silent on whether the <em>*functional form*</em> was correct. Both checks matter, and this dataset is a clean illustration of a result that passes the first and fails the second.</p><p>- -</p><p><strong>DML: same machine, better conditions</strong></p><p>LinearDML and NonParamDML are the same Robinson partialling-out estimators from Phase 8 — GBM nuisance models, 5-fold cross-fitting, Neyman-orthogonal scores — applied here to a dataset where the conditions are far more favourable.</p><p>LinearDML: ATE = $8,185, 95% CI [$6,235, $10,135], recovering 90.9% of benchmark. ATT = $10,716, 95% CI [$8,801, $14,043]. NonParamDML: ATE = $8,052 (89.5% recovery), ATT = $10,312.</p><p>Both confidence intervals are well clear of zero. Compare this to Phase 8’s LaLonde result, where the identical machinery produced an ATT of $1,499 with a CI of [−$492, $3,519] — crossing zero. The method didn’t change. The data did. n=9,915 versus n=614, AUC=0.699 versus AUC=0.916. DML’s machinery was correct in both phases; what changed was whether the underlying estimation problem was well-posed to begin with.</p><p>- -</p><p><strong>The new concept: CausalForest and CATE</strong></p><p>Every method so far in this series — across eight phases — produces a single number per estimand. CausalForest produces a number for every individual: tau(X_i), the conditional average treatment effect given that person’s age, income, education, family size, marital status, two-earner status, and IRA participation.</p><p>CausalForest’s headline numbers: ATE = $8,369, ATT = $11,238 — both consistent with the DML cluster. But the distribution behind that ATE is the real finding. Mean $8,369, median $5,662 — a large gap between mean and median that signals strong right skew. Standard deviation $9,605. The 10th percentile is $642; the 90th percentile is $20,831. Most workers see a modest effect from eligibility. A smaller group sees an effect more than thirty times larger.</p><p>Feature importance attributes 77.5% of this heterogeneity to income alone. Age is a distant second at 12.3%; every other covariate is below 6%.</p><p>This has a straightforward interpretation. A worker with little disposable income can’t turn “you’re now eligible to contribute to this account” into materially more savings — there’s nothing in the budget to redirect. A higher earner with slack has somewhere to put it. The treatment effect isn’t one number that everyone shares with some noise around it. It’s a function of income, and CausalForest is the first method in this series built to recover that function rather than average it away.</p><p>One important caveat. CausalForest’s analytic confidence interval for ATE is [−$8,550, $25,288] — enormous, and it crosses zero despite the point estimate of $8,369 sitting comfortably with every other method. This is a known property of forest-based analytic inference: variance estimates from individual tree leaves can be very large even when the aggregate point estimate is stable. CausalForest’s ATT, computed via bootstrap instead, is tight: [$9,053, $14,000]. The lesson isn’t that CausalForest’s ATE is unreliable — it’s that analytic and bootstrap confidence intervals from the same model can disagree substantially, and reporting only one of them can be misleading in either direction.</p><p>- -</p><p><strong>MetaLearners: S, T, and X</strong></p><p>S(ingle)-Learner — one model, treatment as a feature: ATE = $7,495, ATT = $8,183. The ATT−ATE gap is $688, the smallest of any method. This is consistent with the S-Learner’s known tendency to shrink heterogeneity toward zero when the treatment variable has a weaker signal than the covariates do — exactly the situation here, where income dominates.</p><p>T(wo)-Learner — two separate models, one per group: ATE = $8,011, ATT = $9,132.</p><p>X(Cross)-Learner — cross-imputation, designed for imbalanced groups: ATE = $8,015, ATT = $9,552. With 5,908 eligible and 4,007 ineligible workers, the imbalance here is moderate rather than severe, and X-Learner’s result sits closest to the DML and CausalForest cluster among the three MetaLearners.</p><p>- -</p><p><strong>Putting it together</strong></p><p>Six of seven methods for ATE: $7,495, $8,011, $8,015, $8,052, $8,185, $8,369. A band of $874. All within 17% of the $9,000 benchmark. DoWhy’s $5,028 sits well outside that band — not because its identification was wrong, but because its functional form couldn’t represent the heterogeneity that the other six methods, each in a different way, could.</p><p>For ATT, the spread is wider: $8,183 to $11,238 among the flexible methods, with DoWhy again the outlier at $5,028. This wider spread is itself informative — ATT is more sensitive to how a method handles heterogeneity, because the treated subpopulation (higher income on average) is exactly where CausalForest’s CATE function says the effect is largest.</p><p>The naive estimate was $19,559. Confounding by income alone explains roughly half of that gap — every adjusted method lands between $5,000 and $11,500. But getting the confounding right wasn’t sufficient on its own. DoWhy’s backdoor regression correctly identified the causal structure, passed three refutation tests, and still underestimated the effect by 44%, because it assumed the same number applied to everyone. It doesn’t. CausalForest’s CATE distribution — $642 at the 10th percentile, $20,831 at the 90th — is closer to the honest answer to “what is the effect of 401(k) eligibility”: it depends who you ask.</p><p>- -</p><p><strong>Eight phases, three lessons</strong></p><p>This series started with A/B testing — the gold standard, where randomisation does all the work — and ended with a comparative study where seven methods, none of them randomisation, converge on an answer the naive comparison missed by a factor of two.</p><p>Identification precedes estimation. Phase 8’s Full CPS result — DML producing p=0.020 on a dataset with AUC=0.977 and an effective sample size of 2.3% — was the starkest version of this lesson: no estimator, however sophisticated, fixes a population that doesn’t overlap. This phase’s good overlap (AUC=0.699, ESS=86%) is precisely what let six different methods converge.</p><p>The estimand is a choice, not a default. Every phase from 3 through 8 targeted ATT for comparability with LaLonde’s RCT. This phase is the first to compute both ATE and ATT side by side on the same data, and the $1,572 average gap between them is the clearest demonstration in the series that “the effect” is not a single well-defined quantity until you specify the effect on whom.</p><p>Convergence is evidence; divergence is a question. When DML, CausalForest, and the MetaLearners agree within $874 despite making different assumptions about functional form, that agreement carries more weight than any individual confidence interval. When DoWhy diverges, the question isn’t which number is right — both its identification and its arithmetic were correct — but which assumption (constant effects) the divergence reveals as false.</p><p>- -</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full code and outputs</em></a></p><p><em>This concludes the Applied Causal Inference series — eight methods, eight datasets, two estimands, and one consistent finding: the right answer depends on what you’re willing to assume, and the data will tell you when those assumptions don’t hold.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a8f6cdbb73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Double ML: Partialling Out Confounders with Gradient Boosting]]></title>
            <link>https://ajay-deshpande.medium.com/double-ml-partialling-out-confounders-with-gradient-boosting-91affa996dca?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/91affa996dca</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 21:50:39 GMT</pubDate>
            <atom:updated>2026-06-10T21:50:39.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D-KbEiZ34hUJ3mqtp5PRzw.png" /></figure><p>This is Part 8 of the Applied Causal Inference series.<br><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers the framing and basics</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 — covers Difference-in-Differences</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9">Part 4 — covers Propensity Score Matching</a><br><a href="https://medium.com/@ajay-deshpande/inverse-probability-weighting-reweighting-instead-of-discarding-fb37c42abdee">Part 5 — covers Inverse Probability Weighting</a><br><a href="https://ajay-deshpande.medium.com/synthetic-control-building-a-counterfactual-state-439999eb4583">Part 6 — Synthetic Control: Building a Counterfactual State</a><br><a href="https://ajay-deshpande.medium.com/regression-discontinuity-the-value-of-a-threshold-14ca410b6da0">Part 7 — Regression Discontinuity: The value of a Threshold</a></p><p>This part covers Double Machine Learning — flexible nuisance models, cross-fitting, PLR estimator and Neyman-orthogonal scores.*</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/DoubleML.py"><em>Full notebook</em></a></p><p>- -</p><p><strong>What this phase actually produced</strong></p><p>Same dataset as Phases 3, 4, and 5: LaLonde (1986) job training data, 185 treated workers, 429 CPS-3 controls. <br>True ATT from the RCT: $1,794.</p><p>DML ATT = $1,499. Recovery: 83.6%. <br>95% bootstrap CI: [−$492, +$3,519]. <br>t = 1.53. p = 0.127. <strong><em>CI crosses zero.</em></strong></p><p>The point estimate is the best in the series. The uncertainty is honest.</p><p>A propensity trimming robustness check (three thresholds: 0.05, 0.10, 0.15) confirmed that the point estimate is stable — all trimmed results within 2% of $1,499 — and that the CI crosses zero at every threshold. Sample size is the binding constraint.</p><p>The Full CPS path produced ATT = $1,846, SE = $795, p = 0.020. It looks better. It is not. Explained below.</p><p>These are the honest results.</p><p>- -</p><p><strong>Why AIPW failed</strong></p><p>Phase 4’s AIPW estimated ATT = $476 — worse than raw IPW’s $1,212. The method is theoretically doubly robust: if either the outcome model or the propensity model is correctly specified, the estimator is consistent. The problem was that both were given the wrong tool for the job.</p><p>The outcome model was OLS. The outcome variable is 1978 earnings: right-skewed, with a mass at zero and a long right tail from a handful of workers with high earnings. OLS assumes a linear, homoscedastic conditional mean. It predicted negative earnings for some workers. It systematically underfit the right tail. The doubly-robust augmentation term, which is supposed to correct for propensity misspecification, instead amplified the outcome misspecification. ATT fell from $1,212 to $476.</p><p>The diagnosis is not that doubly-robust methods are unreliable. It is that they require well-specified models, and OLS is not well-specified for heavily skewed earnings.</p><p>DML fixes this by replacing linear nuisance models with gradient boosting, and by changing the structure of the estimator so that nuisance misspecification has only a second-order effect.</p><p>- -</p><p><strong>The Robinson estimator</strong></p><p>Robinson (1988) proposed a clean solution to the partially linear regression problem:</p><p>Y = theta * D + g(X) + epsilon</p><p>D = m(X) + v</p><p>where g(X) captures how covariates affect earnings and m(X) = E[D|X] is the propensity score. The causal effect theta is the coefficient on treatment after partialling out X from both sides.</p><p>Partialling out means computing residuals:</p><p>Y~ = Y − E[Y|X]</p><p>D~ = D − E[D|X]</p><p>Ytilde is the variation in earnings not explained by the covariates. D~ is the variation in treatment assignment not explained by the covariates. Any shared variation in Y~ and D~ must be causal — the confounders are gone. Regressing Y~ on D~ (no intercept, since both are mean-zero by construction) recovers theta.</p><p>The insight is that you can use any model for E[Y|X] and E[D|X] — you are not constrained to OLS. Use gradient boosting. Use a random forest. Use whatever fits the data. The residuals carry the identification regardless.</p><p>- -</p><p><strong>## Cross-fitting and why it matters</strong></p><p>If you fit E[Y|X] and E[D|X] on the same observations you then use to compute theta, you introduce overfitting bias. A GBM model will partially memorise individual residuals, shrinking Y~ and D~ toward zero and biasing the slope estimate downward.</p><p>Cross-fitting prevents this. With K = 5 folds: fit E[Y|X] and E[D|X] on folds 2–5, predict on fold 1. Repeat for each fold. Every observation’s nuisance prediction is out-of-sample. The final Y~ and D~ vectors are free of in-sample overfitting.</p><p>Per-fold diagnostics: mean outcome RMSE $7,179, mean propensity AUC 0.916, stable across all five folds. Residual means near zero (Y~ : −$73, <br>D~ : 0.008). The nuisance models are well-behaved.</p><p>The Neyman-orthogonal score adds a further guarantee. The score function for theta has a zero derivative with respect to small perturbations in the nuisance functions at their true values. This means first-order errors in E[Y|X] and E[D|X] cancel out of the influence function — they affect theta only at second order. GBM nuisance models converge at slower than parametric rates; Neyman orthogonality ensures that doesn’t prevent theta from achieving the standard parametric rate.</p><p>- -</p><p><strong>From ATE to ATT</strong></p><p>The base Robinson estimator recovers ATE — the population-average treatment effect. Our estimand throughout the series is ATT — the effect on workers who actually received training.</p><p>To target ATT, reweight the moment condition by e(X) = P(D=1|X):</p><p>theta_ATT = sum[ e(X_i) * Dtilde_i * Ytilde_i ] / sum[ e(X_i) * Dtilde_i² ]</p><p>e(X) up-weights observations in regions of covariate space where treated workers live. Control workers with very low propensity scores — who look nothing like treated workers — receive near-zero weight. The moment condition focuses on the treated subpopulation.</p><p>This is exactly the same weighting logic as Phase 4’s IPW: use propensity scores to make the comparison group look like the treated group. The difference is that DML builds the weighting directly into an orthogonalised moment condition rather than applying it to raw outcomes. Standard errors are computed via the weighted sandwich formula and confirmed by 500-draw bootstrap.</p><p>- -</p><p><strong>Results</strong></p><p>DML ATT = $1,499. SE = $983. <br>95% CI: [−$492, +$3,519]. <br><strong><em>p = 0.127.</em></strong></p><p>The confidence interval is wide. It <strong><em>crosses zero</em></strong>. A frequentist would fail to reject the null. Let’s put that in context.</p><p>PSM (Phase 3): ATT ≈ $300. CI: [−$1,819, +$2,064]. Recovery 17%. PSM required trimming 55% of treated units to achieve borderline overlap and still produced a near-zero point estimate.</p><p>IPW trimmed (Phase 4): ATT = $1,212. CI: [−$141, +$2,718]. Recovery 68%. Required propensity trimming and still barely escaped a CI crossing zero.</p><p>AIPW (Phase 4): ATT = $476. CI: [−$1,132, +$2,084]. Recovery 27%. The doubly-robust estimator actively worsened the result by amplifying OLS misspecification.</p><p>DML ATT = $1,499. Recovery 83.6%. The best point estimate in the series. The CI is wide because 185 treated workers and 429 controls with AUC 0.916 is a hard estimation problem. That was always true — DML did not create the uncertainty, it measured it correctly.</p><p>- -</p><p><strong>The Full CPS precision trap (Risky Pitfall)</strong></p><p>We also ran DML on the Full CPS dataset — 185 treated workers and 15,992 controls. The result: ATT = $1,846, SE = $795, p = 0.020. Significant. Closer to the benchmark.</p><p>A researcher without overlap diagnostics would choose this result. That would be a mistake, and it illustrates one of the more insidious failure modes in applied causal inference.</p><p>With 15,992 controls from the general population, GBM near-perfectly separates the groups: AUC = 0.977. Every control worker looks nothing like a treated worker. The GBM propensity model assigns e(X) ≈ 0 to almost all of them. In the propensity-weighted PLR moment, near-zero e(X) means near-zero contribution — the same ESS collapse that broke Phase 4’s IPW, now hidden inside a different formula.</p><p>The effective sample size after weighting: 375 of 16,177 observations (2.3%). The identification work is being done by 375 control workers near the overlap boundary. Mean |D~| = 0.013 for Full CPS vs 0.194 for CPS-3 — the treatment residual signal is 15 times weaker.</p><p>So why does the SE shrink? The sandwich SE formula has N in the denominator. Full CPS has N = 16,177 vs CPS-3’s N = 614 — a 26x difference. The N advantage more than compensates for the 15x signal disadvantage, and the SE falls even though the identification is collapsing. The t-statistic rises above 2. The p-value crosses 0.05.</p><p>The significant result is precise about the wrong thing: a non-representative boundary stratum of controls, not the treated subpopulation. CPS-3 ESS = 257 of 614 (41.9%) — a much healthier fraction, drawn from a control group that was specifically selected for demographic similarity to the treated workers. Its p = 0.127 reflects genuine uncertainty, not a diagnostic failure.</p><p>The general lesson: large N does not fix poor overlap. It can mask it. When the effective sample size is 2.3% of the nominal N, every diagnostic number that depends on N — the SE, the t-statistic, the p-value — is misleading. The correct checks are AUC, mean |D~|, and ESS, not sample size.</p><p>- -</p><p><strong>## Propensity trimming: confirming the result</strong></p><p>Given the wide CI, the natural question is whether trimming low-propensity observations improves precision. We trimmed at e(X) ≥ 0.05, 0.10, and 0.15 and re-ran PLR ATT.</p><p>Point estimates: $1,496, $1,527, $1,486. All within 2% of the untrimmed $1,499. The trimmed observations were already receiving near-zero propensity weight in the moment condition — removing them changed nothing about the estimate. They were adding noise, not signal.</p><p>The CI crossed zero at every threshold. Trimming did not rescue the result, and it was not supposed to. The goal was confirmation: if the point estimate is driven by low-propensity noise, trimming should move it. It did not. The $1,499 estimate is stable.</p><p>This is the correct use of a robustness check. Not to find a threshold that produces a significant result. To verify that the reported result is not an artifact of a modelling choice.</p><p>- -</p><p><strong>What this teaches</strong></p><p>GBM is the right tool for skewed outcomes. OLS is a parametric model with specific assumptions about the error distribution. When those assumptions are badly violated — mass at zero, long right tail — the model misfits and any estimator built on it inherits the misspecification. Gradient boosting makes no distributional assumptions. It fits conditional means nonparametrically. For earnings data, this matters.</p><p>Neyman orthogonality is not just theory. The reason DML can use flexible nonparametric nuisance models and still recover parametric convergence rates for theta is the orthogonality property. Without it, the slower convergence of GBM would contaminate the causal estimate. Cross-fitting handles in-sample overfitting; orthogonality handles the speed-of-convergence problem. Both are necessary.</p><p>Significance is not identification. Full CPS produced p = 0.020. CPS-3 produced p = 0.127. If you use the p-value to choose between them, you select the wrong result. The correct selection criterion is overlap quality: AUC, ESS, and mean |D~|. Identification precedes inference.</p><p>The CI tells the truth. 185 treated workers, 429 controls, borderline overlap. Every method in this series has produced wide CIs on this dataset. PSM, IPW, AIPW, and now DML. DML gave the best point estimate. It also gave an honest CI. Those two facts are not in tension.</p><p>- -</p><p><strong>What happens next: Phase 8 (DoWhy + EconML — Capstone)</strong></p><p>We revised the plan and combined phase 8 and 9 into this capstone. Every phase in this series answered one question with one method on one dataset. Phase 8 breaks that formula deliberately.</p><p>The dataset is the 401(k) eligibility data — roughly 9,000 observations, real survey data, a natural treatment (eligibility for a 401k plan), and a continuous outcome (net financial assets). Enough observations that heterogeneous effect estimation is credible. A known benchmark from Chernozhukov et al. (2018) — the paper that introduced DML — to compare against.</p><p>Two estimand questions are answered simultaneously. The ATE question: what is the average effect of 401k eligibility on net financial assets across the full population? The ATT question: what is the effect on those who were actually eligible?</p><p>The structure is comparative. First, a survey of all methods that could in principle answer these questions — which ones work on this data, which ones don’t, and why. Then estimation via DoWhy (DAG-based identification, explicit assumption declaration, automated refutation tests) and EconML (DML, CausalForest, MetaLearners). The CausalForest output gives heterogeneous treatment effects — how the effect varies across individuals — something no prior phase touched. The phase closes with a comparison table across all methods and both estimands.</p><p>- -</p><p><em>Next: Phase 8 — Causal Inference at Scale: DoWhy + EconML</em></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/tree/master"><em>Full code and outputs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91affa996dca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regression Discontinuity: The Value of a Threshold]]></title>
            <link>https://ajay-deshpande.medium.com/regression-discontinuity-the-value-of-a-threshold-14ca410b6da0?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ca410b6da0</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 08:00:06 GMT</pubDate>
            <atom:updated>2026-06-06T08:00:06.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvKRJT7V8vb9SO1XgBrTgg.png" /></figure><p>This is Part 7 of the Applied Causal Inference series.</p><p>This is Part 6 of the Applied Causal Inference series.<br><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers the framing and basics</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 — covers Difference-in-Differences</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9">Part 4 — covers Propensity Score Matching</a><br><a href="https://medium.com/@ajay-deshpande/inverse-probability-weighting-reweighting-instead-of-discarding-fb37c42abdee">Part 5 — covers Inverse Probability Weighting</a><br><a href="https://ajay-deshpande.medium.com/synthetic-control-building-a-counterfactual-state-439999eb4583">Part 6 — Synthetic Control: Building a Counterfactual State</a></p><p>This part covers Regression Discontinuity Design — identification from a threshold, not a model.</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/RD.py"><em>Full notebook</em></a></p><p>- -</p><p><strong>What this phase actually produced</strong></p><p>We simulated a scholarship cutoff dataset: 2,000 students, exam scores roughly normally distributed with mean 65. Students scoring 70 or above receive a scholarship. The true Local Average Treatment Effect (LATE) embedded in the simulation is $2,500.</p><p>Local linear RD estimated LATE = $2,587. Recovery: 103.5%. 95% CI: [$2,096, $3,078]. t-statistic: 10.33. p-value: 0.000.</p><p>The naive mean difference is $6,765 — biased upward by more than $4,000 because higher-scoring students earn more regardless of the scholarship.</p><p>The McCrary density test returned p = 0.000. In a real study this would be a stop signal. Here it is a false positive from our simplified implementation — explained below.</p><p>These are the honest results.</p><p>- -</p><p><strong>A different identification strategy</strong></p><p>Every method in this series so far has handled confounding by adjusting for observed covariates — DiD via time, PSM and IPW via propensity scores, Synthetic Control via pre-treatment trajectories. All of them require some version of the assumption that observed covariates are sufficient to explain selection into treatment.</p><p>RD requires no such assumption. It exploits a threshold in a running variable that determines treatment. Students above 70 get the scholarship; students below do not. The identification assumption is much simpler: the potential outcomes E[Y(0)|X] and E[Y(1)|X] are continuous at the cutoff. Everything else — ability, family income, motivation, unobserved confounders — is allowed to vary freely, as long as it varies smoothly through score = 70.</p><p>Near the threshold, students are nearly identical. A student scoring 71 and a student scoring 69 differ in their exam result, but plausibly not in their underlying ability, motivation, or future earnings potential. The treatment — scholarship — is the only thing that changes discontinuously at 70. The jump in outcomes at that point is the causal effect.</p><p>This is the appeal of RD. You do not need to measure or model the confounders. You need to believe that nothing else jumps at the cutoff.</p><p>- -</p><p><strong>The estimand: LATE, not ATE</strong></p><p>The RD estimate is a LATE — Local Average Treatment Effect. It applies specifically to students near the threshold. A student scoring 55 might benefit much more or much less from a scholarship than a student scoring 69. RD says nothing about students far from the cutoff.</p><p>This is a genuine limitation. In exchange, you get much weaker identifying assumptions. The tradeoff is explicit: external validity for internal validity. If the policy question is about the marginal student — the one who barely qualifies — LATE is exactly the right estimand. If the question is about the average student across the whole population, RD is the wrong tool.</p><p>- -</p><p><strong>The naive estimate is badly wrong</strong></p><p>The raw mean difference in earnings between scholarship recipients and non-recipients is $6,765. The true LATE is $2,500. The bias is $4,265 — nearly twice the actual effect.</p><p>The source of the bias is transparent: exam scores predict earnings directly, through ability, effort, and learning. Students who score above 70 are systematically higher-ability students who would have earned more regardless of the scholarship. A naive comparison conflates the scholarship effect with the ability effect.</p><p>RD strips the ability effect out by comparing students within a narrow band around the threshold — where the ability distribution is effectively continuous and the only discontinuity is the scholarship assignment.</p><p>- -</p><p><strong>Bandwidth selection: the central tradeoff</strong></p><p>The bandwidth h defines the window around the cutoff used for estimation. It is the most consequential tuning choice in RD.</p><p>Narrow bandwidth: only students very close to the threshold. Low bias — the linear approximation is accurate near the cutoff. High variance — few observations.</p><p>Wide bandwidth: more students, including those far from the threshold. Low variance. High bias — the linear approximation deteriorates as you move away from the cutoff, especially if the true earnings-score relationship is nonlinear.</p><p>Cross-validation (leave-one-out MSE, evaluated separately on each side of the cutoff) selected h = 18.45 score points. This places students with scores between 51.6 and 88.5 in the estimation window: 1,082 controls and 581 treated, 1,663 of 2,000 observations total.</p><p>The Imbens-Kalyanaraman (2012) formula is an analytical alternative that estimates the optimal bandwidth via higher-order derivative estimation. In practice, CV and IK typically agree closely.</p><p>- -</p><p><strong>The estimate: local linear at h = 18.45</strong></p><p>LATE = $2,587. SE = $251. 95% CI: [$2,096, $3,078]. t = 10.33. p = 0.000.</p><p>The confidence interval is entirely above zero and well above it. The estimate recovers 103.5% of the true $2,500. The 1,663 observations in the window are sufficient to detect the effect with high precision.</p><p>Local quadratic at the same bandwidth gives $2,893. Slightly higher, wider CI. The two estimates are close enough that the local linear approximation appears adequate within h = 18.45 — the true earnings function is not severely curved in this range.</p><p>A credible RD result is stable across a range of bandwidths. The sensitivity analysis confirms this: from h = 10 to h = 30, the local linear estimates cluster near $2,500 with overlapping confidence intervals throughout. The result is not driven by the specific bandwidth chosen.</p><p>- -</p><p><strong>The McCrary test: a false positive</strong></p><p>The McCrary density test checks for a jump in the density of the running variable at the cutoff. Under no manipulation, the density should be smooth. Our implementation returned p = 0.000 — a highly significant density gap.</p><p>This is a false positive from a limitation of our simplified implementation, not evidence of manipulation. The running variable was simulated as normal(65, 12). The density is continuously declining through score = 70 — there is substantially more mass below 70 than above it simply because the distribution is centered at 65. Our bin-based local linear implementation fits separate straight lines to the bin counts on each side and measures the gap at the cutoff. With a curved density (the tails of a normal distribution), the local linear fit on each side extrapolates with different slopes to the cutoff point, producing an apparent jump that does not exist in the underlying density.</p><p>The standard McCrary test (McCrary 2008, rddensity in R) uses local polynomial density estimation that accounts for the curvature. Our simplified version does not. In a real application, use the formal implementation.</p><p>This is worth stating directly rather than presenting the result without context. The notebook documents the limitation and flags the false positive explicitly.</p><p>- -</p><p><strong>What this teaches</strong></p><p>The threshold does work that a model cannot. RD controls for all confounders — observed and unobserved — as long as they vary smoothly through the cutoff. IPW, PSM, and DiD all require assumptions about observed covariates being sufficient. RD only requires the continuity assumption. In a well-designed institutional setting — scholarship cutoffs, admission thresholds, eligibility rules — this is often more credible.</p><p>LATE is a feature, not a bug. The restricted external validity of LATE is the price of the weaker identification assumption. In many policy settings, the marginal unit near the threshold is exactly the unit of interest — the student who barely qualifies, the firm that barely meets a regulatory threshold. When the question is about the margin, LATE answers it directly.</p><p>Bandwidth sensitivity is not optional. The single most important robustness check in RD is whether the estimate changes materially as the bandwidth varies. An estimate that holds across a range of bandwidths is credible. One that depends on a specific bandwidth is suspicious.</p><p>Diagnostic tests have limits. The McCrary test is a necessary check, not a sufficient one. A non-significant McCrary result does not prove no manipulation; it means we cannot detect it statistically. Conversely, a significant result in a simplified implementation may be a false positive rather than evidence of fraud. Understanding what a test does and does not establish is as important as running it.</p><p>- -</p><p><strong>What happens next: Phase 7 (Double ML)</strong></p><p>RD returned to a simulated dataset with a clean identification strategy. Phase 7 returns to LaLonde.</p><p>In Phase 4, AIPW estimated ATT = $476 — worse than raw IPW’s $1,212. The reason: the outcome model was OLS linear regression on skewed earnings. Linear regression misfits heavily right-skewed data, and the doubly-robust augmentation amplified the misspecification error instead of correcting it.</p><p>Double ML fixes this. It replaces the linear outcome model with flexible nonlinear learners — gradient boosting, random forest — that can handle the earnings distribution. The propensity model gets the same upgrade. The result is a doubly-robust estimator where both nuisance models are well-specified, and the Neyman-orthogonal score ensures the causal estimate converges at parametric rates even though the nuisance models converge more slowly.</p><p>- -</p><p><em>Next: Phase 7 — Double ML: Flexible Nuisance Models for Causal Estimation</em></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full code and outputs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ca410b6da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synthetic Control: Building a Counterfactual State]]></title>
            <link>https://ajay-deshpande.medium.com/synthetic-control-building-a-counterfactual-state-439999eb4583?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/439999eb4583</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 23:49:54 GMT</pubDate>
            <atom:updated>2026-06-06T08:00:55.489Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Synthetic Control: Building a Counterfactual State</strong></p><p>This is Part 6 of the Applied Causal Inference series.<br><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers the framing and basics</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 — covers Difference-in-Differences</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9">Part 4 — covers Propensity Score Matching</a><br><a href="https://medium.com/@ajay-deshpande/inverse-probability-weighting-reweighting-instead-of-discarding-fb37c42abdee">Part 5 — covers Inverse Probability Weighting</a></p><p>This part covers Synthetic Control — a completely different identification strategy designed for when you have exactly one treated unit.</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/SC.py"><em>Full notebook</em></a></p><p>- -</p><p><strong>What this phase actually produced</strong></p><p>We simulated a state-level panel: 1 treated state, 20 donor states, 30 periods, policy introduced at period 21. The true embedded effect is $1,500 per period.</p><p>Synthetic Control estimated ATT = $1,521. Recovery: 101.4%. Pre-period RMSPE = $353 (1.68% of the treated state’s pre-period mean). Post/Pre RMSPE ratio = 4.36. Permutation p-value = 0.000.</p><p>Six donors received non-zero weights. Fourteen received weight zero. All three placebo-in-time tests produced near-zero effects (−$115, −$236, −$166). 19 of 20 donor placebos were valid; none came close to the treated state’s RMSPE ratio.</p><p>This is the cleanest result in the series. The method recovered the true effect almost exactly, with strong statistical evidence and clean diagnostics throughout.</p><p>- -</p><p><strong>Why a different dataset</strong></p><p>Every phase from 2 through 4 used the LaLonde job training data: 185 treated workers, hundreds of control workers, a single cross-section or short panel. The methods differed, but the data regime was the same — many treated units, many controls, estimate an average effect across individuals.</p><p>Synthetic Control is designed for the opposite regime. The canonical examples are Abadie and Gardeazabal (2003) studying the economic cost of terrorism in the Basque Country (one treated region), and Abadie, Diamond, and Hainmueller (2010) studying California’s tobacco control program (one treated state). One treated unit. A panel of potential donor units. Many pre-treatment periods.</p><p>You cannot run IPW or PSM on one treated unit. There is no distribution of propensity scores to reweight, no pool of individual-level matches to find. The individual-level framework breaks down entirely at N=1.</p><p>Synthetic Control sidesteps this by never asking for many treated units. It asks instead: can we find a weighted combination of untreated units whose pre-treatment outcome trajectory closely matches the treated unit? If yes, that weighted combination — the synthetic control — is a credible counterfactual for what the treated unit would have looked like without the intervention.</p><p>We simulate a dataset with a known true effect so we can evaluate the method’s recovery precisely, using the same principle as the LaLonde RCT benchmark in earlier phases.</p><p>- -</p><p><strong>The method: constrained quadratic programming</strong></p><p>The synthetic control is built by solving an optimization problem. Find weights W = (w₁, w₂, …, w_J) over J donor states such that the weighted pre-treatment outcome matches the treated state’s pre-treatment outcome as closely as possible.</p><p>Minimize: ||Y_treated_pre − Y_donors_pre @ W||²</p><p>Subject to: wⱼ ≥ 0 for all j, and Σwⱼ = 1.</p><p>The non-negativity and sum-to-one constraints are what separate Synthetic Control from regression. They force the synthetic state to be a convex combination of actual donor states — no negative weights, no extrapolation outside the observed data. OLS would allow negative weights, which have no meaningful interpretation as a “weighted average of states.”</p><p>Six of twenty donors received non-zero weights. The three largest — donor_16 (30.4%), donor_2 (29.8%), donor_18 (25.2%) — account for 85% of the synthetic state. The remaining 14 donors received weight zero: they add nothing to the pre-period fit that the six active donors do not already provide. This sparsity is expected and desirable. A synthetic control that spreads weight across all donors is harder to interpret and may be overfitting the pre-period noise.</p><p>A practical note: the QP solver requires scaled inputs. Raw income values in the tens of thousands cause numerical precision issues in the optimizer. Normalizing by the pre-period mean before optimization and rescaling afterward is standard practice.</p><p>- -</p><p><strong>Pre-period fit: the first diagnostic</strong></p><p>Before interpreting any post-treatment gaps, verify the pre-period fit. Pre-period RMSPE = $353. The treated state’s pre-period mean income is approximately $21,000. RMSPE as a fraction of mean: 1.68%.</p><p>That is excellent. The synthetic control is tracking the treated state within 1.7% of its typical income level over 20 pre-treatment periods. The gap series during the pre-period hovers near zero with no systematic drift.</p><p>If pre-period fit is poor — RMSPE/mean above 5% as a rough threshold, or visible drift in the pre-period gap — the synthetic control is not a credible counterfactual. The post-period divergence reflects pre-existing differences, not the treatment. The method should be questioned or the donor pool reconsidered before proceeding.</p><p>Here, the fit is clean enough to proceed with confidence.</p><p>- -</p><p><strong>The gap plot: reading the result</strong></p><p>The gap series — treated outcome minus synthetic outcome, period by period — is the core output of Synthetic Control. It should read like this:</p><p>Pre-period (t=1 to 20): gap near zero. The synthetic control is successfully tracking the treated state. No spurious pre-treatment effects visible.</p><p>Post-period (t=21 to 30): gap opens up sharply and stabilizes. Average post-period gap = $1,521. True embedded effect = $1,500.</p><p>The gap never reverts, which is consistent with a permanent policy effect rather than a temporary shock. The synthetic control continues on its pre-treatment trajectory while the treated state diverges from it. The divergence is the treatment effect.</p><p>- -</p><p><strong>Placebo-in-time</strong></p><p>We tested three placebo treatment dates within the pre-period: t=10, t=13, and t=16. For each, we fit a synthetic control using only the data before the placebo date, then measure the gap in the remaining pre-period.</p><p>The placebo ATTs were −$115, −$236, and −$166. All three are small relative to the estimated $1,521 post-period effect and were flagged as ✓ small. No spurious treatment effects appear at any pre-period date.</p><p>This rules out a specific failure mode: a synthetic control that happens to diverge from the treated state regardless of the date you call treatment. Here, the divergence is concentrated at the actual treatment date, not distributed across the pre-period.</p><p>- -</p><p><strong>Placebo-in-space: inference without distributional assumptions</strong></p><p>The standard hypothesis test for Synthetic Control is permutation-based. Apply the same procedure to each donor state as if it were the treated unit, using the remaining donors as the pool. Compute the post/pre RMSPE ratio for each.</p><p>The treated state’s ratio = 4.36. The post-period gap grew to 4.36 times the pre-period noise level. The placebo distribution shows all 19 valid donor ratios clustered at low values — none came close to 4.36.</p><p>Permutation p-value = 0.000. Zero of 19 placebos achieved a ratio as large as the treated state.</p><p>One donor was excluded from the placebo distribution: its pre-period RMSPE exceeded twice the treated state’s pre-period RMSPE. Donors that cannot be fit well are excluded because they would inflate the placebo distribution artificially — a donor with poor pre-fit will naturally produce high post/pre ratios regardless of treatment.</p><p>A p-value of 0.000 here should be read as “p &lt; 1/20 = 0.05” given 19 valid placebos. The exact interpretation: if the treatment had no effect, the probability of observing a ratio this extreme by chance is less than 1 in 20. With a ratio of 4.36 against a placebo maximum that is substantially lower, the evidence is unambiguous.</p><p>- -</p><p><strong>What this teaches</strong></p><p>Synthetic Control makes the counterfactual visible. The synthetic state is not an abstract statistical adjustment. It is a named, weighted combination of real states — donor_16, donor_2, donor_18 and three others — that together replicate the treated state’s pre-treatment history. You can look at those six states and ask whether they make sense as a comparison group. That interpretability is unusual in causal inference.</p><p>Inference requires no distributional assumptions. The permutation test makes no claim about the error distribution, normality, or independence across time. It asks one question: is the treated state’s post/pre RMSPE ratio unusual relative to what happens when you apply the same method to units that definitely were not treated? With p=0.000, the answer is unambiguous.</p><p>The method has hard limits. Synthetic Control was designed for N=1 and degrades with multiple treated units — though extensions exist (augmented SC, staggered adoption SC). It requires a long pre-treatment period to establish a reliable counterfactual trajectory. And it cannot extrapolate beyond the convex hull of the donor pool: if the treated state is extreme on some dimension, no convex combination of donors can match it, and the pre-period fit will be poor. These are design constraints, not bugs.</p><p>- -</p><p><strong>What happens next: Phase 6 (Regression Discontinuity)</strong></p><p>Synthetic Control required a long pre-treatment time series and a panel of donor units. Its identification rests on the parallel pre-treatment trajectory.</p><p>Regression Discontinuity requires neither. It exploits a sharp discontinuity in treatment assignment: units just above a threshold receive treatment, units just below do not. The identifying assumption is that units near the threshold are otherwise comparable — they differ only in which side of the cutoff they fall on, which is effectively random near the boundary.</p><p>We simulate a scholarship cutoff dataset: students who score just above a threshold receive a scholarship; students just below do not. The estimand is LATE — the Local Average Treatment Effect at the threshold. The effect may differ substantially for students far from the cutoff.</p><p>- -</p><p><a href="https://ajay-deshpande.medium.com/regression-discontinuity-the-value-of-a-threshold-14ca410b6da0"><em>Next: Phase 6 — Regression Discontinuity: The Value of a Threshold</em></a></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full code and outputs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439999eb4583" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inverse Probability Weighting: Reweighting Instead of Discarding]]></title>
            <link>https://ajay-deshpande.medium.com/inverse-probability-weighting-reweighting-instead-of-discarding-fb37c42abdee?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb37c42abdee</guid>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Sun, 31 May 2026 04:35:05 GMT</pubDate>
            <atom:updated>2026-05-31T04:35:05.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5bxkSergirxE0-SZB-8Gg.png" /></figure><p>Part 5 of the Applied Causal Inference series — IPW, AIPW, doubly-robust estimation, and honest results on the LaLonde dataset<br><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers the framing and basics</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 — covers Difference-in-Differences</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9">Part 4 — covers Propensity Score Matching</a></p><p>This part covers Inverse Probability Weighting — and why keeping all the data doesn’t automatically get you a better answer.</p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/IPW.py"><em>Full notebook</em></a></p><p>- -</p><p><strong>What this phase actually produced</strong></p><p>The LaLonde job training dataset has a known true effect of $1,794. PSM on the CPS-3 control group gave $123–$468 on 83 matched pairs. The CI crossed zero. The result was statistically inconclusive.</p><p>IPW on the same CPS-3 group gave ATT = $1,212. 95% CI: approximately −$141 to +$2,718. The CI still clips zero at the lower end, but the point estimate is substantially closer to $1,794, and the interval is meaningfully narrower than PSM’s.</p><p>IPW on the full CPS group gave ATT = −$1,021. Wrong sign. The Full CPS ATT from AIPW is −$4,264. Also, wrong sign, with a tight CI that excludes zero on the wrong side.</p><p>The AIPW doubly-robust estimate on CPS-3 gave ATT = $476 — worse than raw IPW on the same dataset.</p><p>These are the honest results. The rest of this article explains what each finding means and why it happened.</p><p>- -</p><p><strong>Why ATT and not ATE</strong></p><p>IPW is often described as naturally estimating the ATE — the average treatment effect across the full population. That framing comes from the survey sampling literature, where the Horvitz-Thompson (1952) estimator was designed for population-level inference. It carried into causal inference and became the default description.</p><p>But for this problem, ATE is the wrong estimand. The LaLonde RCT benchmark of $1,794 is an ATT: the effect on workers who actually enrolled in NSW job training. ATE would measure the effect if training were extended to the full CPS population — workers who have different earnings histories, different demographics, and who would never realistically enroll. We have no ground truth to compare an ATE against.</p><p>ATT is the headline. ATE is computed at the end of the notebook as a secondary result with a note on what question it answers and why it cannot be benchmarked here.</p><p>The weight formula changes with the estimand. For ATE, the treated unit gets weight 1/e(X) and the control gets weight 1/(1−e(X)). For ATT, the treated unit keeps weight 1 — it is the reference population — and the control gets weight e(X)/(1−e(X)), which measures how “treated-like” the control worker is. A control worker who looks very similar to the treated group gets a high weight. A control worker who looks nothing like the treated group gets a weight near zero.</p><p>- -</p><p><strong>The core idea and where it improves on PSM</strong></p><p>PSM and IPW use the same propensity model — logistic regression on the same eight covariates. The difference is entirely in what happens after the scores are computed.</p><p>PSM finds the nearest control for each treated worker and discards any treated worker without a close-enough match. On CPS-3, that meant dropping 102 of 185 treated workers. The 83-pair matched sample was too small and too noisy to detect a $1,794 signal.</p><p>IPW keeps every treated worker. Instead of requiring a close match, it reweights the control group so that it resembles the treated group on observed covariates. A control worker who looks like a typical NSW participant gets upweighted. A control worker who looks nothing as one gets downweighted to near zero. The treated group stays untouched at weight 1. No one is dropped.</p><p>The expected gain is direct: more treated workers mean a larger effective sample, which means narrower confidence intervals, which means more statistical power. Whether the estimates are accurate depends on whether the propensity model correctly captures the selection process — the same assumption PSM relies on.</p><p>- -</p><p><strong>Path A: Full CPS controls (15,992 workers) — weights explode</strong></p><p>PSM stopped at the diagnostic for the Full CPS group: AUC near 1.0, near-zero overlap; the method was flagged as inapplicable before matching began.</p><p>IPW runs anyway. That is the difference. IPW does not refuse to produce a number. But the number is worse than meaningless.</p><p>When the propensity model achieves AUC = 0.971, the treated workers have propensity scores near zero — the model says they had almost no chance of being treated given their covariates. The ATT control weight for each control worker is e(X)/(1−e(X)). With e(X) near zero for almost every CPS worker, these weights collapse toward zero across the board. The reweighted control group has almost no contribution from any single unit. The estimate is effectively the difference between the treated mean and the noise.</p><p>Raw HT weights tell the same story from the other direction. The maximum weight is 1,261 — one control worker is carrying the informational equivalent of 1,261 observations. The effective sample size (ESS) collapses to 149 out of 16,177–0.9% of the dataset. Trimming the weights recovers the ESS numerically, but deceptively: the trim bounds are [0.989, 1.007], which means trimming forced all weights to approximately 1.0. The reweighting is neutralized. Every Full CPS worker gets equal weight despite massive covariate differences from the treated group. What comes out is something close to the naive mean difference, which is −$8,498 on the Full CPS group.</p><p>The trimmed IPW ATT on Full CPS is −$1,021. AIPW is −$4,264. Both are wrong signs.</p><p>PSM’s decision to stop at the diagnostic was the right call. IPW demonstrates what happens when you don’t (last cell in the notebook).</p><p>- -</p><p><strong>Path B: CPS-3 controls (429 workers) — primary analysis</strong></p><p>CPS-3 AUC = 0.874. Borderline, same as Phase 3. Mean SMD before reweighting = 0.443.</p><p>After applying trimmed ATT weights, mean SMD drops to 0.186 — a 58% reduction. Five of eight covariates remain above the 0.1 threshold: age (0.173), black (0.328), married (0.379), re74 (0.306), re75 (0.120). Race, marital status, and prior earnings are the same variables that resisted balancing in PSM. The propensity model with linear logistic terms cannot fully bridge the structural difference between NSW participants and CPS workers.</p><p>The trimmed ATT ESS is 446 out of 614–72.6% of the dataset is contributing real information. This is healthy. No single observation is dominating.</p><p>The trimmed IPW ATT estimate is $1,212. 95% CI: [−$141, $2,718]. The CI clips zero at the lower bound, but the point estimate recovers 68% of the $1,794 benchmark using all 185 treated workers. PSM recovered at most 26% on 83 pairs.</p><p>That improvement is exactly what you would predict from the arithmetic. Increasing the effective sample from 83 to 446 shrinks the standard error substantially. The point estimate moved closer to the benchmark at the same time, likely because the reweighted control group is a better counterfactual than the 83-pair matched subset.</p><p>- -</p><p><strong>Why did AIPW perform worse than raw IPW</strong></p><p>The AIPW doubly-robust estimate on CPS-3 is $476. This is worse than trimmed IPW’s $1,212 on the same dataset.</p><p>AIPW is doubly robust: consistent if either the propensity model or the outcome regression model is correctly specified. Not both — either. If the propensity model is right, the augmentation term from the outcome model cancels out. If the outcome model is right, the propensity weighting cancels out. You have two independent lines of defense.</p><p>The outcome model here is OLS linear regression on re78. Earnings are highly right-skewed with a large spike at zero — many workers had zero earnings in the pre-training period. Linear regression fits poorly on this distribution, especially for treated workers with zero or near-zero prior earnings. The predicted values from the outcome model are systematically wrong.</p><p>When the outcome model is misspecified, the augmentation terms add noise rather than correct for propensity model errors. The result is a higher-variance estimate that moves further from the benchmark than raw IPW alone. “Doubly robust” does not mean robust to both models being wrong simultaneously. It means one must be right. Neither was.</p><p>This is not an argument against AIPW in general. It is an argument for better outcome models — which is exactly what Phase 7 (Double ML) addresses by replacing linear regression with flexible nonlinear learners that can handle skewed outcome distributions.</p><p>- -</p><p><strong>What this teaches</strong></p><p>Three things that follow directly from these results.</p><p>IPW’s advantage over PSM is real but limited by the same constraint. Keeping all 185 treated workers instead of 83 produced a substantially better estimate — $1,212 versus $123–$468, narrower CI, closer to benchmark. The mechanism is simply arithmetic: a more effective sample size means more statistical power. But IPW and PSM fail on the same datasets and for the same root reason. Full CPS fails for both. CPS-3 works for both. Overlap is the binding constraint. IPW quantifies overlap failure through ESS collapse; PSM quantifies it through discarded observations. The diagnostic is different; the failure mode is identical.</p><p>ESS is the right diagnostic for IPW, not the weight histogram. The weight distribution plot is useful for visualizing extreme tails. But ESS gives you the number that matters: how much information is actually in your weighted sample? Full CPS ESS of 149 at raw weights (0.9% of N) and the trim-to-flat behavior [0.989, 1.007] tells you everything you need to know before looking at the estimate. CPS-3 ESS of 446 (72.6%) tells you the reweighting is doing real work with a healthy, effective sample.</p><p>AIPW’s double robustness is a guarantee about model specification, not a free lunch. If your outcome model is linear regression on skewed earnings, you are not protected — you are adding a misspecified correction term to an already imperfect propensity estimate. The practical implication: invest in the outcome model. Better flexible learners reduce misspecification bias and make the doubly-robust guarantee meaningful in practice.</p><p>- -</p><p><strong>What happens next: Phase 5 (Synthetic Control)</strong></p><p>IPW is an individual-level method. It operates on 185 treated workers and a few hundred control workers, reweighting each person’s contribution to the estimate.</p><p>Synthetic Control operates at a completely different level of aggregation. Instead of individual workers, it works with aggregate units — states, countries, firms. Instead of reweighting individuals, it constructs a weighted combination of control units whose pre-treatment aggregate outcomes match the treated unit’s pre-treatment trajectory as closely as possible.</p><p>It is designed for the opposite data regime: one treated unit, many pre-treatment time periods, and a small number of donor control units. Small N, large T. The opposite of LaLonde.</p><p>We simulate a state-level panel dataset — one state that receives a policy intervention, 20 donor states that do not — to demonstrate the method on data it was actually designed for.</p><p>- -</p><p><em>Next: Phase 5 — Synthetic Control: Building a Counterfactual State</em></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full code and outputs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb37c42abdee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Propensity Score Matching: When the Method Tells You It Can’t Help]]></title>
            <link>https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c8d50384df9</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Wed, 27 May 2026 04:50:50 GMT</pubDate>
            <atom:updated>2026-05-27T19:17:49.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFmIPRDrkVGA9tOuxWapZQ.png" /></figure><p><em>This is Part 4 of the Applied Causal Inference series. <br></em><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 - covers the framing and basics.</em></a><em><br></em><a href="https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 - covers A/B testing.</em></a><em> <br></em><a href="https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56"><em>Part 3 - covers Difference-in-Differences.</em></a><em><br>This part covers Propensity Score Matching — and what happens when you run it on a dataset where it genuinely cannot work.</em></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full notebook</em></a></p><p><strong>— -</strong></p><p><strong>What this phase actually produced</strong></p><p>The LaLonde job training dataset has a known true effect of $1,794. The naive comparison of the CPS control group gives $123. The CPS control group, it gives $429. Both are wrong.</p><p>PSM on the full CPS group: correctly flagged as inapplicable. AUC near 1.0, near-zero overlap, we stopped before matching.</p><p>PSM on the similar CPS sample group: ran the full pipeline. Matched 83 of 185 treated workers. ATT estimate: $123–$468. 95% CI: approximately −$1,400 to +$2,300. The CI crosses zero. The estimate is not statistically significant.</p><p>These are the honest results. The rest of this article explains what each finding means and why it happened.</p><p><strong>— -</strong></p><p><strong>The core idea and its hard prerequisite</strong></p><p>PSM solves a specific problem: you want to compare treated and untreated units, but they differ on covariates that also affect the outcome. Direct comparison is biased. You need a comparable control group.</p><p>The Rosenbaum-Rubin theorem (1983) says you can match on a single number — the probability of treatment given covariates, p(X) = P(treat=1 | X) — and achieve balance on all covariates in expectation. Estimate this with logistic regression. Match each treated unit to the nearest control by propensity score.</p><p>The hard prerequisite: <strong>overlap</strong>. Treated and control units must share a common propensity score range. If the model can almost perfectly predict group membership from covariates, the groups are from fundamentally different populations, and no matching algorithm helps.</p><p>The AUC of the propensity model is your first diagnostic. Target range: 0.6–0.85. AUC above 0.95 is a stop signal.</p><p><strong>— -</strong></p><p><strong>Path A: Full CPS controls (15k workers) - stopped at the diagnostic</strong></p><p>The full CPS workers earn around $13,000/year pre-training on average. The treated workers earn $2,000. The two groups differ substantially on age, education, race composition, and marital status. Mean SMD across covariates: 1.087. With 15,992 control workers spanning the full population, the logistic model achieves an AUC score near 1.0 — it can almost perfectly predict who received training just from demographics.</p><p>The overlap plot shows two completely separated spikes. Treated workers cluster at propensity scores near zero. Full CPS workers cluster near 1.0. There is essentially no middle ground — the sheer size and demographic breadth of the full CPS means it contains virtually no workers who resemble the disadvantaged treated group.</p><p>We stopped here. Running the matching would have produced a number, but that number would have been meaningless — every treated worker matched to the “least different” worker from a pool of 15,992, who is still very different. That is not a counterfactual. It is a bad match that produces false precision.</p><p><strong>— -</strong></p><p><strong>Path B: Trimmed CPS-3 controls (429 workers)</strong></p><p>The CPS-3 control group (429 workers) is closer to the treated workers. Mean SMD: 0.443. AUC: 0.87. Borderline — but within the range where PSM is technically feasible. We documented the borderline status and continued.</p><p><strong>Matching: 83 pairs from 185 treated workers</strong></p><p>We used nearest-neighbor matching with a caliper of 0.2 × the standard deviation of propensity scores (Rosenbaum and Rubin, 1985). The caliper enforces a quality floor — treated workers without a CPS match within the threshold are dropped rather than matched poorly.</p><p>102 of 185 treated workers (55%) were dropped. This is the honest cost of the overlap problem. The matched sample contains 83 pairs.</p><p><strong>A note on KNN and memory at scale.</strong> Scikit-learn’s NearestNeighbors indexes the control propensity scores for lookup. In 1D — matching on propensity score alone — memory is O(n_control) and performance is fine for the LaLonde dataset. The constraint becomes real in two situations: matching on raw covariates in high dimensions rather than collapsing to a 1D propensity score (the index grows with dimensionality, search slows exponentially), and control pools with millions of observations (the full index may not fit in memory). At that scale, approximate nearest-neighbor methods — FAISS, Annoy — or stratification on propensity score deciles are the right tools. This is one reason propensity score methods are preferred over direct covariate matching: keeping the problem in 1D avoids the dimensional blowup.</p><p><strong>Balance improved — but not completely</strong></p><p>The Love plot shows mean SMD dropping from 0.443 before matching to 0.102 after — a 77% reduction. Most covariates crossed below the 0.1 threshold. Three did not: education (SMD = 0.112), re74 (0.275), and re75 (0.209). Prior earnings in particular remain meaningfully imbalanced after matching.</p><p><strong>The estimate: directionally right, statistically inconclusive</strong></p><p>Simple paired difference: $123, SE = $990, 95% CI = [−$1,819, $2,064], p = 0.90.</p><p>OLS on matched sample with covariates: $468, SE = $968, 95% CI = [−$1,431, $2,366], p = 0.63.</p><p>Both estimates are directionally positive — a meaningful improvement over the naive −$635. But both CIs cross zero by a large margin. At no conventional significance level can we confirm a positive effect.</p><p>The direction is correct. The precision is not there.</p><p><strong>— -</strong></p><p><strong>Why the CI is so wide — the arithmetic is simple</strong></p><p>83 matched pairs. Earnings standard deviation is roughly $7,000. Standard error of the paired mean difference: 7,000 / √83 ≈ $768. A 95% CI spans roughly ±$1,500 around the estimate. Given an estimate of $123, the lower bound is easily negative.</p><p>To detect an effect of $1,794 with 80% power at α = 0.05, you would need roughly 120 matched pairs with this level of outcome variance. We have 83. And those 83 pairs still carry residual imbalance on prior earnings — adding noise on top of the power shortfall.</p><p>This is not a code error. It is the honest arithmetic of what happens when you lose 55% of your sample to a caliper on a borderline-overlap dataset.</p><p><strong>— -</strong></p><p><strong>On the Rosenbaum bounds: not applicable here</strong></p><p>The notebook runs Rosenbaum sensitivity bounds but scopes them clearly: they are not interpretable for this result.</p><p>Rosenbaum bounds start from the assumption that you have a statistically significant estimate and ask how robust it is to hidden confounding. Our estimate is not significant at Γ = 1 — the baseline with no hidden bias assumed. The worst-case p-value at Γ = 1 is 0.50 and worsens from there.</p><p>This tells you nothing about hidden confounders. It tells you the estimate was already too noisy to work with. Running bounds on it and reporting them as robustness evidence would be misleading. The failure mode here is power and overlap — both observable problems — not hidden confounding, which bounds are designed to probe.</p><p><strong>— -</strong></p><p><strong>What this teaches</strong></p><p>Three things that are genuinely useful and rarely stated this directly.</p><p><strong>AUC above 0.85 is a warning, not a model quality metric</strong>. When the propensity model predicts group membership with high accuracy, the groups are incomparable. On the full CPS dataset (AUC ≈ 1.0), we stopped. On the trimmed CPS-3 dataset (AUC = 0.87), we continued with documentation. The threshold matters.</p><p><strong>Dropping unmatched workers is honest; matching them badly is not</strong>. 55% data loss is uncomfortable. But the alternative — forcing matches on workers with no comparable control, then reporting a confident ATT — would be worse. Wide confidence intervals are the method’s way of saying “the data can’t support a precise answer.” That is correct behavior.</p><p><strong>Rosenbaum bounds are a robustness tool, not a catch-all</strong>. They answer one specific question about hidden confounders. They cannot compensate for insufficient power or poor overlap. Using them to shore up a non-significant result would be misrepresentation.</p><p><strong>— -</strong></p><p><strong>What happens next: Phase 4 (IPW)</strong></p><p>PSM dropped 55% of treated workers. The matched ATT applies to a subset of the treated population — those for whom a comparable CPS match existed. The 102 dropped workers are simply excluded from the analysis.</p><p>Inverse Probability Weighting keeps all 185 treated workers and all control workers. Instead of discarding unmatched units, it reweights every observation by the inverse of its treatment probability. Treated workers with low propensity scores (who look unlikely to be treated based on covariates) receive high weights — their experience is informative precisely because they got treatment despite looking unlikely to. Control workers with high propensity scores get upweighted for the same reason.</p><p>The result is a reweighted sample that mimics a randomized experiment using all available data. IPW can estimate ATE — the effect across the full population — not just ATT on a subset. Phase 4 tests whether this approach can recover the $1,794 benchmark on the same dataset where PSM could not.</p><p><strong>— -</strong></p><p><em>Next: Phase 4 — Inverse Probability Weighting: Reweighting Instead of Discarding</em></p><p><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>Full code and outputs</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c8d50384df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference-in-Differences: When Time Becomes Your Control Group]]></title>
            <link>https://ajay-deshpande.medium.com/difference-in-differences-when-time-becomes-your-control-group-2f8f80de1c56?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8f80de1c56</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Sat, 23 May 2026 00:08:15 GMT</pubDate>
            <atom:updated>2026-05-27T04:52:04.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqHfqAB_Ntaw7DhTgCNsMA.png" /></figure><p><em>This is Part 3 of the Applied Causal Inference series. <br></em><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — covers why most data science answers the wrong question</em></a><em>. <br></em><a href="https://medium.com/@ajay-deshpande/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be"><em>Part 2 — covers A/B testing</em></a><em>. <br>This part covers what to do when you can’t randomize but have before-and-after data.</em></p><p><em>Full notebook: </em><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/DiD.py"><em>Github</em></a></p><p><strong>— -</strong></p><p><strong>The setup</strong></p><p>In 1986, economist Robert LaLonde published a paper that quietly broke a lot of data science practice.</p><p>He had data from a real job training program — the Job Training Partnership Act (JTPA). Workers were randomly assigned to receive training or not. He had the true treatment effect: $1,794 increase in annual earnings.</p><p>Then he did something clever. He threw away the randomized control group and replaced it with workers drawn from two large surveys — the Current Population Survey (CPS) and the Panel Study of Income Dynamics (PSID). These were real workers who hadn’t received training, but they’d never been randomly assigned to anything. They’d simply not enrolled.</p><p>Then he asked: if you handed this observational dataset to a data scientist and asked them to estimate the training effect, what would they get?</p><p>The answers were all over the place. Some methods returned estimates near the truth. Others returned estimates that were negative, implying training <em>hurt</em> earnings. The true effect was $1,794. The naive comparison gave numbers ranging from −$8,498 to +$2,249 depending on the comparison group and method used.</p><p>This dataset became the canonical benchmark for causal inference. It’s what we use in Phase 2.</p><p><strong>— -</strong></p><p><strong>Why the naive comparison fails so badly</strong></p><p>Before running any method, look at who enrolled in training versus who didn’t.</p><p>The PSID workers — the non-experimental control group — earned around $13,000 per year before training began. The treated workers earned around $2,000 per year. They were younger, less educated, more likely to be minorities, and more likely to be unmarried. They were economically disadvantaged in ways that went far beyond anything training could explain.</p><p>If you simply compare their 1978 earnings, you’re comparing two fundamentally different populations. The training effect is buried under a $11,000 pre-existing earnings gap. Depending on how that gap evolves, your estimate could come out anywhere.</p><p>This is selection bias in its clearest form. Workers who chose to enroll in training did so precisely because they needed it, which means they were already different from those who didn’t enroll in ways that matter for the outcome.</p><p><strong>— -</strong></p><p><strong>The DiD idea</strong></p><p>Difference-in-Differences (DiD) is a way to remove that pre-existing gap without needing randomization.</p><p>The insight is simple. Instead of comparing the <em>level</em> of earnings between groups, compare the <em>change</em> in earnings. If the control group’s earnings grew by $X between 1975 and 1978, and the treated group’s earnings grew by $X + $Y, then $Y is the training effect — the part of the change that goes above and beyond what happened to comparable workers over the same period.</p><p>Written as a formula:</p><p>&gt; <strong>DiD = (Treated earnings 1978 − Treated earnings 1975) − (Control earnings 1978 − Control earnings 1975)</strong></p><p>You’re taking two differences. The first difference removes the time trend (things that changed for everyone). The second difference removes the group-level baseline gap (the pre-existing earnings difference). What’s left is the treatment effect.</p><p>In regression form, this becomes an interaction term:</p><pre>earnings = α + β₁×Post + β₂×Treat + β₃×(Post × Treat) + ε</pre><p>`β₃` — the coefficient on the interaction — is the DiD estimate. It captures the additional change in earnings for treated workers in the post-treatment period, over and above what the control group experienced.</p><p><strong>— -</strong></p><p><strong>The load-bearing assumption: parallel trends</strong></p><p>DiD works under the assumption that you cannot test directly but can make plausible: <strong>parallel trends</strong>.</p><p>In the absence of treatment, the treated group’s earnings would have followed the same <em>trend</em> as the control group. Not the same level — they were already different. The same slope. The same year-on-year movement.</p><p>This is the dashed line in the diagram above. You never observe it. If it’s true, then whatever changed for the control group between 1975 and 1978 is a valid stand-in for what would have changed for the treated group without training. DiD subtracts exactly that.</p><p>If it’s false — if the treated group was already diverging from the control group before training happened — then DiD is removing the wrong thing, and your estimate is biased in an unpredictable direction.</p><p><strong>— -</strong></p><p><strong>Testing parallel trends</strong></p><p>You can’t test parallel trends in the post-period (treatment already happened). But you can test it in the pre-period.</p><p>We have earnings data from 1974 <em>and</em> 1975, both before training. Under parallel trends, the two groups should have moved similarly between 1974 and 1975. If they didn’t — if one group was already accelerating away from the other before any intervention — that’s a warning sign.</p><p>The test: run DiD on the 1974→1975 window only, treating 1975 as the “post” period and ignoring 1978 entirely. The interaction coefficient should be near zero and statistically insignificant. If you find a large, significant “effect” in this fake window, you’re detecting pre-existing divergence — parallel trends are questionable.</p><p>In the LaLonde data with the PSID comparison group, this test is important to look at carefully. The PSID workers are so different from the treated workers that the parallel trends assumption is genuinely hard to defend. The test gives you a quantitative read on how worried you should be.</p><p><strong>— -</strong></p><p><strong>The placebo test</strong></p><p>Related but distinct from the pre-trends test: the placebo period test.</p><p>You pretend treatment happened one period earlier than it did. Using only pre-treatment data (1974 and 1975), you estimate a DiD as if training had occurred between those two years. The estimated “effect” should be zero, because nothing happened between 1974 and 1975. If it isn’t, the groups were already diverging.</p><p>In the LaLonde notebook, the pre-trend coefficient and the placebo estimate are the same number, because we only have two pre-treatment periods. With more pre-periods, you’d run a separate placebo for each and look at the full pattern.</p><p><strong>— -</strong></p><p><strong>What breaking parallel trends looks like</strong></p><p>The notebook includes a deliberate violation: we add $3,000 to the control group’s 1978 earnings, simulating a macroeconomic boom that hit the PSID workers but not the disadvantaged treated workers.</p><p>The DiD estimate drops — treatment looks less effective than it was. The direction is intuitive once you see it: if the control group grows faster than expected, DiD over-subtracts the “natural trend” and underestimates the effect.</p><p>The key lesson isn’t the direction of the bias. It’s that the direction depends entirely on <em>how</em> parallel trends are violated — and you can’t know that from the data alone. This is why the pre-trends test matters. It’s not proof that the assumption holds. It’s evidence that it might.</p><p><strong>— -</strong></p><p><strong>Results</strong></p><p>Across the two DiD specifications (with and without covariates), the estimates land in the range of $1,200–$2,000, depending on whether the GitHub data was loaded or the simulated fallback was used. The LaLonde RCT benchmark is $1,794.</p><p>This is a meaningful improvement over the naive comparison, which swings from negative to wildly positive depending on framing. DiD removes the pre-existing earnings level difference and gives you something defensible — provided you believe the parallel trends assumption.</p><p>The pre-trends test result tells you how much to believe it. If the 1974→1975 interaction is small and insignificant, the design is plausible. If it’s large, you need to be honest about the limitation.</p><p><strong>— -</strong></p><p><strong>What DiD can’t do — and why Phase 3 exists</strong></p><p>DiD required something specific: panel data. The same workers were observed before <em>and</em> after training. It used the time dimension to remove selection bias.</p><p>Two problems remain.</p><p>First, the PSID control group is so different from the treated workers that parallel trends are hard to defend, even if the pre-trends test passes on paper. The assumption does a lot of work here.</p><p>Second, what if you don’t have pre-treatment data? Many observational datasets are cross-sectional — a single snapshot in time. You have information on who received treatment and who didn’t, along with a set of covariates for each person—no panel structure.</p><p>For that problem, we need a different identification strategy. Instead of using time variation to remove selection bias, we construct a comparable control group directly from the data, finding untreated workers who look statistically identical to treated workers on every measured characteristic.</p><p>That’s Propensity Score Matching, and it’s what Phase 3 covers.</p><p><strong>— -</strong></p><p><a href="https://ajay-deshpande.medium.com/propensity-score-matching-when-the-method-tells-you-it-cant-help-4c8d50384df9"><em>Next: Phase 3 — Propensity Score Matching: Building a Comparable Control Group Without Panel Data</em></a></p><p><em>Full code and outputs: </em><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/DiD.py"><em>Github</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8f80de1c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A/B Testing: Why Randomization is the Gold Standard (and Four Ways It Fails in Practice)]]></title>
            <link>https://ajay-deshpande.medium.com/a-b-testing-why-randomization-is-the-gold-standard-and-four-ways-it-fails-in-practice-716e6350d9be?source=rss-4773ba74150b------2</link>
            <guid isPermaLink="false">https://medium.com/p/716e6350d9be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ajay Deshpande]]></dc:creator>
            <pubDate>Wed, 20 May 2026 23:56:50 GMT</pubDate>
            <atom:updated>2026-05-23T00:08:49.168Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is Part 2 of a series on applied causal inference. If you haven’t read </em><a href="https://ajay-deshpande.medium.com/why-most-data-science-doesnt-answer-the-question-you-re-asking-508aad563418"><em>Part 1 — the framing, start there</em></a><em>. This part focuses on A/B testing — what it is, how it works, and four ways it fails in practice. Full code at </em><a href="https://github.com/Ajay-Deshpande/applied-causal-inference/blob/master/notebooks/A-B%20Testing.py"><em>GitHub</em></a></p><p><strong>— -</strong></p><p><strong>The question nobody asks</strong></p><p>Your team redesigned a product page. Someone pulls a report: users who saw the new design converted at 13%, versus 10% for the old design. A 3-percentage-point lift. The room gets excited. Ship it?</p><p>Not yet.</p><p>That 3pp difference has two explanations. Either the new design led to more purchases, or users who happened to see it were already more likely to buy. You cannot tell which is true from that number alone.</p><p>This is the central problem of causal inference. It shows up in every business decision involving data: did the marketing campaign increase revenue, or did we spend more during a period when revenue was already rising? Did job training cause workers to earn more, or did more motivated workers enroll in the training? Did the scholarship cause better graduation rates, or did higher-ability students qualify for it?</p><p>Correlation gives you patterns. Causation tells you what to do. They are not the same thing, and treating one as the other has led to genuinely bad decisions at scale.</p><p><strong>— -</strong></p><p><strong>What an A/B test actually is</strong></p><p>An A/B test is a <strong>Randomized Controlled Trial (RCT)</strong> — the same design used in clinical drug trials, applied to product decisions. You randomly assign each user to either the old experience (control) or the new experience (treatment). The word <em>randomly</em> is doing enormous work here.</p><p>When the assignment is truly random, every characteristic of a user — their age, purchase history, device type, income, mood on that day — is equally distributed across both groups, <em>in expectation</em>. The two groups are statistically identical before the experiment. So any difference in outcomes afterward can only come from one place: the thing you changed.</p><p>This is why, in a proper A/B test, the naive comparison <em>is</em> the causal effect:</p><p>&gt; <strong>ATE = Average purchase rate (treatment) − Average purchase rate (control)</strong></p><p>No adjustment needed. No statistical gymnastics. No assumptions about confounders, because randomization eliminates them by design.</p><p>This simplicity — a single subtraction — is the gold standard that every other causal method is trying to approximate.</p><p><strong>— -</strong></p><p><strong>A key distinction: what are you actually measuring?</strong></p><p>Before running any analysis, you should be clear about your <strong>estimand </strong>— the quantity you’re trying to measure. In an A/B test, we’re estimating the <strong>ATE (Average Treatment Effect)</strong>:</p><p>&gt; <em>If I showed this new page to everyone, what would the average effect be across the entire user population?</em></p><p>This is different from the <strong>ATT (Average Treatment Effect on the Treated) </strong>— the effect on people who actually got the treatment — or the <strong>LATE (Local Average Treatment Effect)</strong> — the effect in a specific subgroup. We’ll encounter all three in later phases. For now, ATE is what we want, and randomization gives it to us cleanly.</p><p><strong>— -</strong></p><p><strong>Building the experiment</strong></p><p>Rather than working with data you don’t control, we simulate a dataset where you know the true answer. This is how you build genuine intuition: when your analysis recovers exactly what you baked in, you know the method works.</p><p>We simulate 10,000 users with a true treatment effect of exactly 3 percentage points. We also include background characteristics — age, prior visits, device type — that won’t matter here (because of randomization) but will become critical confounders in later phases. One dataset is used across the series.</p><p>The data-generating process looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19a92aa2d7fddf63eeb12bbd0ff92e9f/href">https://medium.com/media/19a92aa2d7fddf63eeb12bbd0ff92e9f/href</a></iframe><p>When you run the analysis, your estimate should come back at approximately 0.030. The closer, the better.</p><p><strong>— -</strong></p><p><strong>Three estimators, one answer</strong></p><p>We estimate ATE in three ways. Not because we need three, but because understanding what an “estimator” is — a procedure that produces a number from data — is foundational to everything that follows.</p><p><strong>Method 1: Difference in means -</strong> The simplest thing possible. Average outcome in the treatment group minus average outcome in the control group (Not self-sufficient in case the samples are small and/or the randomization assumption fails).</p><p><strong>Method 2: OLS regression -</strong> Regress `purchased` on `treatment` and covariates. The coefficient on treatment is your ATE estimate. Here’s the interesting part: adding covariates (age, prior visits) makes the estimate <em>more precise</em> (smaller standard error) without meaningfully changing the estimate itself. Why? Because those covariates are uncorrelated with treatment, randomization guarantees that. They explain variation in the outcome but not the treatment effect.</p><p>In Phase 3 (PSM), adding covariates will change the estimate substantially, because there, covariates are confounders, not just noise absorbers. The contrast between these two scenarios is one of the most important things to internalize in this series.</p><p><strong>Method 3: Welch’s t-test -</strong> Tests whether the means are different across groups. Gives you a t-statistic and p-value. Equivalent to Method 1 in large samples.</p><p>All three converge to approximately 0.030 (we designed the data this way). That’s the point.</p><p><strong>— -</strong></p><p><strong>Confidence intervals: knowing how uncertain you are</strong></p><p>A point estimate without a range is incomplete. “The effect is 3pp” is less useful than “the effect is 3pp, and we’re 95% confident it’s between 1.8pp and 4.3pp.”</p><p>We compute confidence intervals (CI) in two ways:</p><p><strong>Analytical CI:</strong> (from OLS standard errors): assumes normality, fast to compute.</p><p><strong>Bootstrap CI</strong>: resample the entire dataset 2,000 times with replacement. Compute ATE on each resample. The 2.5th to 97.5th percentile of that distribution is your 95% CI. This approach makes fewer assumptions and works better with small samples or unusual outcome distributions.</p><p>Both methods should give similar intervals for a binary outcome with N=10,000. In smaller datasets or later phases, they can diverge — and the bootstrap is more trustworthy.</p><p><strong>— -</strong></p><p><strong>The most important part: deliberately breaking it</strong></p><p>This is where the real learning happens.</p><p>We remove randomization. Instead, younger users with more prior visits are more likely to be assigned to the treatment group — they self-select in. We keep everything else identical: the same true effect of 3pp, the same outcome model.</p><p>The naive estimate jumps to roughly 6–8 percentage points. More than double the true effect.</p><p>The reason: younger, more engaged users have higher purchase intent regardless of which page they see. When they’re overrepresented in the treatment group, their naturally higher conversion rates inflate the treatment estimate. The page looks more effective than it is.</p><p>The giveaway in the data: the <strong>Standardized Mean Difference (SMD)</strong> on age and prior visits. In the proper A/B test, SMD is near zero for every covariate — the groups are balanced. In the broken version, SMD on age jumps to ~0.35. The groups are no longer comparable.</p><p>&gt; Without randomization, the naive estimate is more than 2× the true effect. That’s not sampling noise — it’s systematic selection bias, and every decision made from it will be wrong in a predictable direction.</p><p>This broken scenario is not hypothetical. It’s what the LaLonde dataset — our next phase — actually looks like. Workers who chose to enroll in job training were systematically different from those who didn’t. Younger, more motivated, different baseline earnings. Any naive comparison is contaminated.</p><p><strong>— -</strong></p><p><strong>Where the gold standard breaks down</strong></p><p>Randomization eliminates confounders — but only if the experiment is run correctly. In practice, A/B tests fail more often from execution mistakes than from bad statistics. These are the four most common ways a well-intentioned experiment produces a wrong answer.</p><p><strong>— -</strong></p><p><strong>1. Peeking — stopping the experiment early</strong></p><p>This is the most widespread mistake in industry, and it’s easy to understand why it happens. You launch a test on Monday, check the dashboard on Wednesday, see p=0.03, and stop. The numbers look good. Ship it.</p><p>The problem is that p-values are designed to be interpreted at a single pre-specified sample size. If you check repeatedly — at day 1, day 2, day 3 — you give yourself multiple chances to cross the significance threshold by random chance. With 20 peeks, your actual false positive rate isn’t 5%. It’s closer to 40%. You will eventually see p &lt; 0.05 even when there is no true effect, just because you looked enough times.</p><p>The causal consequence: you ship a change that did nothing, or worse, harmed users. The “gold standard” just produced a false causal claim — not because of bad design, but because of impatience.</p><p>The fix is straightforward: decide your sample size before the experiment starts, using power analysis (covered next), and commit to not stopping early. If your team genuinely needs continuous monitoring — common in fast-moving products — use sequential testing methods like always-valid p-values or a Bayesian framework, both of which are designed for this use case.</p><p><strong>— -</strong></p><p><strong>2. Power analysis — knowing your sample size before you start</strong></p><p>Running an underpowered experiment is a different kind of failure. Instead of false positives, you get false negatives: your test finds “no effect” and you don’t ship a change that would have genuinely helped users.</p><p>Power analysis answers a single question: <em>how many users do I need before I start?</em> It requires four inputs you should know before touching any data:</p><p><strong>Baseline conversion rate</strong> — your current rate, from historical data</p><p><strong>Minimum detectable effect (MDE)</strong> — the smallest lift you’d actually care about. A 0.01pp improvement on a low-volume page may not be worth engineering time; a 0.5pp improvement might be. You set this based on <strong><em>business judgment</em></strong>, not statistics.</p><p><strong>Significance level (α)</strong> — usually 0.05, meaning you accept a 5% chance of a false positive</p><p><strong>Desired power (1−β)</strong> — usually 0.80, meaning you want an 80% chance of detecting the effect if it’s real</p><p>These four inputs produce a required sample size per group. If your product can’t generate that traffic in a reasonable timeframe, the experiment isn’t feasible at that MDE — you’d need to either accept a less sensitive test or wait longer.</p><p>The practical failure mode: teams skip this step, run a test for one week because that feels right, and then either stop early (peeking problem) or conclude “no effect” from a sample that was never large enough to see one.</p><p><strong>— -</strong></p><p><strong>3. P-hacking and multiple comparisons</strong></p><p>You designed the experiment to measure one thing — purchase rate. But your dashboard shows 15 metrics: add-to-cart rate, session duration, page scroll depth, return visits, revenue per user, and so on. You look at all of them. Three are significant. You write up the ones that tell a good story.</p><p>This is p-hacking — not necessarily malicious, but statistically identical to running 15 separate experiments and reporting the best result. At α=0.05, you expect one false positive for every 20 tests purely by chance. With 15 metrics, the probability of at least one spurious significant result is around 54%.</p><p>The fix: pre-register your primary metric before the experiment starts. That’s the one you make your shipping decision on. Secondary metrics are exploratory — they generate hypotheses for future experiments, not conclusions from this one. When you do need to test multiple metrics formally, apply a correction: Bonferroni (divide α by the number of tests) is conservative but simple; Benjamini-Hochberg controls the false discovery rate and is less punishing.</p><p>The broader principle: your analysis plan should be written before you see the data. If you’d be embarrassed to show someone the 12 metrics you didn’t report, something has gone wrong.</p><p><strong>— -</strong></p><p><strong>4. Novelty effects — users behaving differently because something is new</strong></p><p>This one is subtler and often overlooked. Your new page design shows a 3pp lift in week one. You ship it. Two months later, conversion is back to baseline.</p><p>What happened: users clicked on the new design because it was different — not because it was better. The novelty wore off and behavior returned to normal. The A/B test captured a real short-term effect that wasn’t the long-term effect you actually cared about.</p><p>Novelty effects are especially common with UI changes (new button colors, layouts, navigation), notification features, and anything that breaks a habitual pattern. They’re less common for structural changes like pricing, checkout flow, or personalization — things where users have to engage with the mechanism, not just notice something different.</p><p>The diagnostic: if you have enough traffic, segment your treatment effect by user tenure in the experiment. New entrants to the test (users who saw the design for the first time this week) versus users who’ve been in the test for two or three weeks. If the effect is large for new entrants and near zero for longer-running users, you’re likely looking at novelty.</p><p>The fix is sometimes just to run the experiment longer. But this conflicts with the peeking problem — running longer means more chances to peek. The right answer is to define, before the experiment, whether you care about the short-term or long-term effect, and size your experiment for that window.</p><p><strong>— -</strong></p><p><strong>The common thread</strong></p><p>All four of these failures share something: they produce a number that looks like a causal estimate but isn’t one. Peeking gives you a false positive. Insufficient power gives you a false negative. P-hacking gives you a cherry-picked result. Novelty gives you a transient effect mistaken for a permanent one.</p><p>The gold standard is only gold if the execution matches the design. An experiment with these problems isn’t better than observational analysis — it’s arguably worse, because it carries the false credibility of “we ran a test.”</p><p>This is worth keeping in mind as we move to DiD and PSM. Those methods are harder to execute than an A/B test. But a badly-run A/B test and a well-run DiD analysis are not obviously ranked. The method matters less than whether the assumptions behind it were actually met.</p><p><strong>— -</strong></p><p><strong>Tracking results with MLflow</strong></p><p>Every phase of this project logs estimates, confidence intervals, and diagnostic plots to MLflow. By Phase 7, you’ll have a single experiment view showing all four methods’ estimates side by side — and whether they converge on the same answer.</p><pre>with mlflow.start_run(run_name=&quot;phase1_ab_test&quot;):<br>  mlflow.log_param(&quot;method&quot;, &quot;AB_Test_RCT&quot;)<br>  mlflow.log_param(&quot;estimand&quot;, &quot;ATE&quot;)<br>  mlflow.log_metric(&quot;ATE_estimate&quot;, round(ATE, 5))<br>  mlflow.log_metric(&quot;CI_lower&quot;, round(boot_ci_low, 5))<br>  mlflow.log_metric(&quot;CI_upper&quot;, round(boot_ci_high, 5))<br>  mlflow.log_metric(&quot;p_value&quot;, round(p_val, 5))</pre><blockquote>This discipline — logging everything, not just the final number — is what separates a reproducible analysis from a one-off script.</blockquote><p><strong>— -</strong></p><p><strong>What you should take from this phase</strong></p><p>Randomization is the only causal method that requires no assumptions about confounders. It eliminates them by design, not by measurement or modeling. Every method in the remaining phases is an attempt to approximate what you built here — using different data structures, different assumptions, different mathematical machinery.</p><p>The discomfort of the broken experiment cell — that uncertainty about whether the estimate reflects reality or selection — is what motivates every method that follows.</p><p><strong>DiD</strong> uses the structure of time: if you have before-and-after data, you can difference out selection bias under one assumption. <strong>PSM</strong> uses observed covariates to construct a comparable control group without needing panel data. <strong>Synthetic Control</strong> builds a counterfactual when you have only one treated unit. <strong>RD</strong> exploits a threshold that nature handed you.</p><p>Each is a different answer to the same question: how do we reconstruct the counterfactual we can never observe?</p><p><strong>— -</strong></p><p><strong>What’s next</strong></p><p><a href="https://medium.com/p/2f8f80de1c56?postPublishedType=initial"><strong>Part 3: Difference-in-Differences — When Time Is Your Control Group</strong></a></p><p>The LaLonde dataset contains earnings data for workers before and after a job training program — plus a comparison group that didn’t receive training. Workers weren’t randomly assigned. But if the two groups had trended the same way without the program, we can difference out the selection. That’s the parallel trends assumption. We’ll test it, visualize it, break it deliberately, and estimate the treatment effect — all on real data with a known benchmark.</p><p><strong>— -</strong></p><p><em>Full notebooks for every phase are available on </em><a href="https://github.com/Ajay-Deshpande/applied-causal-inference"><em>GitHub</em></a><em>. The project is built in Databricks with MLflow tracking throughout.</em></p><p><em>*Questions, corrections, and pushback welcome in the comments.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=716e6350d9be" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>