Causal inference, GLMs and experiments
Prediction asks what happens when you observe ; causal inference asks what happens when you intervene on . This reference summarizes causal DAG rules, A/B testing safeguards (SRM, peeking, CUPED, bandits), observational estimators (IPW, DiD), statsmodels Generalized Linear Models, and Kaplan–Meier retention curves. All blocks share one session using data/ab_test.csv and data/customers.csv:
import numpy as npimport pandas as pdfrom scipy import statsfrom sklearn.linear_model import LogisticRegressionimport statsmodels.api as smimport statsmodels.formula.api as smf
ab = pd.read_csv("data/ab_test.csv")customers = pd.read_csv("data/customers.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| decide which variables to adjust for in a causal model | draw a causal DAG first | adjust confounders; never adjust colliders or mediators (for total effect) |
| check if an A/B test traffic split is broken | stats.chisquare(counts, expected) |
Sample Ratio Mismatch (SRM); stop if |
| shrink A/B test variance using a pre-period metric | CUPED | ; cuts variance by |
| optimize reward while testing variants online | Thompson sampling (Beta–Binomial bandit) | samples from posteriors; minimizes regret |
| estimate ATE from observational data with measured confounders | Propensity score IPW / stabilized IPW | check overlap and post-weight covariate balance (SMD < 0.1) |
| estimate policy impact with before/after + control group | Difference-in-Differences (DiD) | requires parallel trends before treatment |
| model positive count data () | smf.glm(..., family=sm.families.Poisson()) |
np.exp(coef) is the incidence rate ratio (IRR) |
| model overdispersed count data () | smf.glm(..., family=sm.families.NegativeBinomial(alpha=...)) |
or smf.negativebinomial (MLE ) |
| model binary outcomes with odds ratios | smf.glm(..., family=sm.families.Binomial()) |
np.exp(coef) is the odds ratio |
| estimate customer retention with right-censored tenures | Kaplan–Meier | dropping active users biases survival downward |
Potential outcomes and causal DAGs
Section titled “Potential outcomes and causal DAGs”Each unit has two potential outcomes: if treated () and if untreated (). We only ever observe one: .
- ATE (Average Treatment Effect): .
- ATT (Average Treatment Effect on the Treated): .
- Identification assumptions: SUTVA (no interference between units), Conditional Ignorability (, no unmeasured confounders), and Positivity ().
flowchart LR
subgraph Fork["Confounder (adjust)"]
C1["C"] --> T1["T"]
C1 --> Y1["Y"]
end
subgraph Chain["Mediator (do NOT adjust for total effect)"]
T2["T"] --> M2["M"] --> Y2["Y"]
end
subgraph Collider["Collider (NEVER adjust)"]
T3["T"] --> K3["K"]
Y3["Y"] --> K3
end
| Structure | Path | Natural state | Conditioning on middle node | Action for total effect |
|---|---|---|---|---|
| Fork (confounder) | open (creates spurious correlation) | blocks backdoor path | adjust for | |
| Chain (mediator) | open (carries causal effect) | blocks causal path | do not adjust for (adjust only for direct effect) | |
| Collider | blocked | opens spurious correlation (selection bias) | never adjust for or its descendants |
Simpson’s paradox occurs when an aggregate association reverses inside subgroups. The data alone cannot tell you whether the aggregate or subgroup number is right — the DAG decides (adjust if the grouping variable is a confounder, not if it is a mediator or collider).
Experimentation: SRM, peeking, CUPED and bandits
Section titled “Experimentation: SRM, peeking, CUPED and bandits”| Technique / Trap | Formula or rule | Practical takeaway |
|---|---|---|
| Sample Ratio Mismatch (SRM) | goodness-of-fit on group counts vs. planned split | if , logging or randomization is broken — do not trust metrics |
| Optional stopping (peeking) | testing repeatedly at inflates Type I error to ~20–30% | fix sample size upfront, or use sequential boundaries (alpha spending / always-valid p-values) |
| CUPED variance reduction | , | unbiased if is strictly pre-treatment; |
| Epsilon-greedy bandit | random arm with prob , else highest mean | simple; linear regret unless decays |
| UCB1 bandit | pick | deterministic optimism; regret |
| Thompson sampling | draw ; pick | natural Beta–Binomial fit; low regret and robust to delayed feedback |
# 1. Sample Ratio Mismatch check on data/ab_test.csv (planned 50/50 split)counts = ab["group"].value_counts().sort_index()srm = stats.chisquare(counts, f_exp=[len(ab) / 2, len(ab) / 2])print(f"SRM counts={counts.to_dict()}, p={srm.pvalue:.3f}")
# 2. CUPED variance reduction with a correlated pre-experiment covariaterng = np.random.default_rng(42)n_sim = 2_000x_pre = rng.normal(50.0, 10.0, n_sim)treat = rng.integers(0, 2, n_sim)y_post = 0.8 * x_pre + 1.2 * treat + rng.normal(0.0, 6.0, n_sim)
def diff_se(a: np.ndarray, b: np.ndarray) -> float: return float(np.sqrt(a.var(ddof=1) / len(a) + b.var(ddof=1) / len(b)))
theta = float(np.cov(y_post, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))y_cuped = y_post - theta * (x_pre - x_pre.mean())se_raw = diff_se(y_post[treat == 1], y_post[treat == 0])se_cuped = diff_se(y_cuped[treat == 1], y_cuped[treat == 0])drop = 1.0 - se_cuped / se_rawprint(f"SE raw={se_raw:.3f} vs CUPED={se_cuped:.3f} (reduction {drop:.1%})")
# 3. Thompson sampling over 3 arms (true rates 0.08, 0.11, 0.14)true_p = [0.08, 0.11, 0.14]alpha, beta = np.ones(3), np.ones(3)for _ in range(1_500): arm = int(np.argmax(rng.beta(alpha, beta))) reward = int(rng.random() < true_p[arm]) alpha[arm] += reward beta[arm] += 1 - rewardpulls = (alpha + beta - 2).astype(int).tolist()print("Thompson sampling pulls per arm:", pulls)SRM counts={'control': 5002, 'treatment': 4998}, p=0.968SE raw=0.447 vs CUPED=0.266 (reduction 40.4%)Thompson sampling pulls per arm: [112, 683, 705]Observational methods: IPW and DiD
Section titled “Observational methods: IPW and DiD”| Method | Core idea | Key assumption | Watch out |
|---|---|---|---|
| Regression adjustment | include confounders in outcome model | correct functional form + no unmeasured confounders | extrapolates if treated/control do not overlap |
| Propensity score matching | pair treated and control units with similar | ignorability + common support | discards unmatched units (estimates ATT) |
| IPW (Horvitz–Thompson / Hájek) | weight treated by , control by | positivity () | clip extreme propensities; check post-weight SMD < 0.1 |
| Doubly Robust (AIPW) | combines outcome model + IPW | consistent if either model is right | preferred default in modern observational studies |
| Difference-in-Differences (DiD) | parallel trends without treatment | check pre-treatment trend slopes; cluster SEs by unit |
# Estimate the effect of has_autopay on churned using Propensity Score IPWdf = customers.copy()X_cov = pd.get_dummies( df[["age", "tenure_months", "monthly_charges", "payment_method", "contract"]], drop_first=True, dtype=float,)T = df["has_autopay"].to_numpy(dtype=float)Y = df["churned"].to_numpy(dtype=float)
ps = LogisticRegression(max_iter=1_000).fit(X_cov, T).predict_proba(X_cov)[:, 1]ps = np.clip(ps, 0.05, 0.95)w1 = T / psw0 = (1.0 - T) / (1.0 - ps)
naive_ate = float(Y[T == 1].mean() - Y[T == 0].mean())ipw_ate = float(np.sum(w1 * Y) / np.sum(w1) - np.sum(w0 * Y) / np.sum(w0)) # Hajek
# Check standardized mean difference (SMD) of electronic_check before vs after IPWec = (df["payment_method"] == "electronic_check").to_numpy(dtype=float)sd_pool = float(np.sqrt(0.5 * (ec[T == 1].var() + ec[T == 0].var())))smd_before = (ec[T == 1].mean() - ec[T == 0].mean()) / sd_poolsmd_after = ( np.sum(w1 * ec) / np.sum(w1) - np.sum(w0 * ec) / np.sum(w0)) / sd_poolprint(f"naive diff={naive_ate:.4f}, IPW ATE={ipw_ate:.4f}")print(f"electronic_check SMD: before={smd_before:.3f}, after={smd_after:.3f}")naive diff=-0.0493, IPW ATE=-0.0296electronic_check SMD: before=-1.136, after=-0.007Generalized Linear Models (GLMs)
Section titled “Generalized Linear Models (GLMs)”A GLM connects the linear predictor to the expected outcome via a link function and a distribution from the exponential dispersion family.
| Outcome type | statsmodels family |
Canonical link | Inverse link | Interpretation of |
|---|---|---|---|---|
| Continuous, symmetric | sm.families.Gaussian() |
identity | additive unit change () | |
| Binary / proportion | sm.families.Binomial() |
logit | odds ratio (OR) | |
| Counts () | sm.families.Poisson() |
log | incidence rate ratio (IRR) | |
| Overdispersed counts () | sm.families.NegativeBinomial(alpha=...) |
log | incidence rate ratio (IRR) | |
| Positive right-skewed (revenue, duration) | sm.families.Gamma(sm.families.links.Log()) |
log (preferred over inverse) | multiplicative mean ratio |
Compare nested or non-nested GLMs on the same data with AIC () and BIC () — lower is better — and check Pearson dispersion (): values well above in Poisson regression signal overdispersion.
formula = "support_tickets ~ C(contract) + monthly_charges + tenure_months"pois = smf.glm(formula, data=customers, family=sm.families.Poisson()).fit()nb = smf.negativebinomial(formula, data=customers).fit(disp=False)
dispersion = float(pois.pearson_chi2 / pois.df_resid)irrs = np.exp(nb.params.drop(["Intercept", "alpha"]))print(f"Poisson dispersion={dispersion:.3f}, AIC={pois.aic:.1f}")print(f"NegBin alpha={nb.params['alpha']:.3f}, AIC={nb.aic:.1f}")for name, val in irrs.items(): print(f" IRR {name}: {val:.3f}")Poisson dispersion=1.056, AIC=14329.7NegBin alpha=0.043, AIC=14324.7 IRR C(contract)[T.one-year]: 0.937 IRR C(contract)[T.two-year]: 0.986 IRR monthly_charges: 0.993 IRR tenure_months: 0.994Survival analysis and censoring
Section titled “Survival analysis and censoring”When modeling time to an event (churn, failure, recovery), active subjects whose event has not happened by the snapshot date are right-censored (event = 0). Dropping them or treating their current tenure as a churn time biases retention severely downward.
The Kaplan–Meier estimator computes the survival function from event times with events out of subjects still at risk just before :
def kaplan_meier(durations: np.ndarray, events: np.ndarray) -> pd.DataFrame: """Right-censored Kaplan-Meier survival curve with Greenwood SE.""" order = np.argsort(durations) t_all, e_all = durations[order], events[order] times = np.unique(t_all[e_all == 1]) surv, var_sum, rows = 1.0, 0.0, [] for t in times: n_risk = int(np.sum(t_all >= t)) d_events = int(np.sum((t_all == t) & (e_all == 1))) surv *= 1.0 - d_events / n_risk if n_risk > d_events: var_sum += d_events / (n_risk * (n_risk - d_events)) se = surv * np.sqrt(var_sum) rows.append((int(t), n_risk, d_events, surv, se)) return pd.DataFrame(rows, columns=["t", "n_risk", "events", "S", "se"])
for contract in ["month-to-month", "one-year", "two-year"]: sub = customers[customers["contract"] == contract] km = kaplan_meier(sub["tenure_months"].to_numpy(), sub["churned"].to_numpy()) s12 = float(km.loc[km["t"] <= 12, "S"].iloc[-1]) s36 = float(km.loc[km["t"] <= 36, "S"].iloc[-1]) print(f"{contract:<15} S(12m)={s12:.3f}, S(36m)={s36:.3f}")month-to-month S(12m)=0.742, S(36m)=0.557one-year S(12m)=0.974, S(36m)=0.888two-year S(12m)=0.995, S(36m)=0.972Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| controlling for every available column in a causal regression | opens collider bias or blocks mediators, reversing the sign | select covariates from a causal DAG, not by p-value or |
| peeking daily at an A/B test and stopping at | false-positive rate climbs past 20% | pre-commit sample size or use sequential testing |
| using post-treatment metrics as the CUPED covariate | biases treatment effect estimate | use only strictly pre-experiment covariates |
| ignoring extreme propensity scores ( or ) in IPW | one unit gets weight 200 and dominates the ATE | clip/trim propensities, use Hájek weights, check overlap |
| running DiD without checking pre-treatment trends | captures pre-existing divergence as a fake policy effect | plot and test pre-period parallel trends |
| trusting Poisson GLM standard errors when dispersion | p-values are far too small (false significance) | switch to Negative Binomial (smf.negativebinomial) or quasi-Poisson |
using sm.families.Gamma() with its default inverse link |
convergence errors or hard-to-interpret coefficients | pass sm.families.Gamma(sm.families.links.Log()) |
| exponentiating logistic coefficients as “relative risk” | overstates lift when base rate | is an odds ratio, not a risk ratio |
| computing mean tenure on churned customers only | ignores active customers (right censoring), underestimating retention | use Kaplan–Meier or Cox proportional hazards |