Skip to content

Causal inference, GLMs and experiments

Prediction asks what happens when you observe XX; causal inference asks what happens when you intervene on XX. 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 np
import pandas as pd
from scipy import stats
from sklearn.linear_model import LogisticRegression
import statsmodels.api as sm
import statsmodels.formula.api as smf
ab = pd.read_csv("data/ab_test.csv")
customers = pd.read_csv("data/customers.csv")
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 p<0.001p < 0.001
shrink A/B test variance using a pre-period metric CUPED Ycuped=Y−θ(X−Xˉ)Y_{\text{cuped}} = Y - \theta (X - \bar{X}) θ=Cov(Y,X)/Var(X)\theta = \mathrm{Cov}(Y, X) / \mathrm{Var}(X); cuts variance by 1−r21 - r^2
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 (Var≈Mean\mathrm{Var} \approx \text{Mean}) smf.glm(..., family=sm.families.Poisson()) np.exp(coef) is the incidence rate ratio (IRR)
model overdispersed count data (Var>Mean\mathrm{Var} > \text{Mean}) smf.glm(..., family=sm.families.NegativeBinomial(alpha=...)) or smf.negativebinomial (MLE α\alpha)
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 S^(t)=∏ti≤t(1−di/ni)\hat{S}(t) = \prod_{t_i \le t}(1 - d_i / n_i) dropping active users biases survival downward

Each unit ii has two potential outcomes: Yi(1)Y_i(1) if treated (Ti=1T_i = 1) and Yi(0)Y_i(0) if untreated (Ti=0T_i = 0). We only ever observe one: Yi=TiYi(1)+(1−Ti)Yi(0)Y_i = T_i Y_i(1) + (1 - T_i) Y_i(0).

  • ATE (Average Treatment Effect): E[Y(1)−Y(0)]\mathbb{E}[Y(1) - Y(0)].
  • ATT (Average Treatment Effect on the Treated): E[Y(1)−Y(0)∣T=1]\mathbb{E}[Y(1) - Y(0) \mid T = 1].
  • Identification assumptions: SUTVA (no interference between units), Conditional Ignorability ((Y(1),Y(0))⊥T∣X(Y(1), Y(0)) \perp T \mid X, no unmeasured confounders), and Positivity (0<P(T=1∣X)<10 < P(T = 1 \mid X) < 1).
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 T→YT \to Y
Fork (confounder) T←C→YT \leftarrow C \to Y open (creates spurious correlation) blocks backdoor path adjust for CC
Chain (mediator) T→M→YT \to M \to Y open (carries causal effect) blocks causal path do not adjust for MM (adjust only for direct effect)
Collider T→K←YT \to K \leftarrow Y blocked opens spurious correlation (selection bias) never adjust for KK 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) χ2\chi^2 goodness-of-fit on group counts vs. planned split if p<0.001p < 0.001, logging or randomization is broken — do not trust metrics
Optional stopping (peeking) testing repeatedly at α=0.05\alpha = 0.05 inflates Type I error to ~20–30% fix sample size upfront, or use sequential boundaries (alpha spending / always-valid p-values)
CUPED variance reduction Y∗=Y−θ(X−Xˉ)Y^* = Y - \theta(X - \bar{X}), θ=Cov(Y,X)Var(X)\theta = \frac{\mathrm{Cov}(Y, X)}{\mathrm{Var}(X)} unbiased if XX is strictly pre-treatment; Var(Y∗)=(1−r2)Var(Y)\mathrm{Var}(Y^*) = (1 - r^2)\mathrm{Var}(Y)
Epsilon-greedy bandit random arm with prob ε\varepsilon, else highest mean simple; linear regret unless εt\varepsilon_t decays
UCB1 bandit pick arg⁡max⁡a(μ^a+2ln⁡tna)\arg\max_a \left(\hat{\mu}_a + \sqrt{\frac{2 \ln t}{n_a}}\right) deterministic optimism; O(log⁡T)O(\log T) regret
Thompson sampling draw θ~a∼Posteriora\tilde{\theta}_a \sim \text{Posterior}_a; pick arg⁡max⁡aθ~a\arg\max_a \tilde{\theta}_a 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 covariate
rng = np.random.default_rng(42)
n_sim = 2_000
x_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_raw
print(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 - reward
pulls = (alpha + beta - 2).astype(int).tolist()
print("Thompson sampling pulls per arm:", pulls)
Output
SRM counts={'control': 5002, 'treatment': 4998}, p=0.968
SE raw=0.447 vs CUPED=0.266 (reduction 40.4%)
Thompson sampling pulls per arm: [112, 683, 705]
Method Core idea Key assumption Watch out
Regression adjustment include confounders XX 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 e(x)=P(T=1∣X=x)e(x) = P(T=1 \mid X=x) ignorability + common support discards unmatched units (estimates ATT)
IPW (Horvitz–Thompson / Hájek) weight treated by 1/e(x)1/e(x), control by 1/(1−e(x))1/(1-e(x)) positivity (0<e(x)<10 < e(x) < 1) 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) (YˉT,post−YˉT,pre)−(YˉC,post−YˉC,pre)(\bar{Y}_{T,\text{post}} - \bar{Y}_{T,\text{pre}}) - (\bar{Y}_{C,\text{post}} - \bar{Y}_{C,\text{pre}}) parallel trends without treatment check pre-treatment trend slopes; cluster SEs by unit
# Estimate the effect of has_autopay on churned using Propensity Score IPW
df = 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 / ps
w0 = (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 IPW
ec = (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_pool
smd_after = (
np.sum(w1 * ec) / np.sum(w1) - np.sum(w0 * ec) / np.sum(w0)
) / sd_pool
print(f"naive diff={naive_ate:.4f}, IPW ATE={ipw_ate:.4f}")
print(f"electronic_check SMD: before={smd_before:.3f}, after={smd_after:.3f}")
Output
naive diff=-0.0493, IPW ATE=-0.0296
electronic_check SMD: before=-1.136, after=-0.007

A GLM connects the linear predictor η=Xβ\eta = X\beta to the expected outcome μ=E[Y∣X]\mu = \mathbb{E}[Y \mid X] via a link function g(μ)=ηg(\mu) = \eta and a distribution from the exponential dispersion family.

Outcome type statsmodels family Canonical link g(μ)g(\mu) Inverse link μ=g−1(η)\mu = g^{-1}(\eta) Interpretation of eβje^{\beta_j}
Continuous, symmetric sm.families.Gaussian() identity μ\mu η\eta additive unit change (βj\beta_j)
Binary / proportion sm.families.Binomial() logit ln⁡μ1−μ\ln\frac{\mu}{1-\mu} σ(η)\sigma(\eta) odds ratio (OR)
Counts (Var≈μ\mathrm{Var} \approx \mu) sm.families.Poisson() log ln⁡μ\ln \mu eηe^\eta incidence rate ratio (IRR)
Overdispersed counts (Var=μ+αμ2\mathrm{Var} = \mu + \alpha\mu^2) sm.families.NegativeBinomial(alpha=...) log ln⁡μ\ln \mu eηe^\eta incidence rate ratio (IRR)
Positive right-skewed (revenue, duration) sm.families.Gamma(sm.families.links.Log()) log (preferred over inverse) eηe^\eta multiplicative mean ratio

Compare nested or non-nested GLMs on the same data with AIC (2k−2ℓ2k - 2\ell) and BIC (kln⁡n−2ℓk\ln n - 2\ell) — lower is better — and check Pearson dispersion (χPearson2/dfresid\chi^2_{\text{Pearson}} / \text{df}_{\text{resid}}): values well above 1.01.0 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}")
Output
Poisson dispersion=1.056, AIC=14329.7
NegBin 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.994

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 S(t)=P(T>t)S(t) = P(T > t) from event times tit_i with did_i events out of nin_i subjects still at risk just before tit_i:

S^(t)=∏ti≤t(1−dini),Var^(S^(t))≈S^(t)2∑ti≤tdini(ni−di)(Greenwood)\hat{S}(t) = \prod_{t_i \le t} \left(1 - \frac{d_i}{n_i}\right), \qquad \widehat{\mathrm{Var}}(\hat{S}(t)) \approx \hat{S}(t)^2 \sum_{t_i \le t} \frac{d_i}{n_i (n_i - d_i)} \quad (\text{Greenwood})
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}")
Output
month-to-month S(12m)=0.742, S(36m)=0.557
one-year S(12m)=0.974, S(36m)=0.888
two-year S(12m)=0.995, S(36m)=0.972
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 R2R^2
peeking daily at an A/B test and stopping at p<0.05p < 0.05 false-positive rate climbs past 20% pre-commit sample size or use sequential testing
using post-treatment metrics as the CUPED covariate XX biases treatment effect estimate use only strictly pre-experiment covariates
ignoring extreme propensity scores (e(x)≈0e(x) \approx 0 or 11) 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 >1.5> 1.5 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 >10%> 10\% eβe^\beta 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