49. Causal inference, GLMs and advanced experimentation — Cheat sheet
The essentials of module 49 on one page. Every runnable block shares one session and is checked against its output:
import numpy as npimport pandas as pdimport statsmodels.api as smimport statsmodels.formula.api as smffrom scipy import statsfrom sklearn.compose import ColumnTransformerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")ab = pd.read_csv("data/ab_test.csv")sales = pd.read_csv("data/sales.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… |
|---|---|
| check for Sample Ratio Mismatch (SRM) | stats.chisquare(observed_counts, f_exp=expected_counts) |
| reduce A/B variance with pre-period | theta = np.cov(y, x, ddof=1)[0, 1] / np.var(x, ddof=1); y_c = y - theta * (x - x.mean()) |
| pick the next arm with Thompson sampling | int(np.argmax(rng.beta(1 + wins, 1 + pulls - wins))) |
| pick the next arm with UCB1 | int(np.argmax(wins / pulls + np.sqrt(2 * np.log(t) / pulls))) |
| estimate propensity scores | LogisticRegression(max_iter=1000).fit(X, t).predict_proba(X)[:, 1] |
| compute Hájek IPW ATE | (w1 @ y) / w1.sum() - (w0 @ y) / w0.sum() with w1 = t / e, w0 = (1 - t) / (1 - e) |
| check covariate balance after IPW | Standardized Mean Difference: abs(mu1 - mu0) / np.sqrt(0.5 * (v1 + v0)) (target < 0.10) |
| estimate Difference-in-Differences | smf.ols("y ~ treated * post", data=df).fit(cov_type="HC3") (read treated:post) |
| test DiD parallel trends in pre-period | smf.ols("y ~ treated * time", data=pre_df).fit(cov_type="HC3") (want p > 0.05) |
| fit a logistic GLM (odds ratios) | smf.glm("y ~ x1 + C(cat)", data=df, family=sm.families.Binomial()).fit() |
| fit a Poisson GLM (count data) | smf.glm("y ~ x1 + C(cat)", data=df, family=sm.families.Poisson()).fit() |
| check Poisson overdispersion | res.pearson_chi2 / res.df_resid (if > 1.2, switch to Negative Binomial) |
| fit a Negative Binomial count model | smf.negativebinomial("y ~ x1 + C(cat)", data=df).fit(method="bfgs", disp=False) |
| fit a Gamma log-link GLM (skewed positive) | smf.glm("y ~ x", data=df, family=sm.families.Gamma(sm.families.links.Log())).fit() |
| compute Kaplan–Meier survival curve | S(t) = prod(1 - d_j / n_j) over event times t_j, keeping censored units in n_j |
Causal graphs and identification
Section titled “Causal graphs and identification”| DAG pattern | Path | Action for total effect of on |
|---|---|---|
| Confounder (fork) | Adjust for to close the backdoor path | |
| Mediator (chain) | Do not adjust for (it carries part of the effect) | |
| Collider (inverted fork) | Never adjust for (opens a spurious path) |
Key estimands and decomposition:
- (population average effect)
- (effect among treated units)
Experimentation: SRM, peeking, CUPED and bandits
Section titled “Experimentation: SRM, peeking, CUPED and bandits”# 1. SRM check on data/ab_test.csvcounts = ab["group"].value_counts().sort_index().to_numpy()srm = stats.chisquare(counts, f_exp=[counts.sum() / 2, counts.sum() / 2])print(f"SRM: chi2={srm.statistic:.4f}, p={srm.pvalue:.4f}")
# 2. CUPED formula (strictly pre-experiment X)rng = np.random.default_rng(42)x_pre = rng.normal(50, 10, size=2_000)treat = rng.binomial(1, 0.5, size=2_000)y = 0.8 * x_pre + 1.5 * treat + rng.normal(0, 6, size=2_000)theta = np.cov(y, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1)y_cuped = y - theta * (x_pre - x_pre.mean())print( f"SE raw={y.std(ddof=1) / np.sqrt(500):.3f} -> " f"CUPED={y_cuped.std(ddof=1) / np.sqrt(500):.3f}")
# 3. One Thompson sampling draw across 3 armswins, pulls = np.array([12, 20, 29]), np.array([200, 200, 200])draws = rng.beta(1 + wins, 1 + pulls - wins)print("Thompson draws:", np.round(draws, 3), "-> pick arm", int(np.argmax(draws)))SRM: chi2=0.0016, p=0.9681SE raw=0.449 -> CUPED=0.272Thompson draws: [0.038 0.094 0.124] -> pick arm 2Observational causal inference: IPW and DiD
Section titled “Observational causal inference: IPW and DiD”# Hajek IPW for has_autopay -> churnedcat_cols = ["payment_method", "contract", "plan", "region"]num_cols = ["age", "tenure_months", "monthly_charges"]pre = ColumnTransformer( [ ("cat", OneHotEncoder(drop="first", sparse_output=False), cat_cols), ("num", StandardScaler(), num_cols), ])pipe = make_pipeline(pre, LogisticRegression(max_iter=1000))t = customers["has_autopay"].to_numpy()y_c = customers["churned"].to_numpy()e = pipe.fit(customers[cat_cols + num_cols], t).predict_proba( customers[cat_cols + num_cols])[:, 1]w1, w0 = t / e, (1 - t) / (1 - e)ate_ipw = (w1 @ y_c) / w1.sum() - (w0 @ y_c) / w0.sum()print( f"Propensity range [{e.min():.3f}, {e.max():.3f}] | " f"Hajek IPW ATE = {ate_ipw:+.4f}")
# 2x2 Difference-in-Differences (regression form)did_df = pd.DataFrame( { "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1], "y": [58.43, 56.86, 77.14, 206.00], })did_est = smf.ols("y ~ treated * post", data=did_df).fit().params["treated:post"]print(f"2x2 DiD estimate = {did_est:+.2f}")Propensity range [0.087, 0.879] | Hajek IPW ATE = -0.02722x2 DiD estimate = +130.43Generalized Linear Models in statsmodels
Section titled “Generalized Linear Models in statsmodels”| Target | statsmodels call |
Link | Meaning of np.exp(coef) |
|---|---|---|---|
| Binary (0/1) | smf.glm(..., family=sm.families.Binomial()) |
Logit | Odds ratio |
| Count (equidispersed) | smf.glm(..., family=sm.families.Poisson()) |
Log | Incidence rate ratio (IRR) |
| Count (overdispersed) | smf.negativebinomial(...).fit(method="bfgs", disp=False) |
Log | Incidence rate ratio (IRR) |
| Positive right-skewed | smf.glm(..., family=sm.families.Gamma(sm.families.links.Log())) |
Log | Multiplicative mean ratio |
daily = sales.groupby("order_date")["order_id"].nunique().reset_index(name="orders")daily["order_date"] = pd.to_datetime(daily["order_date"])daily["dow"] = daily["order_date"].dt.day_name()daily["year_t"] = (daily["order_date"] - daily["order_date"].min()).dt.days / 365.0
pois = smf.glm( "orders ~ year_t + C(dow)", data=daily, family=sm.families.Poisson()).fit()nb = smf.negativebinomial("orders ~ year_t + C(dow)", data=daily).fit( method="bfgs", maxiter=300, disp=False)disp = pois.pearson_chi2 / pois.df_residprint( f"Poisson AIC={pois.aic:.1f} (Pearson/df={disp:.2f}) | " f"NegBin AIC={nb.aic:.1f} (IRR year_t={np.exp(nb.params['year_t']):.3f}x)")Poisson AIC=5399.0 (Pearson/df=3.09) | NegBin AIC=4844.0 (IRR year_t=1.425x)Survival analysis (Kaplan–Meier)
Section titled “Survival analysis (Kaplan–Meier)”m2m = customers.loc[customers["contract"] == "month-to-month"]t_m = m2m["tenure_months"].to_numpy()e_m = m2m["churned"].to_numpy()
surv, gw = 1.0, 0.0for tj in np.unique(t_m[e_m == 1]): if tj > 12: break n_risk = int(np.sum(t_m >= tj)) d_j = int(np.sum((t_m == tj) & (e_m == 1))) surv *= 1.0 - d_j / n_risk if n_risk > d_j: gw += d_j / (n_risk * (n_risk - d_j))se = surv * np.sqrt(gw)lo, hi = surv - 1.96 * se, surv + 1.96 * seprint(f"Month-to-month S(12) = {surv:.3f} (95% CI [{lo:.3f}, {hi:.3f}])")Month-to-month S(12) = 0.742 (95% CI [0.724, 0.760])Gotchas
Section titled “Gotchas”- Kitchen-sink regressions break causality: conditioning on a collider creates bias; conditioning on a mediator removes the effect you want to estimate.
- Post-treatment CUPED is biased: never put a metric measured during the experiment (like session duration or clicks) into CUPED as .
- SRM invalidates everything: if
stats.chisquareshows a mismatch in group counts (), stop and fix assignment/logging before computing lift. - Peeking inflates : repeated fixed-horizon z-tests push false positives from 5% to 20–30%; pre-register sample size or use sequential alpha-spending boundaries.
- Bandit logs are not A/B tests: adaptive arm selection biases naive p-values and sample means.
- Unchecked IPW weights explode variance: always inspect propensity overlap, use Hájek normalization, clip/trim extreme scores if needed, and verify max .
- GLM
bic_llfvs. discretebic:smf.glm(...).fit()exposes.bic_llf(log-likelihood BIC), whereassmf.negativebinomial(...).fit()exposes.bic. - Never drop censored customers: active subscribers belong in the Kaplan–Meier risk set
n_riskup to their observed tenure.