Skip to content

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 np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import stats
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from 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")
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 XX 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 P(T=1∣X)P(T=1 \mid X) 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
DAG pattern Path Action for total effect of TT on YY
Confounder (fork) T←Z→YT \leftarrow Z \rightarrow Y Adjust for ZZ to close the backdoor path
Mediator (chain) T→M→YT \rightarrow M \rightarrow Y Do not adjust for MM (it carries part of the effect)
Collider (inverted fork) T→C←YT \rightarrow C \leftarrow Y Never adjust for CC (opens a spurious path)

Key estimands and decomposition:

  • ATE=E[Y(1)−Y(0)]\text{ATE} = \mathbb{E}[Y(1) - Y(0)] (population average effect)
  • ATT=E[Y(1)−Y(0)∣T=1]\text{ATT} = \mathbb{E}[Y(1) - Y(0) \mid T = 1] (effect among treated units)
  • E[Y∣T=1]−E[Y∣T=0]=ATT+(E[Y(0)∣T=1]−E[Y(0)∣T=0])\mathbb{E}[Y \mid T=1] - \mathbb{E}[Y \mid T=0] = \text{ATT} + \big(\mathbb{E}[Y(0) \mid T=1] - \mathbb{E}[Y(0) \mid T=0]\big)

Experimentation: SRM, peeking, CUPED and bandits

Section titled “Experimentation: SRM, peeking, CUPED and bandits”
# 1. SRM check on data/ab_test.csv
counts = 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 arms
wins, 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)))
Output
SRM: chi2=0.0016, p=0.9681
SE raw=0.449 -> CUPED=0.272
Thompson draws: [0.038 0.094 0.124] -> pick arm 2

Observational causal inference: IPW and DiD

Section titled “Observational causal inference: IPW and DiD”
# Hajek IPW for has_autopay -> churned
cat_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}")
Output
Propensity range [0.087, 0.879] | Hajek IPW ATE = -0.0272
2x2 DiD estimate = +130.43
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_resid
print(
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)"
)
Output
Poisson AIC=5399.0 (Pearson/df=3.09) | NegBin AIC=4844.0 (IRR year_t=1.425x)
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.0
for 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 * se
print(f"Month-to-month S(12) = {surv:.3f} (95% CI [{lo:.3f}, {hi:.3f}])")
Output
Month-to-month S(12) = 0.742 (95% CI [0.724, 0.760])
  • 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 XX.
  • SRM invalidates everything: if stats.chisquare shows a mismatch in group counts (p<0.001p \lt 0.001), stop and fix assignment/logging before computing lift.
  • Peeking inflates α\alpha: 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 ∣SMD∣<0.10\lvert\text{SMD}\rvert \lt 0.10.
  • GLM bic_llf vs. discrete bic: smf.glm(...).fit() exposes .bic_llf (log-likelihood BIC), whereas smf.negativebinomial(...).fit() exposes .bic.
  • Never drop censored customers: active subscribers belong in the Kaplan–Meier risk set n_risk up to their observed tenure.