49. Causal inference, GLMs and advanced experimentation — Exercises
Practice module 49 across three tiers: 8 warm-ups, 12 core problems and 5 challenges. Each exercise runs in a fresh namespace after the setup block. Try to solve each problem before opening the hints or solution.
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
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)Warm-up
Section titled “Warm-up”M49-W01 · Compute ATE, ATT and selection bias from potential outcomes
Section titled “M49-W01 · Compute ATE, ATT and selection bias from potential outcomes”Write the code: given a small oracle table of potential outcomes y0, y1 and treatment assignments t, compute the true ATE, the true ATT, the naive observed difference in means, and the selection bias (naive - ATT). Print all four rounded to 2 decimals.
ATE=2.67 ATT=2.67 naive=10.00 selection_bias=7.33y0 = np.array([10.0, 12.0, 14.0, 16.0, 20.0, 22.0])y1 = np.array([13.0, 15.0, 16.0, 18.0, 23.0, 25.0])t = np.array([0, 0, 0, 1, 1, 1])
# TODO: compute y_obs, ate, att, naive, and selection_biasHint 1
The observed outcome is y_obs = np.where(t == 1, y1, y0). ATE averages y1 - y0 over all units; ATT averages y1 - y0 over t == 1.
Hint 2
Selection bias equals y0[t == 1].mean() - y0[t == 0].mean(), which also equals naive - att.
Solution
y0 = np.array([10.0, 12.0, 14.0, 16.0, 20.0, 22.0])y1 = np.array([13.0, 15.0, 16.0, 18.0, 23.0, 25.0])t = np.array([0, 0, 0, 1, 1, 1])
y_obs = np.where(t == 1, y1, y0)ate = float(np.mean(y1 - y0))att = float(np.mean((y1 - y0)[t == 1]))naive = float(y_obs[t == 1].mean() - y_obs[t == 0].mean())selection_bias = float(y0[t == 1].mean() - y0[t == 0].mean())
print( f"ATE={ate:.2f} ATT={att:.2f} naive={naive:.2f} " f"selection_bias={selection_bias:.2f}")assert np.isclose(naive, att + selection_bias)assert np.isclose(ate, 2.67, atol=0.01)ATE=2.67 ATT=2.67 naive=10.00 selection_bias=7.33How it works:
np.where(t == 1, y1, y0)reveals only the realized potential outcome per unit.- High-baseline units (
y0 = 16, 20, 22) were assigned to treatment, creating+7.33of selection bias on top of the+2.67ATT.
M49-W02 · Identify a confounder, mediator or collider
Section titled “M49-W02 · Identify a confounder, mediator or collider”Predict the output: read the three DAG rules below and predict what each lookup prints for estimating the total causal effect of T on Y. Do not run the code before writing down your prediction.
Acceptance criteria:
- Write your prediction for all three lines before running the code.
- Your prediction matches the Output inside the solution exactly.
# Three causal roles for a third variable X relative to T -> Y:# 1. T <- X -> Y# 2. T -> X -> Y# 3. T -> X <- Y# TODO: predict whether each role is confounder, mediator or collider,# and whether to adjust ("adjust") or leave out ("do not adjust").Hint 1
A fork (T <- X -> Y) is a common cause; a chain (T -> X -> Y) transmits the effect; an inverted fork (T -> X <- Y) is a common effect.
Hint 2
Only confounders should be adjusted for when estimating a total causal effect.
Solution
patterns = [ ("T <- X -> Y", "confounder", "adjust"), ("T -> X -> Y", "mediator", "do not adjust"), ("T -> X <- Y", "collider", "do not adjust"),]for path, role, action in patterns: print(f"{path:<13} -> {role:<10} ({action})")
assert [r for _, r, _ in patterns] == ["confounder", "mediator", "collider"]assert sum(1 for _, _, a in patterns if a == "adjust") == 1T <- X -> Y -> confounder (adjust)T -> X -> Y -> mediator (do not adjust)T -> X <- Y -> collider (do not adjust)How it works:
- Adjusting for a confounder blocks the backdoor path.
- Adjusting for a mediator blocks the causal path itself; adjusting for a collider opens a spurious path between its causes.
M49-W03 · Run a Sample Ratio Mismatch check
Section titled “M49-W03 · Run a Sample Ratio Mismatch check”Write the code: check two experiments against a planned 50/50 split using scipy.stats.chisquare: (a) data/ab_test.csv and (b) a synthetic experiment with 5,220 control users and 4,780 treatment users. Flag an experiment as "SRM ALERT" if p < 0.001, else "OK".
ab_test chi2= 0.0016 p=9.68e-01 status=OKbroken chi2=19.3600 p=1.08e-05 status=SRM ALERTab = pd.read_csv("data/ab_test.csv")# TODO: extract control/treatment counts from ab, run stats.chisquare on both splitsHint 1
Use ab["group"].value_counts().sort_index().to_numpy() for the observed counts and [n / 2, n / 2] for f_exp.
Hint 2
Compare res.pvalue < 0.001 to choose "SRM ALERT" vs. "OK".
Solution
ab = pd.read_csv("data/ab_test.csv")real_counts = ab["group"].value_counts().sort_index().to_numpy()bad_counts = np.array([5220, 4780])
statuses = {}for label, obs in [("ab_test", real_counts), ("broken", bad_counts)]: exp = [obs.sum() / 2, obs.sum() / 2] res = stats.chisquare(obs, f_exp=exp) status = "SRM ALERT" if res.pvalue < 0.001 else "OK" statuses[label] = status print(f"{label:<8} chi2={res.statistic:7.4f} p={res.pvalue:.2e} status={status}")
assert statuses["ab_test"] == "OK"assert statuses["broken"] == "SRM ALERT"ab_test chi2= 0.0016 p=9.68e-01 status=OKbroken chi2=19.3600 p=1.08e-05 status=SRM ALERTHow it works:
stats.chisquaretests observed group counts against expected 50/50 counts.data/ab_test.csvhas a 5,002 / 4,998 split (), whereas a 5,220 / 4,780 split fails decisively ().
M49-W04 · Compute CUPED theta and variance reduction
Section titled “M49-W04 · Compute CUPED theta and variance reduction”Write the code: given pre-experiment metric x and experiment outcome y for 1,000 simulated users, compute the optimal pooled theta = cov(y, x) / var(x), build y_cuped = y - theta * (x - x.mean()), and verify that 1 - var(y_cuped) / var(y) equals the squared Pearson correlation .
theta=0.6957 var_reduction=0.6180 rho^2=0.6180rng = np.random.default_rng(42)x = rng.normal(100, 15, size=1_000)y = 0.7 * x + rng.normal(0, 8, size=1_000)
# TODO: compute theta, y_cuped, empirical variance reduction and rho**2Hint 1
Use np.cov(y, x, ddof=1)[0, 1] / np.var(x, ddof=1) for theta.
Hint 2
rho = np.corrcoef(x, y)[0, 1], and empirical variance reduction is 1 - np.var(y_cuped, ddof=1) / np.var(y, ddof=1).
Solution
rng = np.random.default_rng(42)x = rng.normal(100, 15, size=1_000)y = 0.7 * x + rng.normal(0, 8, size=1_000)
theta = float(np.cov(y, x, ddof=1)[0, 1] / np.var(x, ddof=1))y_cuped = y - theta * (x - x.mean())var_red = float(1.0 - np.var(y_cuped, ddof=1) / np.var(y, ddof=1))rho_sq = float(np.corrcoef(x, y)[0, 1] ** 2)
print(f"theta={theta:.4f} var_reduction={var_red:.4f} rho^2={rho_sq:.4f}")assert np.isclose(var_red, rho_sq, atol=1e-12)assert np.isclose(y_cuped.mean(), y.mean(), atol=1e-12)theta=0.6957 var_reduction=0.6180 rho^2=0.6180How it works:
- Subtracting
theta * (x - x.mean())leaves the sample mean unchanged while stripping out the component ofylinearly predictable fromx. - The fractional variance drop equals identically.
M49-W05 · Update Beta parameters for Thompson sampling
Section titled “M49-W05 · Update Beta parameters for Thompson sampling”Write the code: three checkout arms start with uniform Beta(1, 1) priors. After observing (wins, pulls) of (14, 150), (22, 150) and (31, 150), compute each arm’s posterior (alpha, beta), posterior mean, and draw 5,000 samples (rng = np.random.default_rng(42)) to print each arm’s probability of being selected next.
arm 0: Beta(15, 137) mean=0.099 P(pick)=0.003arm 1: Beta(23, 129) mean=0.151 P(pick)=0.082arm 2: Beta(32, 120) mean=0.211 P(pick)=0.915wins = np.array([14, 22, 31])pulls = np.array([150, 150, 150])# TODO: posterior alpha/beta, posterior means, and Monte Carlo selection probabilitiesHint 1
With a Beta(1, 1) prior, alpha = 1 + wins and beta = 1 + (pulls - wins).
Hint 2
Draw samples = rng.beta(alpha, beta, size=(5_000, 3)) and take np.argmax(samples, axis=1).
Solution
wins = np.array([14, 22, 31])pulls = np.array([150, 150, 150])alpha = 1 + winsbeta = 1 + (pulls - wins)post_mean = alpha / (alpha + beta)
rng = np.random.default_rng(42)draws = rng.beta(alpha, beta, size=(5_000, len(wins)))chosen = np.argmax(draws, axis=1)probs = np.bincount(chosen, minlength=len(wins)) / len(chosen)
for i in range(len(wins)): print( f"arm {i}: Beta({alpha[i]}, {beta[i]}) " f"mean={post_mean[i]:.3f} P(pick)={probs[i]:.3f}" )
assert np.isclose(probs.sum(), 1.0)assert probs[2] > probs[1] > probs[0]arm 0: Beta(15, 137) mean=0.099 P(pick)=0.003arm 1: Beta(23, 129) mean=0.151 P(pick)=0.082arm 2: Beta(32, 120) mean=0.211 P(pick)=0.915How it works:
- Beta–Binomial conjugacy updates
(alpha, beta)in arithmetic per batch. - Thompson sampling selects each arm in proportion to its posterior probability of being the best arm.
M49-W06 · Calculate the 2×2 Difference-in-Differences estimate
Section titled “M49-W06 · Calculate the 2×2 Difference-in-Differences estimate”Write the code: a promo email was sent to Region A (treated = 1) in Week 2 (post = 1) while Region B (treated = 0) received no promo. Given mean daily orders A_pre = 42.0, A_post = 55.5, B_pre = 38.0, B_post = 43.0, compute the DiD lift by hand and verify it matches smf.ols("y ~ treated * post", data=df).
manual DiD = +8.50 | OLS interaction = +8.50df = pd.DataFrame( { "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1], "y": [38.0, 43.0, 42.0, 55.5], })# TODO: compute manual 2x2 DiD and compare with smf.ols interaction coefficientHint 1
Manual DiD is (55.5 - 42.0) - (43.0 - 38.0).
Hint 2
The interaction parameter in smf.ols("y ~ treated * post", data=df).fit().params is named "treated:post".
Solution
df = pd.DataFrame( { "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1], "y": [38.0, 43.0, 42.0, 55.5], })did_manual = (55.5 - 42.0) - (43.0 - 38.0)did_ols = float(smf.ols("y ~ treated * post", data=df).fit().params["treated:post"])print(f"manual DiD = {did_manual:+.2f} | OLS interaction = {did_ols:+.2f}")
assert np.isclose(did_manual, 8.5)assert np.isclose(did_manual, did_ols)manual DiD = +8.50 | OLS interaction = +8.50How it works:
- Region A grew by
+13.5orders, while control Region B grew by+5.0orders due to common seasonality. - Subtracting the common trend leaves a DiD estimate of
+8.5orders/day, identical to thetreated:postOLS interaction.
M49-W07 · Convert GLM log-link coefficients to incidence rate ratios
Section titled “M49-W07 · Convert GLM log-link coefficients to incidence rate ratios”Write the code: given log-link coefficients from a Poisson GLM ({"promo": 0.25, "weekend": 0.40, "price_hike": -0.15}), convert each coefficient into its Incidence Rate Ratio (IRR) and percent change in expected count.
promo beta=+0.25 IRR=1.284x change=+28.4%weekend beta=+0.40 IRR=1.492x change=+49.2%price_hike beta=-0.15 IRR=0.861x change=-13.9%coefs = {"promo": 0.25, "weekend": 0.40, "price_hike": -0.15}# TODO: compute IRR = exp(beta) and percent change = (IRR - 1) * 100Hint 1
For a log link , a +1 increase in multiplies by np.exp(beta_j).
Hint 2
Percent change is (irr - 1.0) * 100.
Solution
coefs = {"promo": 0.25, "weekend": 0.40, "price_hike": -0.15}irrs = {}for name, beta in coefs.items(): irr = float(np.exp(beta)) pct = (irr - 1.0) * 100.0 irrs[name] = irr print(f"{name:<11} beta={beta:+.2f} IRR={irr:.3f}x change={pct:+.1f}%")
assert irrs["promo"] > 1.0 and irrs["price_hike"] < 1.0assert np.isclose(irrs["weekend"], np.exp(0.40))promo beta=+0.25 IRR=1.284x change=+28.4%weekend beta=+0.40 IRR=1.492x change=+49.2%price_hike beta=-0.15 IRR=0.861x change=-13.9%How it works:
- Because , adding to the linear predictor multiplies by .
- Negative coefficients yield IRRs below
1.0(a percentage decrease in expected count).
M49-W08 · Compute one Kaplan–Meier survival curve on a small cohort
Section titled “M49-W08 · Compute one Kaplan–Meier survival curve on a small cohort”Write the code: compute the Kaplan–Meier survival probability at each observed event time for a 6-customer cohort with tenure = [2, 3, 4, 4, 6, 8] and churned = [1, 0, 1, 1, 0, 1]. Notice how the two censored customers (churned == 0 at months 3 and 6) stay in n_risk until they leave.
t=2 n_risk=6 events=1 S(t)=0.8333t=4 n_risk=4 events=2 S(t)=0.4167t=8 n_risk=1 events=1 S(t)=0.0000tenure = np.array([2, 3, 4, 4, 6, 8])churned = np.array([1, 0, 1, 1, 0, 1])# TODO: loop over unique event times, compute n_risk, d_j, and running S(t)Hint 1
The unique event times are np.unique(tenure[churned == 1]) -> [2, 4, 8].
Hint 2
At each event time tj, n_risk = np.sum(tenure >= tj) and d_j = np.sum((tenure == tj) & (churned == 1)). Multiply surv *= (1 - d_j / n_risk).
Solution
tenure = np.array([2, 3, 4, 4, 6, 8])churned = np.array([1, 0, 1, 1, 0, 1])
surv = 1.0out = {}for tj in np.unique(tenure[churned == 1]): n_risk = int(np.sum(tenure >= tj)) d_j = int(np.sum((tenure == tj) & (churned == 1))) surv *= 1.0 - d_j / n_risk out[int(tj)] = surv print(f"t={tj} n_risk={n_risk} events={d_j} S(t)={surv:.4f}")
assert np.isclose(out[2], 5 / 6)assert np.isclose(out[4], (5 / 6) * (2 / 4))assert np.isclose(out[8], 0.0)t=2 n_risk=6 events=1 S(t)=0.8333t=4 n_risk=4 events=2 S(t)=0.4167t=8 n_risk=1 events=1 S(t)=0.0000How it works:
- At
t = 2, all 6 customers are at risk and 1 churns (S = 5/6). - The customer censored at
t = 3leaves beforet = 4, son_risk = 4att = 4(not 5). Two churn there, dropping survival to(5/6) * (2/4) = 0.4167.
M49-C01 · Demonstrate collider bias in a simulation
Section titled “M49-C01 · Demonstrate collider bias in a simulation”Write the code: simulate 5,000 applicants where coding_skill and communication_skill are independent standard normals (rng = np.random.default_rng(42)). Suppose a company hires an applicant (hired = 1) whenever coding_skill + communication_skill > 1.2. Compute the Pearson correlation between the two skills (a) across all applicants and (b) conditioned on hired == 1.
All applicants (n=5000): r=-0.034 (p=0.017)Hired only (n=947): r=-0.650 (p=6.82e-115)rng = np.random.default_rng(42)coding = rng.normal(size=5_000)comm = rng.normal(size=5_000)hired = (coding + comm) > 1.2
# TODO: compute Pearson correlation overall vs among hired applicants onlyHint 1
Use stats.pearsonr(coding, comm) overall, and stats.pearsonr(coding[hired], comm[hired]) inside the hired subset.
Hint 2
hired is a collider (coding -> hired <- comm), so conditioning on hired == 1 creates a strong negative correlation even though the two traits are independent in the population.
Solution
rng = np.random.default_rng(42)coding = rng.normal(size=5_000)comm = rng.normal(size=5_000)hired = (coding + comm) > 1.2
r_all, p_all = stats.pearsonr(coding, comm)r_hired, p_hired = stats.pearsonr(coding[hired], comm[hired])print(f"All applicants (n={len(coding)}): r={r_all:+.3f} (p={p_all:.3f})")print(f"Hired only (n={int(hired.sum())}): r={r_hired:+.3f} (p={p_hired:.2e})")
assert abs(r_all) < 0.05assert r_hired < -0.40 and p_hired < 1e-10All applicants (n=5000): r=-0.034 (p=0.017)Hired only (n=947): r=-0.650 (p=6.82e-115)How it works:
- Across all 5,000 applicants,
codingandcommare uncorrelated (rnear 0). - Conditioning on the collider
hired == 1induces a strong spurious negative correlation: knowing a hired candidate has lower coding skill forces their communication skill to be high enough to pass the bar.
M49-C02 · Uncover Simpson’s paradox in segmented conversion rates
Section titled “M49-C02 · Uncover Simpson’s paradox in segmented conversion rates”Interpret a result: an analytics dashboard reports that Checkout B converts worse than Checkout A overall (12.2% vs. 14.5%). Use the segmented table below to compute the lift inside each customer tier (new vs. returning), the pooled lift, and the weighted average lift (stratifying by tier shares). Print all numbers and identify which checkout actually wins.
variant A B lifttiernew 0.01 0.097 0.087returning 0.16 0.180 0.020Pooled lift (B - A): -0.0230Stratified ATE (B - A): +0.0469Winner: Bdata = pd.DataFrame( [ ("returning", "A", 900, 144), ("returning", "B", 300, 54), ("new", "A", 100, 1), ("new", "B", 700, 68), ], columns=["tier", "variant", "visitors", "buyers"],)# TODO: compute per-tier lift, pooled lift, and tier-share-weighted liftHint 1
Pivot rate = buyers / visitors by index="tier", columns="variant", then compute lift = B - A.
Hint 2
The overall tier shares are tier_weights = data.groupby("tier")["visitors"].sum() / data["visitors"].sum(). Multiply tier_weights by the per-tier lifts and sum to get the standardized ATE.
Solution
data = pd.DataFrame( [ ("returning", "A", 900, 144), ("returning", "B", 300, 54), ("new", "A", 100, 1), ("new", "B", 700, 68), ], columns=["tier", "variant", "visitors", "buyers"],)data["rate"] = data["buyers"] / data["visitors"]piv = data.pivot(index="tier", columns="variant", values="rate")piv["lift"] = piv["B"] - piv["A"]
pooled = data.groupby("variant")[["buyers", "visitors"]].sum()pooled_lift = float( pooled.loc["B", "buyers"] / pooled.loc["B", "visitors"] - pooled.loc["A", "buyers"] / pooled.loc["A", "visitors"])tier_w = data.groupby("tier")["visitors"].sum() / data["visitors"].sum()adj_lift = float((piv["lift"] * tier_w).sum())
print(piv.round(4))print(f"Pooled lift (B - A): {pooled_lift:+.4f}")print(f"Stratified ATE (B - A): {adj_lift:+.4f}")print("Winner:", "B" if adj_lift > 0 else "A")
assert pooled_lift < 0 < adj_liftassert (piv["lift"] > 0).all()variant A B lifttiernew 0.01 0.097 0.087returning 0.16 0.180 0.020Pooled lift (B - A): -0.0230Stratified ATE (B - A): +0.0469Winner: BHow it works:
- Variant B outperforms Variant A in both
new(+8.7 pp) andreturning(+2.0 pp) segments. - Because 90% of A’s traffic was high-converting returning users while 70% of B’s traffic was new users, pooling reverses the sign. Stratifying by the confounder
tierrecovers the true+4.7pp advantage for B.
M49-C03 · Fix the bug: peeking with repeated z-tests
Section titled “M49-C03 · Fix the bug: peeking with repeated z-tests”Fix the bug: a teammate runs 500 A/A simulations (n_per_arm = 1,000, p0 = 0.10) and checks a two-proportion z-test every 100 users (10 peeks) using the unadjusted critical value z > 1.96. Compare the false-positive rate of the buggy unadjusted threshold against a Bonferroni-adjusted sequential threshold (alpha / 10 per look) so overall Type I error stays at or below 0.05.
Naive (z>1.96): FPR = 0.170Bonferroni (z>2.81): FPR = 0.022rng = np.random.default_rng(42)n_sims, n_per_arm, p0, k = 500, 1_000, 0.10, 10ctrl = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)trt = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)
# BUGGY threshold: z_crit = stats.norm.ppf(1 - 0.05 / 2)# TODO: compute false-positive rate for naive threshold vs Bonferroni (alpha / k)Hint 1
Checkpoints are np.linspace(100, 1000, 10, dtype=int). For each checkpoint n_now, compute the pooled two-proportion |z| across all 500 simulations.
Hint 2
For Bonferroni across k = 10 two-sided looks, z_bonf = stats.norm.ppf(1 - (0.05 / k) / 2).
Solution
rng = np.random.default_rng(42)n_sims, n_per_arm, p0, k = 500, 1_000, 0.10, 10ctrl = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)trt = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)checkpoints = np.linspace(n_per_arm // k, n_per_arm, k, dtype=int)
max_z = np.zeros(n_sims)for n_now in checkpoints: c_now = ctrl[:, n_now - 1] t_now = trt[:, n_now - 1] p_pool = (c_now + t_now) / (2 * n_now) se = np.sqrt(np.maximum(2 * p_pool * (1 - p_pool) / n_now, 1e-12)) z = np.abs((t_now - c_now) / n_now) / se max_z = np.maximum(max_z, z)
z_naive = float(stats.norm.ppf(1 - 0.05 / 2))z_bonf = float(stats.norm.ppf(1 - (0.05 / k) / 2))fpr_naive = float(np.mean(max_z > z_naive))fpr_bonf = float(np.mean(max_z > z_bonf))
print(f"Naive (z>{z_naive:.2f}): FPR = {fpr_naive:.3f}")print(f"Bonferroni (z>{z_bonf:.2f}): FPR = {fpr_bonf:.3f}")
assert fpr_naive > 0.12assert fpr_bonf <= 0.05Naive (z>1.96): FPR = 0.170Bonferroni (z>2.81): FPR = 0.022How it works:
- Tracking
max_zacross all 10 checkpoints evaluates whether a simulation ever crossed the threshold at any peek. - Tightening the critical value from
1.96to2.81restores Type I error control below0.05.
M49-C04 · Apply CUPED to 2024 customer revenue
Section titled “M49-C04 · Apply CUPED to 2024 customer revenue”Write the code: using data/sales.csv and data/customers.csv, build the 2023 (pre) and 2024 (post) total revenue per customer for customers who signed up before 2023-07-01. Assign 50/50 random treatment (rng = np.random.default_rng(7)), add a true lift of USD 40 to treated 2024 revenue, and compare raw vs. CUPED standard error and variance reduction.
Raw diff=+105.13 SE=33.05CUPED diff=+73.10 SE=29.69 var_reduction=19.3%customers = pd.read_csv("data/customers.csv")sales = pd.read_csv("data/sales.csv")# TODO: aggregate 2023 & 2024 revenue per eligible customer, apply CUPED, compare SEsHint 1
Group sales by ["customer_id", "year"] summing revenue, .unstack(fill_value=0), then .reindex(eligible, fill_value=0).
Hint 2
Compute theta on (y_obs, x_pre) without treatment labels, then compute se = np.sqrt(y1.var(ddof=1)/len(y1) + y0.var(ddof=1)/len(y0)) for both y_obs and y_cuped.
Solution
customers = pd.read_csv("data/customers.csv")sales = pd.read_csv("data/sales.csv")sales["year"] = pd.to_datetime(sales["order_date"]).dt.yeareligible = customers.loc[customers["signup_date"] < "2023-07-01", "customer_id"]
rev = ( sales.groupby(["customer_id", "year"])["revenue"] .sum() .unstack(fill_value=0.0) .reindex(eligible, fill_value=0.0))x_pre = rev[2023].to_numpy()rng = np.random.default_rng(7)t = rng.binomial(1, 0.5, size=len(eligible))y_obs = rev[2024].to_numpy() + 40.0 * t
theta = float(np.cov(y_obs, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))y_cuped = y_obs - theta * (x_pre - x_pre.mean())
def diff_se(y: np.ndarray, tr: np.ndarray) -> tuple[float, float]: y1, y0 = y[tr == 1], y[tr == 0] diff = float(y1.mean() - y0.mean()) se = float(np.sqrt(y1.var(ddof=1) / len(y1) + y0.var(ddof=1) / len(y0))) return diff, se
d_raw, se_raw = diff_se(y_obs, t)d_cup, se_cup = diff_se(y_cuped, t)vr = 1.0 - (se_cup / se_raw) ** 2print(f"Raw diff={d_raw:+.2f} SE={se_raw:.2f}")print(f"CUPED diff={d_cup:+.2f} SE={se_cup:.2f} var_reduction={vr:.1%}")
assert se_cup < se_rawassert 0.15 < vr < 0.25Raw diff=+105.13 SE=33.05CUPED diff=+73.10 SE=29.69 var_reduction=19.3%How it works:
- Customer revenue is noisier than order count because of occasional high-ticket electronics purchases, so 2023–2024 revenue correlation is about
0.44. - Even so, CUPED cuts variance by roughly 19%, tightening the standard error for free.
M49-C05 · Implement epsilon-greedy vs. UCB1 bandits
Section titled “M49-C05 · Implement epsilon-greedy vs. UCB1 bandits”Write the code: simulate 2,000 visitors across 3 arms with true conversion rates [0.05, 0.09, 0.13] using rng = np.random.default_rng(42) for two strategies: eps_greedy (epsilon = 0.15) and ucb1 (exploration bonus sqrt(2 * ln(t) / pulls)). Print each strategy’s total conversions, cumulative expected regret, and pull counts.
eps_greedy conv=231 regret= 16.5 pulls=[160, 93, 1747]ucb1 conv=197 regret= 45.4 pulls=[348, 438, 1214]rates = np.array([0.05, 0.09, 0.13])# TODO: implement simulate(strategy) for 2,000 visitors and compare eps_greedy vs ucb1Hint 1
Always pull each arm once on steps t = 1, 2, 3 so pulls is strictly positive before dividing.
Hint 2
At each step, regret += rates.max() - rates[arm]. Use a fresh np.random.default_rng(42) inside each strategy run.
Solution
rates = np.array([0.05, 0.09, 0.13])best = float(rates.max())
def simulate(strategy: str, n: int = 2_000) -> tuple[int, float, list[int]]: rng = np.random.default_rng(42) k = len(rates) pulls = np.zeros(k, dtype=int) wins = np.zeros(k, dtype=int) regret = 0.0 for t in range(1, n + 1): if t <= k: arm = t - 1 elif strategy == "eps_greedy": if rng.random() < 0.15: arm = int(rng.integers(k)) else: arm = int(np.argmax(wins / pulls)) else: ucb = wins / pulls + np.sqrt(2.0 * np.log(t) / pulls) arm = int(np.argmax(ucb)) wins[arm] += int(rng.random() < rates[arm]) pulls[arm] += 1 regret += best - rates[arm] return int(wins.sum()), regret, pulls.tolist()
out = {}for strat in ["eps_greedy", "ucb1"]: conv, reg, pulls = simulate(strat) out[strat] = (conv, reg, pulls) print(f"{strat:<11} conv={conv:>3d} regret={reg:>5.1f} pulls={pulls}")
assert out["eps_greedy"][2][2] > out["eps_greedy"][2][0]assert out["ucb1"][2][2] > out["ucb1"][2][0]eps_greedy conv=231 regret= 16.5 pulls=[160, 93, 1747]ucb1 conv=197 regret= 45.4 pulls=[348, 438, 1214]How it works:
- Both strategies send the majority of traffic to arm 2 (the 13% winner).
- UCB1 explores systematically based on uncertainty (
sqrt(2 ln t / n_a)), whereas -greedy keeps allocating a flat 15% of pulls uniformly at random.
M49-C06 · Check propensity overlap and trim extreme weights
Section titled “M49-C06 · Check propensity overlap and trim extreme weights”Write the code: fit a logistic propensity model for has_autopay on data/customers.csv using payment_method, contract, plan, region, age, tenure_months and monthly_charges. Compute the maximum IPW weight, the Hájek IPW ATE on the full sample, and the Hájek IPW ATE after trimming to the [0.10, 0.90] common-support region.
Full n=5000 max_w=11.11 ATE=-0.0272Trimmed n=4996 max_w=9.43 ATE=-0.0270customers = pd.read_csv("data/customers.csv")cat_cols = ["payment_method", "contract", "plan", "region"]num_cols = ["age", "tenure_months", "monthly_charges"]# TODO: fit propensity pipeline, compute max weight, full IPW ATE, and trimmed IPW ATEHint 1
w = np.where(t == 1, 1 / ps, 1 / (1 - ps)) gives every unit’s IPW weight.
Hint 2
Filter with keep = (ps >= 0.10) & (ps <= 0.90) before recomputing Hájek IPW.
Solution
customers = pd.read_csv("data/customers.csv")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 = customers["churned"].to_numpy()ps = pipe.fit(customers[cat_cols + num_cols], t).predict_proba( customers[cat_cols + num_cols])[:, 1]
def hajek(yv: np.ndarray, tv: np.ndarray, ev: np.ndarray) -> float: w1, w0 = tv / ev, (1 - tv) / (1 - ev) return float((w1 @ yv) / w1.sum() - (w0 @ yv) / w0.sum())
weights = np.where(t == 1, 1.0 / ps, 1.0 / (1.0 - ps))keep = (ps >= 0.10) & (ps <= 0.90)ate_full = hajek(y, t, ps)ate_trim = hajek(y[keep], t[keep], ps[keep])
print(f"Full n={len(y)} max_w={weights.max():.2f} ATE={ate_full:+.4f}")print( f"Trimmed n={int(keep.sum())} " f"max_w={weights[keep].max():.2f} ATE={ate_trim:+.4f}")
assert keep.sum() < len(y)assert weights[keep].max() <= 10.0assert abs(ate_full - ate_trim) < 0.01Full n=5000 max_w=11.11 ATE=-0.0272Trimmed n=4996 max_w=9.43 ATE=-0.0270How it works:
- Checking whether trimming moves the ATE is a standard sensitivity diagnostic for positivity.
- Here both full and
[0.10, 0.90]-trimmed estimates agree closely, confirming the result is not driven by extreme weights.
M49-C07 · Compute covariate balance (SMD) before and after IPW
Section titled “M49-C07 · Compute covariate balance (SMD) before and after IPW”Write the code: using the same has_autopay propensity model on data/customers.csv, compute the absolute Standardized Mean Difference (|SMD|) before and after IPW for payment_method_electronic_check, payment_method_credit_card, age and monthly_charges. Verify every covariate drops below 0.10 after weighting.
payment_method_electronic_check raw=1.1357 -> ipw=0.0095payment_method_credit_card raw=0.5847 -> ipw=0.0028age raw=0.0752 -> ipw=0.0137monthly_charges raw=0.0460 -> ipw=0.0074customers = pd.read_csv("data/customers.csv")# TODO: fit propensity model, compute raw and IPW |SMD| for the 4 named featuresHint 1
X_mat = pre.transform(X) gives the encoded numeric matrix; strip the transformer prefix with name.split("__", 1)[1].
Hint 2
Use np.average(col[m1], weights=w[m1]) and np.average((col[m1] - mu1)**2, weights=w[m1]) for weighted mean and variance.
Solution
customers = pd.read_csv("data/customers.csv")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), ])X = customers[cat_cols + num_cols]t = customers["has_autopay"].to_numpy()pipe = make_pipeline(pre, LogisticRegression(max_iter=1000)).fit(X, t)ps = pipe.predict_proba(X)[:, 1]w = np.where(t == 1, 1.0 / ps, 1.0 / (1.0 - ps))
X_mat = pre.transform(X)names = [c.split("__", 1)[1] for c in pre.get_feature_names_out()]df_x = pd.DataFrame(X_mat, columns=names)
def abs_smd(vals: np.ndarray, tr: np.ndarray, wt: np.ndarray | None = None) -> float: m1, m0 = tr == 1, tr == 0 if wt is None: mu1, mu0 = vals[m1].mean(), vals[m0].mean() v1, v0 = vals[m1].var(ddof=1), vals[m0].var(ddof=1) else: mu1 = float(np.average(vals[m1], weights=wt[m1])) mu0 = float(np.average(vals[m0], weights=wt[m0])) v1 = float(np.average((vals[m1] - mu1) ** 2, weights=wt[m1])) v0 = float(np.average((vals[m0] - mu0) ** 2, weights=wt[m0])) return abs(mu1 - mu0) / float(np.sqrt(0.5 * (v1 + v0)))
targets = [ "payment_method_electronic_check", "payment_method_credit_card", "age", "monthly_charges",]after_vals = []for col in targets: v = df_x[col].to_numpy() raw, adj = abs_smd(v, t), abs_smd(v, t, w) after_vals.append(adj) print(f"{col:<32} raw={raw:.4f} -> ipw={adj:.4f}")
assert max(after_vals) < 0.02payment_method_electronic_check raw=1.1357 -> ipw=0.0095payment_method_credit_card raw=0.5847 -> ipw=0.0028age raw=0.0752 -> ipw=0.0137monthly_charges raw=0.0460 -> ipw=0.0074How it works:
- Standardized Mean Difference puts binary indicators and continuous features on the same scale.
- IPW drives all four confounders — including
electronic_check, which starts above1.13— well under0.02.
M49-C08 · Test parallel trends before running Difference-in-Differences
Section titled “M49-C08 · Test parallel trends before running Difference-in-Differences”Write the code: in data/web_traffic.csv, a marketing campaign launches on 2024-09-16 (ISO week 38). Compare 2024 (treated = 1) against 2023 (treated = 0, which had no September campaign) on daily signups: first test parallel pre-trends on ISO weeks 36 → 37, then estimate the DiD campaign lift on ISO weeks 37 → 38 with HC3 standard errors.
Pre-trend (w36->w37): diff=+4.29, p=0.6541Campaign DiD (w38): lift=+88.86, SE=27.00, p=0.0010wt = pd.read_csv("data/web_traffic.csv")wt["date"] = pd.to_datetime(wt["date"])wt["year"] = wt["date"].dt.yearwt["iso_week"] = wt["date"].dt.isocalendar().week.astype(int)# TODO: pre-trend OLS on weeks 36-37, then DiD OLS on weeks 37-38 (cov_type="HC3")Hint 1
Filter wt["year"].isin([2023, 2024]) and create treated = (year == 2024).astype(int).
Hint 2
Fit smf.ols("signups ~ treated * w37", data=pre).fit(cov_type="HC3") for the pre-trend check, and smf.ols("signups ~ treated * post", data=did_df).fit(cov_type="HC3") for weeks 37–38.
Solution
wt = pd.read_csv("data/web_traffic.csv")wt["date"] = pd.to_datetime(wt["date"])wt["year"] = wt["date"].dt.yearwt["iso_week"] = wt["date"].dt.isocalendar().week.astype(int)
sub = wt[wt["year"].isin([2023, 2024]) & wt["iso_week"].isin([36, 37, 38])].copy()sub["treated"] = (sub["year"] == 2024).astype(int)
pre = sub[sub["iso_week"].isin([36, 37])].copy()pre["w37"] = (pre["iso_week"] == 37).astype(int)pt = smf.ols("signups ~ treated * w37", data=pre).fit(cov_type="HC3")
did_df = sub[sub["iso_week"].isin([37, 38])].copy()did_df["post"] = (did_df["iso_week"] == 38).astype(int)did = smf.ols("signups ~ treated * post", data=did_df).fit(cov_type="HC3")
print( f"Pre-trend (w36->w37): diff={pt.params['treated:w37']:+.2f}, " f"p={pt.pvalues['treated:w37']:.4f}")print( f"Campaign DiD (w38): lift={did.params['treated:post']:+.2f}, " f"SE={did.bse['treated:post']:.2f}, p={did.pvalues['treated:post']:.4f}")
assert pt.pvalues["treated:w37"] > 0.05assert did.params["treated:post"] > 50 and did.pvalues["treated:post"] < 0.01Pre-trend (w36->w37): diff=+4.29, p=0.6541Campaign DiD (w38): lift=+88.86, SE=27.00, p=0.0010How it works:
- Weeks 36 → 37 show no significant divergence between 2024 and 2023 (), validating the seasonal control group.
- In week 38, the September 2024 campaign adds nearly 89 incremental daily signups ().
M49-C09 · Fix the bug: fit a logistic GLM and interpret odds ratios
Section titled “M49-C09 · Fix the bug: fit a logistic GLM and interpret odds ratios”Fix the bug: a teammate fits OLS (smf.ols) on binary churned in data/customers.csv and gets out-of-range probability predictions below 0. Replace OLS with a Binomial logit GLM (smf.glm(..., family=sm.families.Binomial())), verify all predicted probabilities sit strictly inside (0, 1), and print the odds ratios (np.exp(params)) for one-year, two-year, support_tickets and has_autopay.
OLS pred range: [-0.259, 0.804]GLM pred range: [0.002, 0.925]OR C(contract)[T.one-year] = 0.351OR C(contract)[T.two-year] = 0.157OR support_tickets = 1.570OR has_autopay = 0.644customers = pd.read_csv("data/customers.csv")formula = ( "churned ~ C(contract) + tenure_months + support_tickets" " + monthly_charges + has_autopay")# BUGGY: ols = smf.ols(formula, data=customers).fit()# TODO: fit Binomial GLM, check min/max predicted probabilities, print odds ratiosHint 1
Call smf.glm(formula, data=customers, family=sm.families.Binomial()).fit().
Hint 2
glm.fittedvalues holds the predicted probabilities on the response scale; np.exp(glm.params) gives odds ratios.
Solution
customers = pd.read_csv("data/customers.csv")formula = ( "churned ~ C(contract) + tenure_months + support_tickets" " + monthly_charges + has_autopay")ols_preds = smf.ols(formula, data=customers).fit().fittedvaluesglm = smf.glm(formula, data=customers, family=sm.families.Binomial()).fit()glm_preds = glm.fittedvalues
print(f"OLS pred range: [{ols_preds.min():.3f}, {ols_preds.max():.3f}]")print(f"GLM pred range: [{glm_preds.min():.3f}, {glm_preds.max():.3f}]")for term in [ "C(contract)[T.one-year]", "C(contract)[T.two-year]", "support_tickets", "has_autopay",]: print(f"OR {term:<24} = {np.exp(glm.params[term]):.3f}")
assert ols_preds.min() < 0.0assert 0.0 < glm_preds.min() and glm_preds.max() < 1.0OLS pred range: [-0.259, 0.804]GLM pred range: [0.002, 0.925]OR C(contract)[T.one-year] = 0.351OR C(contract)[T.two-year] = 0.157OR support_tickets = 1.570OR has_autopay = 0.644How it works:
- Linear probability (OLS) predicts negative probabilities for low-risk customers.
- The logit link constrains every Binomial GLM prediction to
(0, 1)and yields clean multiplicative odds ratios: each extra support ticket raises churn odds, while annual contracts sharply lower them.
M49-C10 · Diagnose overdispersion in daily order counts
Section titled “M49-C10 · Diagnose overdispersion in daily order counts”Choose a method and justify it: aggregate data/sales.csv to daily units sold (quantity.sum()), fit both a Poisson GLM and a Negative Binomial model with year_t + C(dow) + C(month), compute pearson_chi2 / df_resid and both AIC/BIC values, and programmatically choose "NegativeBinomial" if pearson_chi2 / df_resid > 1.2 and nb.aic < pois.aic, else "Poisson".
Poisson AIC=7543.4 BIC=7630.7 Pearson/df=5.49NegBin AIC=5834.5 BIC=5926.4 alpha=0.0907Chosen model: NegativeBinomialsales = pd.read_csv("data/sales.csv")sales["order_date"] = pd.to_datetime(sales["order_date"])# TODO: aggregate daily units, fit Poisson GLM and Negative Binomial, compare & pickHint 1
daily = sales.groupby("order_date")["quantity"].sum().reset_index(name="units").
Hint 2
Remember smf.glm exposes .bic_llf, while smf.negativebinomial exposes .bic. Fit Negative Binomial with method="bfgs", maxiter=300, disp=False.
Solution
sales = pd.read_csv("data/sales.csv")sales["order_date"] = pd.to_datetime(sales["order_date"])daily = sales.groupby("order_date")["quantity"].sum().reset_index(name="units")daily["dow"] = daily["order_date"].dt.day_name()daily["month"] = daily["order_date"].dt.monthdaily["year_t"] = (daily["order_date"] - daily["order_date"].min()).dt.days / 365.0
formula = "units ~ year_t + C(dow) + C(month)"pois = smf.glm(formula, data=daily, family=sm.families.Poisson()).fit()nb = smf.negativebinomial(formula, data=daily).fit( method="bfgs", maxiter=300, disp=False)disp = float(pois.pearson_chi2 / pois.df_resid)choice = "NegativeBinomial" if (disp > 1.2 and nb.aic < pois.aic) else "Poisson"
print(f"Poisson AIC={pois.aic:.1f} BIC={pois.bic_llf:.1f} Pearson/df={disp:.2f}")print(f"NegBin AIC={nb.aic:.1f} BIC={nb.bic:.1f} alpha={nb.params['alpha']:.4f}")print("Chosen model:", choice)
assert disp > 3.0assert nb.aic + 500 < pois.aicassert choice == "NegativeBinomial"Poisson AIC=7543.4 BIC=7630.7 Pearson/df=5.49NegBin AIC=5834.5 BIC=5926.4 alpha=0.0907Chosen model: NegativeBinomialHow it works:
- Daily units sold include bulk orders and promo spikes, creating heavy overdispersion (
Pearson/df = 5.49). - Negative Binomial absorbs that extra variance via
alpha, slashing AIC by over 1,000 points.
M49-C11 · Compute Kaplan–Meier curves and Greenwood CIs by plan
Section titled “M49-C11 · Compute Kaplan–Meier curves and Greenwood CIs by plan”Write the code: compute Kaplan–Meier survival curves with 95% Greenwood confidence intervals for each plan (basic, standard, premium) in data/customers.csv, and print S(12) and S(24) with their 95% CIs for each plan.
basic S(12)=0.862 [0.847,0.878] S(24)=0.810 [0.791,0.830]premium S(12)=0.806 [0.781,0.832] S(24)=0.718 [0.686,0.749]standard S(12)=0.878 [0.863,0.893] S(24)=0.832 [0.813,0.851]customers = pd.read_csv("data/customers.csv")# TODO: write kaplan_meier(time, event) and print S(12) and S(24) with 95% CI per planHint 1
Greenwood’s variance at time is surv**2 * sum(d_j / (n_risk * (n_risk - d_j))) over all event times .
Hint 2
To look up S(m) and its CI at month m, take the last row with time <= m.
Solution
customers = pd.read_csv("data/customers.csv")
def km_table(time: np.ndarray, event: np.ndarray) -> pd.DataFrame: order = np.argsort(time) t_s, e_s = time[order], event[order] rows = [(0.0, 1.0, 1.0, 1.0)] surv, gw = 1.0, 0.0 for tj in np.unique(t_s[e_s == 1]): n_risk = int(np.sum(t_s >= tj)) d_j = int(np.sum((t_s == tj) & (e_s == 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 = max(0.0, surv - 1.96 * se), min(1.0, surv + 1.96 * se) rows.append((float(tj), surv, lo, hi)) return pd.DataFrame(rows, columns=["time", "s", "lo", "hi"])
s24_map = {}for plan, grp in customers.groupby("plan"): km = km_table(grp["tenure_months"].to_numpy(), grp["churned"].to_numpy()) r12 = km.loc[km["time"] <= 12].iloc[-1] r24 = km.loc[km["time"] <= 24].iloc[-1] s24_map[str(plan)] = float(r24["s"]) print( f"{plan:<9} S(12)={r12['s']:.3f} [{r12['lo']:.3f},{r12['hi']:.3f}] " f"S(24)={r24['s']:.3f} [{r24['lo']:.3f},{r24['hi']:.3f}]" )
assert s24_map["premium"] < s24_map["basic"]assert s24_map["premium"] < s24_map["standard"]basic S(12)=0.862 [0.847,0.878] S(24)=0.810 [0.791,0.830]premium S(12)=0.806 [0.781,0.832] S(24)=0.718 [0.686,0.749]standard S(12)=0.878 [0.863,0.893] S(24)=0.832 [0.813,0.851]How it works:
premiumsubscribers churn significantly faster thanbasicandstandardsubscribers across the first 24 months, with non-overlapping 95% confidence intervals.- Keeping censored active customers in
n_riskproduces unbiased retention estimates at every horizon.
M49-C12 · Predict the output: post-treatment adjustment breaks CUPED
Section titled “M49-C12 · Predict the output: post-treatment adjustment breaks CUPED”Predict the output: suppose treatment raises both a post-treatment mediator m_post (+2.0) and the final outcome y (y = 0.8 * m_post + noise, so the true total ATE is +1.6). Predict what happens when you mistakenly run CUPED using m_post as the covariate: does the CUPED estimate stay near +1.6, drop near 0.0, or flip negative?
Acceptance criteria:
- Write down your qualitative prediction (approximate value of
raw_atevs.bad_cuped_ate) before opening the solution. - Confirm your prediction against the exact Output inside the solution.
rng = np.random.default_rng(42)n = 4_000t = rng.binomial(1, 0.5, size=n)m_post = 2.0 * t + rng.normal(size=n) # post-treatment mediator!y = 0.8 * m_post + rng.normal(size=n) # true total ATE = 1.60# TODO: predict raw difference vs CUPED difference using m_postHint 1
theta = cov(y, m_post) / var(m_post) will be close to 0.8.
Hint 2
Subtracting 0.8 * (m_post - mean) removes 0.8 * 2.0 = 1.6 from the treated group — wiping out the entire treatment effect!
Solution
rng = np.random.default_rng(42)n = 4_000t = rng.binomial(1, 0.5, size=n)m_post = 2.0 * t + rng.normal(size=n)y = 0.8 * m_post + rng.normal(size=n)
theta = float(np.cov(y, m_post, ddof=1)[0, 1] / np.var(m_post, ddof=1))y_bad = y - theta * (m_post - m_post.mean())
raw_ate = float(y[t == 1].mean() - y[t == 0].mean())bad_ate = float(y_bad[t == 1].mean() - y_bad[t == 0].mean())print( f"True ATE = +1.600 | Raw ATE = {raw_ate:+.3f} | " f"Post-treatment CUPED = {bad_ate:+.3f}")
assert abs(raw_ate - 1.6) < 0.10assert abs(bad_ate) < 0.10True ATE = +1.600 | Raw ATE = +1.548 | Post-treatment CUPED = -0.025How it works:
- Because
m_postlies on the causal patht -> m_post -> y, subtractingtheta * m_postsubtracts out the treatment effect itself. - Always restrict CUPED covariates to measurements recorded strictly before randomization.
Challenge
Section titled “Challenge”M49-X01 · Implement a doubly robust (AIPW) estimator
Section titled “M49-X01 · Implement a doubly robust (AIPW) estimator”Write the code: implement the Augmented Inverse Probability Weighting (AIPW) estimator:
Verify its doubly robust property on a simulation (n = 4,000, true ATE = +2.0, nonlinear confounding in x^2): show that AIPW recovers +2.0 even when (a) the outcome model is linear (misspecified) while the propensity model is correct, OR (b) the propensity model is constant (misspecified) while the outcome model is correct!
Naive (biased): +3.030AIPW (good PS, bad outcome): +2.009AIPW (bad PS, good outcome): +2.020AIPW (both correct): +2.010rng = np.random.default_rng(42)n = 4_000x = rng.uniform(-1.5, 1.5, size=n)p_true = 1.0 / (1.0 + np.exp(-(0.8 * x + 0.7 * x**2)))t = rng.binomial(1, p_true)y = 2.0 * t + 1.5 * x + 1.2 * x**2 + rng.normal(size=n)
# TODO: implement aipw(y, t, e_hat, mu1_hat, mu0_hat) and test both misspecificationsHint 1
Fit separate regressions on t == 1 and t == 0 to predict mu1_hat and mu0_hat for all n rows.
Hint 2
For case (a), fit LogisticRegression on [x, x**2] (correct) and OLS on [x] (wrong). For case (b), set e_hat = np.full(n, t.mean()) (wrong) and fit OLS on [x, x**2] (correct).
Solution
rng = np.random.default_rng(42)n = 4_000x = rng.uniform(-1.5, 1.5, size=n)p_true = 1.0 / (1.0 + np.exp(-(0.8 * x + 0.7 * x**2)))t = rng.binomial(1, p_true)y = 2.0 * t + 1.5 * x + 1.2 * x**2 + rng.normal(size=n)
X_lin = x[:, None]X_quad = np.column_stack([x, x**2])
def fit_outcomes(X_feat: np.ndarray) -> tuple[np.ndarray, np.ndarray]: X_aug = sm.add_constant(X_feat) m1 = sm.OLS(y[t == 1], X_aug[t == 1]).fit() m0 = sm.OLS(y[t == 0], X_aug[t == 0]).fit() return m1.predict(X_aug), m0.predict(X_aug)
def aipw( yv: np.ndarray, tv: np.ndarray, e: np.ndarray, m1: np.ndarray, m0: np.ndarray) -> float: psi = (m1 - m0) + tv * (yv - m1) / e - (1 - tv) * (yv - m0) / (1 - e) return float(np.mean(psi))
e_good = LogisticRegression(max_iter=1000).fit(X_quad, t).predict_proba(X_quad)[:, 1]e_bad = np.full(n, t.mean())m1_good, m0_good = fit_outcomes(X_quad)m1_bad, m0_bad = fit_outcomes(X_lin)
naive = float(y[t == 1].mean() - y[t == 0].mean())aipw_a = aipw(y, t, e_good, m1_bad, m0_bad)aipw_b = aipw(y, t, e_bad, m1_good, m0_good)aipw_both = aipw(y, t, e_good, m1_good, m0_good)
print(f"Naive (biased): {naive:+.3f}")print(f"AIPW (good PS, bad outcome): {aipw_a:+.3f}")print(f"AIPW (bad PS, good outcome): {aipw_b:+.3f}")print(f"AIPW (both correct): {aipw_both:+.3f}")
assert abs(naive - 2.0) > 0.8assert abs(aipw_a - 2.0) < 0.10assert abs(aipw_b - 2.0) < 0.10assert abs(aipw_both - 2.0) < 0.10Naive (biased): +3.030AIPW (good PS, bad outcome): +2.009AIPW (bad PS, good outcome): +2.020AIPW (both correct): +2.010How it works:
- Naive difference-in-means is heavily biased (
+3.03vs. true+2.00) due to quadratic confounding. - AIPW stays accurate as long as at least one of the two nuisance models (propensity or outcome) is well-specified, and achieves lowest variance when both are right.
M49-X02 · Build a nearest-neighbor propensity score matcher with caliper
Section titled “M49-X02 · Build a nearest-neighbor propensity score matcher with caliper”Write the code: implement 1-to-1 nearest-neighbor propensity score matching (with replacement and a caliper of 0.02) for has_autopay on data/customers.csv. Match each treated customer (has_autopay == 1) to the closest control customer (has_autopay == 0) by propensity score, print the number of matched treated units, the matched ATT estimate, and verify that |SMD| of payment_method_electronic_check drops from above 1.0 to below 0.05 in the matched sample.
Matched treated: 2645/2645 | Matched ATT = -0.0113electronic_check |SMD|: 1.1357 -> 0.0000customers = pd.read_csv("data/customers.csv")# TODO: estimate propensity scores, match treated to nearest control within 0.02 caliper,# compute matched ATT and electronic_check |SMD|Hint 1
Sort control propensity scores e0_sorted and use np.searchsorted (or scipy.spatial.KDTree(e0[:, None])) to find the nearest control index for every treated unit in .
Hint 2
Keep pairs with dist <= 0.02; the matched ATT is np.mean(y1[ok] - y0[match_idx[ok]]).
Solution
from scipy.spatial import KDTree
customers = pd.read_csv("data/customers.csv")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), ])X = customers[cat_cols + num_cols]t = customers["has_autopay"].to_numpy()y = customers["churned"].to_numpy()ps = make_pipeline(pre, LogisticRegression(max_iter=1000)).fit(X, t).predict_proba(X)[ :, 1]
e1, e0 = ps[t == 1], ps[t == 0]y1, y0 = y[t == 1], y[t == 0]ec = (customers["payment_method"] == "electronic_check").to_numpy(dtype=float)ec1, ec0 = ec[t == 1], ec[t == 0]
dists, nn_idx = KDTree(e0[:, None]).query(e1[:, None], k=1)ok = dists <= 0.02att_matched = float(np.mean(y1[ok] - y0[nn_idx[ok]]))
def smd_1d(a: np.ndarray, b: np.ndarray) -> float: return abs(float(a.mean() - b.mean())) / float( np.sqrt(0.5 * (a.var(ddof=1) + b.var(ddof=1))) )
smd_before = smd_1d(ec1, ec0)smd_after = smd_1d(ec1[ok], ec0[nn_idx[ok]])print( f"Matched treated: {int(ok.sum())}/{len(e1)} | " f"Matched ATT = {att_matched:+.4f}")print(f"electronic_check |SMD|: {smd_before:.4f} -> {smd_after:.4f}")
assert ok.sum() > 2_500assert smd_before > 1.0 and smd_after < 0.05Matched treated: 2645/2645 | Matched ATT = -0.0113electronic_check |SMD|: 1.1357 -> 0.0000How it works:
KDTreematches all 2,645 treated units to their closest control neighbors in milliseconds.- Enforcing a
0.02caliper guarantees tight propensity overlap and collapses theelectronic_checkimbalance from1.14to near zero.
M49-X03 · Run a two-sample log-rank test from scratch
Section titled “M49-X03 · Run a two-sample log-rank test from scratch”Write the code: implement the Mantel–Haenszel log-rank test in pure NumPy to test whether survival differs between month-to-month (Group 1) and one-year (Group 2) customers in data/customers.csv. At each distinct event time across the pooled groups, compute expected events and hypergeometric variance , then form with 1 degree of freedom.
Observed=823 Expected=546.6 chi2=359.04 p=4.57e-80customers = pd.read_csv("data/customers.csv")g1 = customers[customers["contract"] == "month-to-month"]g2 = customers[customers["contract"] == "one-year"]# TODO: compute observed O1, expected E1, variance V, chi2 statistic, and p-valueHint 1
Pool all unique event times from both groups: times = np.unique(np.concatenate([t1[e1 == 1], t2[e2 == 1]])).
Hint 2
Guard n_j > 1 before dividing by n_j - 1, and get the p-value via stats.chi2.sf(chi2_stat, df=1).
Solution
customers = pd.read_csv("data/customers.csv")g1 = customers[customers["contract"] == "month-to-month"]g2 = customers[customers["contract"] == "one-year"]
t1, e1 = g1["tenure_months"].to_numpy(), g1["churned"].to_numpy()t2, e2 = g2["tenure_months"].to_numpy(), g2["churned"].to_numpy()times = np.unique(np.concatenate([t1[e1 == 1], t2[e2 == 1]]))
o1_sum = e1_sum = var_sum = 0.0for tj in times: n1 = int(np.sum(t1 >= tj)) n2 = int(np.sum(t2 >= tj)) d1 = int(np.sum((t1 == tj) & (e1 == 1))) d2 = int(np.sum((t2 == tj) & (e2 == 1))) n = n1 + n2 d = d1 + d2 o1_sum += d1 e1_sum += n1 * d / n if n > 1: var_sum += (n1 * n2 * d * (n - d)) / (n**2 * (n - 1))
chi2_stat = (o1_sum - e1_sum) ** 2 / var_sumpval = float(stats.chi2.sf(chi2_stat, df=1))print( f"Observed={o1_sum:.0f} Expected={e1_sum:.1f} " f"chi2={chi2_stat:.2f} p={pval:.2e}")
assert o1_sum > e1_sumassert chi2_stat > 200 and pval < 1e-40Observed=823 Expected=546.6 chi2=359.04 p=4.57e-80How it works:
- Under the null hypothesis of identical survival, month-to-month customers would have experienced far fewer churns (
Expected) than the 823 actually observed. - Summing
(d1 - E1)over all risk sets accounts for right censoring at every tenure month and yields an overwhelming log-rank .
M49-X04 · Implement O’Brien–Fleming sequential stopping boundaries
Section titled “M49-X04 · Implement O’Brien–Fleming sequential stopping boundaries”Write the code: unlike Bonferroni (which uses the same strict threshold at every look), O’Brien–Fleming sequential boundaries spend almost no on early looks and save power for the final look: at information fraction , the boundary is (for looks at overall , the standard constant is ). Simulate 2,000 A/A experiments (n_per_arm = 2,000, p0 = 0.10, K = 5 evenly spaced looks) and compare the overall false-positive rate of naive peeking (z > 1.96) against O’Brien–Fleming (z > 2.040 / sqrt(f_j)).
OBF z-boundaries: [4.56, 3.23, 2.63, 2.28, 2.04]Naive FPR = 0.135 | O'Brien-Fleming FPR = 0.045rng = np.random.default_rng(42)n_sims, n_per_arm, p0, K = 2_000, 2_000, 0.10, 5c_obf = 2.040# TODO: simulate 5 looks, compare naive z>1.96 vs O'Brien-Fleming boundariesHint 1
At look j in 1..5, information fraction is f_j = j / K, checkpoint is n_now = int(n_per_arm * f_j), and the OBF boundary is c_obf / np.sqrt(f_j).
Hint 2
Notice that at the final look (f_5 = 1.0), the OBF critical value is only 2.040 — almost as easy to cross as the single-look 1.96, preserving power while keeping overall Type I error near 0.05.
Solution
rng = np.random.default_rng(42)n_sims, n_per_arm, p0, K = 2_000, 2_000, 0.10, 5c_obf = 2.040
ctrl = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)trt = rng.binomial(1, p0, size=(n_sims, n_per_arm)).cumsum(axis=1)
rej_naive = np.zeros(n_sims, dtype=bool)rej_obf = np.zeros(n_sims, dtype=bool)obf_bounds = []for j in range(1, K + 1): frac = j / K n_now = int(n_per_arm * frac) c_now, t_now = ctrl[:, n_now - 1], trt[:, n_now - 1] p_pool = (c_now + t_now) / (2 * n_now) se = np.sqrt(np.maximum(2 * p_pool * (1 - p_pool) / n_now, 1e-12)) z = np.abs((t_now - c_now) / n_now) / se z_obf = c_obf / np.sqrt(frac) obf_bounds.append(round(float(z_obf), 2)) rej_naive |= z > stats.norm.ppf(0.975) rej_obf |= z > z_obf
print("OBF z-boundaries:", obf_bounds)print( f"Naive FPR = {rej_naive.mean():.3f} | " f"O'Brien-Fleming FPR = {rej_obf.mean():.3f}")
assert rej_naive.mean() > 0.12assert 0.035 <= rej_obf.mean() <= 0.065OBF z-boundaries: [4.56, 3.23, 2.63, 2.28, 2.04]Naive FPR = 0.135 | O'Brien-Fleming FPR = 0.045How it works:
- Early looks require a dramatic signal (
z > 4.56at 20% traffic), preventing false stops on noisy early data. - The final look uses
z > 2.04(barely above1.96), keeping overall false-positive rate right around0.05with minimal loss of statistical power.
M49-X05 · Fit a Gamma GLM with log link for right-skewed buyer revenue
Section titled “M49-X05 · Fit a Gamma GLM with log link for right-skewed buyer revenue”Write the code: filter data/ab_test.csv to buyers (converted == 1, where revenue > 0 is strictly positive and right-skewed). Fit (a) OLS (smf.ols) and (b) a Gamma GLM with log link (smf.glm(..., family=sm.families.Gamma(sm.families.links.Log()))) for revenue ~ C(group) + C(device) + time_on_page_s. Compare AIC, verify the Gamma GLM preserves mean calibration (mean(fitted) ≈ mean(revenue)), and print the treatment multiplicative ratio np.exp(beta_treatment).
OLS AIC=10481.1 | Gamma(Log) GLM AIC=9941.2Observed mean=42.36 | Gamma fitted mean=42.36Treatment revenue ratio = 0.961x (p=0.354)ab = pd.read_csv("data/ab_test.csv")buyers = ab[ab["converted"] == 1].copy()# TODO: fit OLS vs Gamma(Log) GLM on buyers, compare AIC, check mean calibrationHint 1
Pass family=sm.families.Gamma(sm.families.links.Log()) to smf.glm.
Hint 2
Check buyers["revenue"].mean() vs. gamma_glm.fittedvalues.mean(). A log-OLS regression on log(revenue) under-predicts mean revenue on the dollar scale when back-transformed, whereas a Gamma log-link GLM models directly!
Solution
ab = pd.read_csv("data/ab_test.csv")buyers = ab[ab["converted"] == 1].copy()formula = "revenue ~ C(group) + C(device) + time_on_page_s"
ols = smf.ols(formula, data=buyers).fit()gamma_glm = smf.glm( formula, data=buyers, family=sm.families.Gamma(sm.families.links.Log())).fit()
trt_ratio = float(np.exp(gamma_glm.params["C(group)[T.treatment]"]))trt_p = float(gamma_glm.pvalues["C(group)[T.treatment]"])obs_mean = float(buyers["revenue"].mean())fit_mean = float(gamma_glm.fittedvalues.mean())
print(f"OLS AIC={ols.aic:.1f} | Gamma(Log) GLM AIC={gamma_glm.aic:.1f}")print(f"Observed mean={obs_mean:.2f} | Gamma fitted mean={fit_mean:.2f}")print(f"Treatment revenue ratio = {trt_ratio:.3f}x (p={trt_p:.3f})")
assert gamma_glm.aic + 300 < ols.aicassert abs(obs_mean - fit_mean) < 0.5assert trt_p > 0.05OLS AIC=10481.1 | Gamma(Log) GLM AIC=9941.2Observed mean=42.36 | Gamma fitted mean=42.36Treatment revenue ratio = 0.961x (p=0.354)How it works:
- Buyer revenue is heavily right-skewed with variance proportional to , matching the Gamma variance function; its AIC beats Gaussian OLS by more than 400 points.
- Unlike OLS on
log(revenue), a Gamma log-link GLM estimates directly without back-transformation bias, and confirms no significant treatment difference in order value among buyers (p > 0.05).