49. Causal inference, GLMs and advanced experimentation
Prediction answers “what is likely to happen next?” Decision-making asks a harder question: “what happens if we intervene?” Customers who use autopay churn at 16.9%, while customers without autopay churn at 21.9%. Does turning on autopay cause a 5-percentage-point drop in churn, or do stable credit-card customers simply enroll in autopay more often? A predictive model cannot tell those two stories apart. Causal inference and modern experimentation give you the framework and estimators to answer intervention questions reliably.
This module completes the statistical toolkit you started in module 29. You move from classic fixed-horizon A/B tests and OLS to the tools data scientists reach for every week in production: causal diagrams, Sample Ratio Mismatch checks, CUPED variance reduction, multi-armed bandits, propensity score weighting, Difference-in-Differences, Generalized Linear Models for counts and binary outcomes, and Kaplan–Meier survival analysis for customer retention.
What you will learn
Section titled “What you will learn”- Define potential outcomes, ATE and ATT, draw causal DAGs to separate confounders, mediators and colliders, and diagnose Simpson’s paradox.
- Catch broken experiments with Sample Ratio Mismatch (SRM) checks, explain why optional stopping (peeking) inflates false positives, reduce variance with CUPED, and compare fixed A/B tests with multi-armed bandits (epsilon-greedy, UCB1 and Thompson sampling).
- Estimate causal effects from observational data using propensity scores, Inverse Probability Weighting (IPW) with covariate balance checks, and Difference-in-Differences (DiD) with parallel-trends tests.
- Fit Generalized Linear Models (GLMs) (logistic, Poisson and Negative Binomial) in
statsmodels, diagnose overdispersion and compare models with AIC and BIC. - Build Kaplan–Meier retention curves and Greenwood confidence intervals in NumPy and pandas to handle right-censored customer tenure data cleanly.
Prerequisites
Section titled “Prerequisites”- 29. Statistics and probability: hypothesis tests, confidence intervals, A/B testing and
statsmodelsOLS. - 48. Probability, Bayesian statistics and information theory: Beta–Binomial updating and Negative Binomial intuition (recommended).
- 23. NumPy, 24. pandas fundamentals and 28. Visualization: arrays,
groupbyand Matplotlib charts. - The course datasets in
data/(Get the data and Data dictionary).
Concepts
Section titled “Concepts”All runnable Python blocks on this page execute in one session from top to bottom. Start by importing the libraries and fixing display options:
import matplotlib.pyplot as pltimport 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)print("statsmodels", sm.__version__, "| pandas", pd.__version__)statsmodels 0.15.0 | pandas 3.1.1For every customer and binary intervention (for example, means enrolling in autopay, means not enrolling), imagine two potential outcomes:
- : the outcome customer would have if treated.
- : the outcome customer would have if untreated.
Customer ‘s individual treatment effect is . The fundamental problem of causal inference is that for any single unit at a given time, you observe at most one of the two potential outcomes:
The unobserved outcome is the counterfactual. Because you never see both outcomes for the same customer, you target population averages instead:
- Average Treatment Effect (ATE): the mean effect across the entire population:
- Average Treatment Effect on the Treated (ATT): the mean effect specifically among the units that actually received the treatment:
When you take a naive difference in observed group means, , algebra splits it into two pieces:
Selection bias is the baseline difference between treated and control units that would have existed even without treatment. A randomized experiment sets independently of , which makes selection bias zero on average. In observational data, selection bias is almost never zero.
Three core assumptions let you identify causal effects from data:
| Assumption | Meaning | Violation example |
|---|---|---|
| Ignorability (unconfoundedness) | Unmeasured customer loyalty drives both autopay and retention | |
| Positivity (overlap) | for all | One payment method forbids autopay completely |
| SUTVA (no interference) | One unit’s treatment does not alter another’s outcome | Discounting one store cannibalizes a nearby store |
Causal DAGs: confounders, mediators and colliders
Section titled “Causal DAGs: confounders, mediators and colliders”A Directed Acyclic Graph (DAG) is a causal diagram made of nodes (variables) and one-way arrows (direct causal effects) with no feedback cycles. DAGs turn informal domain stories into exact rules for which variables you must adjust for and which variables you must leave alone.
Every three-variable path in a DAG falls into one of three basic structures:
flowchart LR
subgraph Confounder["1. Confounder (Fork)"]
Z1["Z (Payment method)"] --> T1["T (Autopay)"]
Z1 --> Y1["Y (Churn)"]
T1 --> Y1
end
subgraph Mediator["2. Mediator (Chain)"]
T2["T (New checkout)"] --> M2["M (Page speed)"]
M2 --> Y2["Y (Conversion)"]
end
subgraph Collider["3. Collider (Inverted fork)"]
T3["T (Marketing spend)"] --> C3["C (High-intent lead)"]
Y3["Y (Product fit)"] --> C3
end
- A confounder () is a common cause of treatment and outcome. It creates a non-causal backdoor path between and . Adjusting for blocks the backdoor path and removes the bias.
- A mediator () sits on the causal pathway from treatment to outcome. If you want the total causal effect of on , do not adjust for — holding the mediator constant strips away the very mechanism by which works.
- A collider () is a common effect of two variables. The path is naturally blocked. Adjusting for a collider opens a spurious path between its causes (known as collider bias or Berkson’s paradox).
See the difference in a quick simulation where and are independent causes of a collider , while confounds and :
rng = np.random.default_rng(42)n = 4_000z = rng.normal(size=n) # confoundert = 0.8 * z + rng.normal(size=n) # treatment caused by Zy = 1.5 * t + 1.2 * z + rng.normal(size=n) # true effect of T on Y is 1.5c = 0.9 * t + 0.9 * y + rng.normal(scale=0.5, size=n) # collider caused by T and Y
sim = pd.DataFrame({"t": t, "y": y, "z": z, "c": c})for label, formula in [ ("Naive (y ~ t)", "y ~ t"), ("Adjust confounder (y ~ t + z)", "y ~ t + z"), ("Bad: adjust collider (y ~ t + z + c)", "y ~ t + z + c"),]: coef = smf.ols(formula, data=sim).fit().params["t"] print(f"{label:<38} estimated effect = {coef:+.3f}")Naive (y ~ t) estimated effect = +2.070Adjust confounder (y ~ t + z) estimated effect = +1.496Bad: adjust collider (y ~ t + z + c) estimated effect = -0.418Throwing every available column into a regression (“kitchen-sink adjustment”) is dangerous for causal questions. Leaving out the confounder inflates the estimate from to about , adjusting for nails the true , and adding the collider wrecks the estimate all the way down to about .
Simpson’s paradox in business data
Section titled “Simpson’s paradox in business data”Simpson’s paradox happens when a trend or comparison that holds inside every subgroup reverses direction when the subgroups are combined. It is not a mathematical trick — it is confounding in action.
Suppose a product team rolls out a redesigned checkout page gradually: 80% of mobile visitors see the new page, while only 20% of desktop visitors see it. Because desktop converts higher than mobile regardless of page design, the pooled conversion rate makes the better checkout look worse:
rows = [ ("desktop", "control", 800, 128), ("desktop", "treatment", 200, 36), ("mobile", "control", 200, 16), ("mobile", "treatment", 800, 80),]simp = pd.DataFrame(rows, columns=["device", "group", "visitors", "buyers"])simp["rate"] = simp["buyers"] / simp["visitors"]
by_device = simp.pivot(index="device", columns="group", values="rate")by_device["lift"] = by_device["treatment"] - by_device["control"]pooled = simp.groupby("group")[["buyers", "visitors"]].sum()pooled["rate"] = pooled["buyers"] / pooled["visitors"]
print(by_device.round(3))print("\nPooled conversion:")print(pooled.round(3))group control treatment liftdevicedesktop 0.16 0.18 0.02mobile 0.08 0.10 0.02
Pooled conversion: buyers visitors rategroupcontrol 144 1000 0.144treatment 116 1000 0.116Inside desktop, treatment beats control (+2.0 percentage points). Inside mobile, treatment also beats control (+2.0 percentage points). Yet pooled together, treatment trails control (11.6% vs. 14.4%) because device confounded group assignment. To decide whether to trust the pooled number or the segmented number, you always consult the causal DAG: here device causes both group assignment and conversion, so device is a confounder and you must stratify by it.
Experimentation pitfalls: peeking, SRM and novelty effects
Section titled “Experimentation pitfalls: peeking, SRM and novelty effects”Even a randomized A/B test breaks if you violate its statistical protocol. Three failure modes cause the majority of bad experiment decisions in practice:
- Sample Ratio Mismatch (SRM): You configure a 50/50 split, yet at the end of the week control has 5,180 users and treatment has 4,820. A chi-square goodness-of-fit test (
stats.chisquare) checks whether the observed counts match the expected ratio. Even a small SRM (say ) means randomization or telemetry is broken — for instance, a buggy redirect dropping mobile users in treatment. Never analyze conversion lift on an experiment with an unresolved SRM. - Optional stopping (peeking): In a fixed-horizon test at , the 5% false-positive guarantee holds only if you test once at the planned sample size. Checking the p-value every day and shipping the moment gives noise many chances to cross the threshold, inflating the false-positive rate to 20–30% or higher. Solutions include waiting for the pre-registered sample size, using sequential alpha-spending boundaries (such as O’Brien–Fleming), or using always-valid sequential tests.
- Novelty and primacy effects: Returning users click a shiny new button out of curiosity (novelty effect) or temporarily stumble over a changed layout (primacy effect). Both fade over 1–2 weeks. Segmenting metrics by new vs. returning users and tracking daily lift over time reveals whether an effect is durable.
Variance reduction with CUPED
Section titled “Variance reduction with CUPED”Waiting for statistical power costs weeks of engineering time. CUPED (Controlled-experiment Using Pre-Experiment Data) cuts metric variance — and therefore cuts required sample size — by using a pre-experiment covariate that correlates with the post-experiment outcome .
Because randomization ensures the pre-experiment mean is identical in treatment and control, subtracting from every user’s outcome leaves the treatment effect unbiased:
Computing on the pooled sample (ignoring treatment labels) minimizes variance without leaking treatment information. The variance shrinks by a factor of , where :
| Pre/post correlation | Variance remaining | Sample size saved |
|---|---|---|
| 0.30 | 91% | 9% |
| 0.50 | 75% | 25% |
| 0.70 | 51% | 49% |
| 0.80 | 36% | 64% |
Exploration vs. exploitation: multi-armed bandits
Section titled “Exploration vs. exploitation: multi-armed bandits”A fixed 50/50 A/B test sends half of all visitors to the losing variant until the experiment ends. When traffic is limited or campaigns are short (flash sales, headline tests, email send-time choices), you may care more about maximizing conversions during the test than about equal-precision estimates of every arm.
A multi-armed bandit shifts traffic dynamically toward arms that perform well while still exploring uncertain arms. Performance is measured by cumulative regret: the total expected reward lost compared to an oracle that knew the best arm from visitor 1:
Three classic bandit algorithms cover most practical needs:
| Strategy | Selection rule | Pros and cons |
|---|---|---|
| -greedy | Pick a random arm with probability , else the arm with the highest sample mean | Simple, easy to debug; fixed keeps wasting traffic forever |
| UCB1 | Pick the arm maximizing | Deterministic; automatically shrinks exploration as counts grow |
| Thompson sampling | Sample per arm and pick the largest draw | Natural Bayesian uncertainty; strong empirical regret; handles delayed batches well |
Thompson sampling connects directly to the Beta–Binomial updating from module 48: start each arm with , increment on a conversion and on a non-conversion. Keep in mind the trade-off: bandits reduce regret, but because arm assignment adapts over time, naive p-values and confidence intervals from bandit logs are biased. Use fixed-horizon A/B tests when you need clean long-term inference, guardrail metrics, or regulatory evidence; use bandits when short-lived opportunity cost dominates.
Observational causal methods I: propensity scores, matching and IPW
Section titled “Observational causal methods I: propensity scores, matching and IPW”Often you cannot randomize: you cannot force half your customers onto a two-year contract or randomly deny autopay. Instead, you observe who chose treatment () and who did not (), along with pre-treatment covariates .
The propensity score is the probability of receiving treatment given covariates:
Rosenbaum and Rubin’s central theorem shows that if ignorability holds given the full vector , it also holds given the single scalar . That turns a high-dimensional adjustment problem into a 1D score, used in three ways:
- Propensity score matching: pair each treated unit with the control unit(s) having the closest propensity score (usually within a maximum distance called a caliper). Matching estimates the ATT cleanly and discards units outside the region of common support.
- Inverse Probability Weighting (IPW): keep all units and reweight them to build a balanced “pseudo-population” where treatment is independent of . Treated units get weight and control units get weight . In practice, always use the normalized Hájek IPW estimator, which stabilizes variance by dividing by the sum of weights in each group:
- Doubly robust estimation (AIPW): combines an outcome regression model with IPW weights. It remains consistent if either the propensity model or the outcome model is correctly specified.
After weighting or matching, you always check covariate balance using the Standardized Mean Difference (SMD) for every confounder:
A common rule of thumb is for every covariate after weighting. If a covariate still has large imbalance, refine the propensity model (add interactions or nonlinear terms) or check whether positivity is violated ( near 0 or 1).
Observational causal methods II: Difference-in-Differences (DiD)
Section titled “Observational causal methods II: Difference-in-Differences (DiD)”What if treated and control groups differ in unobserved, time-invariant ways — for example, one region is permanently wealthier than another? Propensity scores only adjust for observed confounders. Difference-in-Differences (DiD) handles time-invariant unobserved confounding by comparing changes over time instead of raw levels.
Suppose a treated group () receives an intervention in the post-period (), while a control group () never receives it:
Equivalently, fit an OLS regression with an interaction term:
Here absorbs permanent baseline differences between groups, absorbs common time shocks (seasonality, market-wide growth), and the interaction coefficient is the exact DiD causal effect.
DiD relies on the parallel trends assumption: in the absence of treatment, the treated and control groups would have moved along parallel trajectories from the pre-period to the post-period. You can never prove the unobserved post-period counterfactual, so you test its credibility by checking pre-treatment periods (plotting both series and testing whether the pre-period group-by-time slope interaction is near zero).
Generalized Linear Models (GLMs) in statsmodels
Section titled “Generalized Linear Models (GLMs) in statsmodels”Ordinary Least Squares assumes the outcome is continuous, unbounded and has constant error variance. Real business targets often violate all three:
churnedis binary ( or ): OLS can predict probabilities below or above .support_ticketsand dailyordersare non-negative integers () whose variance grows with the mean.- Buyer
revenueis strictly positive and heavily right-skewed.
A Generalized Linear Model (GLM) generalizes linear regression with two ingredients:
- A random component (family) from the exponential family specifying the conditional distribution of and its mean–variance relationship.
- A link function mapping the expected value onto the unbounded linear predictor :
| Outcome type | GLM family | Canonical / standard link | Interpreting |
|---|---|---|---|
| Continuous, symmetric | Gaussian | Identity: | Additive change (identical to OLS) |
| Binary (0/1) | Binomial | Logit: | Odds ratio per 1-unit increase in |
| Counts (variance mean) | Poisson | Log: | Incidence rate ratio (IRR) per 1-unit increase |
| Overdispersed counts | Negative Binomial | Log: | Incidence rate ratio (IRR) with extra variance |
| Positive skewed amounts | Gamma | Log: | Multiplicative factor on mean amount |
For count data, always check overdispersion: in a Poisson model, , so the ratio (or ) should sit near . When it is much larger than , Poisson standard errors are too narrow and p-values are artificially small. Switching to a Negative Binomial model adds a dispersion parameter so , and you compare candidate models using AIC and BIC (lower is better).
Survival analysis and censoring: Kaplan–Meier and hazard rates
Section titled “Survival analysis and censoring: Kaplan–Meier and hazard rates”Suppose you want to estimate how long subscription customers stay before churning. In data/customers.csv, 4,037 of 5,000 customers are still active on the snapshot date 2024-12-31. Their true churn times have not happened yet — you only know that each active customer survived at least as long as their current tenure_months. This is right censoring.
If you drop active customers and average only the churners’ tenures, you throw away your longest-lived customers and badly underestimate retention. If you treat censored tenure as if those customers churned today, you also underestimate retention. Survival analysis uses every customer’s observed time without bias.
Define two core functions of time :
- Survival function : the probability a customer is still active past month .
- Hazard rate : the instantaneous risk of churning at time given survival up to .
The Kaplan–Meier estimator computes non-parametrically from observed event times . At each event time , let be the number of customers still at risk (tenure , neither churned nor censored before ) and be the number who churned at :
Censored customers contribute to the denominator at every time step up to their observed tenure, then leave the risk set cleanly without counting as an event. Uncertainty is quantified by Greenwood’s formula for the variance of :
Worked examples
Section titled “Worked examples”Example 1 — Detect Sample Ratio Mismatch and simulate the peeking trap
Section titled “Example 1 — Detect Sample Ratio Mismatch and simulate the peeking trap”Goal: Audit data/ab_test.csv for Sample Ratio Mismatch, then simulate sequential peeking under a true null to measure how quickly false positives balloon.
Step 1 — Check data/ab_test.csv for SRM
Section titled “Step 1 — Check data/ab_test.csv for SRM”Run a chi-square goodness-of-fit test against the planned 50/50 split on the real checkout experiment, and compare it with a broken experiment that drops 5% of treatment users.
ab = pd.read_csv("data/ab_test.csv")counts = ab["group"].value_counts().sort_index()n_total = int(counts.sum())srm_ok = stats.chisquare(counts.to_numpy(), f_exp=[n_total / 2, n_total / 2])
# Contrast with a broken 50/50 split that silently drops 5% of treatment logsbroken = np.array([5000, 4750])srm_bad = stats.chisquare(broken, f_exp=[broken.sum() / 2, broken.sum() / 2])
print( f"ab_test.csv counts: control={counts['control']}, " f"treatment={counts['treatment']}")print(f"SRM check (ab_test): chi2={srm_ok.statistic:.4f}, p={srm_ok.pvalue:.4f}")print(f"SRM check (broken): chi2={srm_bad.statistic:.2f}, p={srm_bad.pvalue:.2e}")ab_test.csv counts: control=5002, treatment=4998SRM check (ab_test): chi2=0.0016, p=0.9681SRM check (broken): chi2=6.41, p=1.13e-02data/ab_test.csv passes the SRM check cleanly (). By contrast, losing just 5% of treatment telemetry yields (and with larger traffic, ), flagging a logging or randomization bug immediately before anyone trusts the conversion numbers.
Step 2 — Simulate the peeking false-positive trap
Section titled “Step 2 — Simulate the peeking false-positive trap”Generate 1,000 A/A experiments where control and treatment have the exact same true conversion rate () and total sample size per arm. Measure the false-positive rate when you peek 1, 2, 5, 10, 20 or 40 evenly spaced times and stop early whenever two-sided .
rng = np.random.default_rng(42)n_sims, n_per_arm, p0 = 1_000, 2_000, 0.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)
look_counts = [1, 2, 5, 10, 20, 40]fprs = []for k in look_counts: checkpoints = np.linspace(n_per_arm // k, n_per_arm, k, dtype=int) rejected = np.zeros(n_sims, dtype=bool) 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 rejected |= z > stats.norm.ppf(0.975) fprs.append(float(rejected.mean())) print(f"peeks = {k:>2d} | false-positive rate = {rejected.mean():.3f}")peeks = 1 | false-positive rate = 0.039peeks = 2 | false-positive rate = 0.069peeks = 5 | false-positive rate = 0.136peeks = 10 | false-positive rate = 0.183peeks = 20 | false-positive rate = 0.236peeks = 40 | false-positive rate = 0.295With 1 look at the end, the false-positive rate sits near the nominal 5%. Peeking 20 times pushes the false-positive rate above 23%, and peeking 40 times nears 30% — almost six times the advertised .
Step 3 — Plot false-positive inflation against number of peeks
Section titled “Step 3 — Plot false-positive inflation against number of peeks”fig, ax = plt.subplots(figsize=(6.5, 3.8))ax.plot(look_counts, [100 * f for f in fprs], marker="o", linewidth=2, color="#d95f02")ax.axhline(5.0, linestyle="--", color="#555555", label="Nominal 5% alpha")ax.set_xlabel("Number of interim peeks")ax.set_ylabel("False-positive rate (%)")ax.set_title("Peeking inflates false positives under a true null (1,000 A/A sims)")ax.set_ylim(0, 35)ax.grid(alpha=0.3)ax.legend()fig.tight_layout()plt.show()
Common mistakes:
- Running an SRM check with
alpha = 0.05on dozens of experiments without investigating borderline cases; most experimentation platforms alert at or and block shipping until root-caused. - Calling a test “statistically significant” after watching a live dashboard cross mid-week.
Example 2 — Cut experiment variance in half with CUPED
Section titled “Example 2 — Cut experiment variance in half with CUPED”Goal: Use customers’ real 2023 order counts from data/sales.csv as a pre-experiment covariate to shrink the standard error of a simulated 2024 loyalty-program experiment.
Step 1 — Build the pre/post customer panel
Section titled “Step 1 — Build the pre/post customer panel”Select customers who signed up before July 2023 so every customer has a full pre-period (2023) and post-period (2024) history, then measure the pre/post correlation .
customers = pd.read_csv("data/customers.csv")sales = pd.read_csv("data/sales.csv")sales["year"] = pd.to_datetime(sales["order_date"]).dt.year
eligible = customers.loc[customers["signup_date"] < "2023-07-01", "customer_id"]orders_by_yr = ( sales.groupby(["customer_id", "year"])["order_id"] .nunique() .unstack(fill_value=0) .reindex(eligible, fill_value=0))x_pre = orders_by_yr[2023].to_numpy(dtype=float)y_base = orders_by_yr[2024].to_numpy(dtype=float)rho = float(np.corrcoef(x_pre, y_base)[0, 1])print(f"eligible customers: {len(eligible):,}")print( f"pre/post correlation rho = {rho:.3f} " f"(theoretical var reduction = {rho**2:.1%})")eligible customers: 2,458pre/post correlation rho = 0.738 (theoretical var reduction = 54.4%)A customer’s 2023 order count correlates strongly () with their 2024 order count. Theory predicts CUPED will eliminate roughly of the outcome variance.
Step 2 — Run a randomized experiment and compare raw vs. CUPED estimates
Section titled “Step 2 — Run a randomized experiment and compare raw vs. CUPED estimates”Randomly assign half the eligible customers to treatment and inject a modest true lift of +0.25 orders per customer in 2024. Compare Welch’s two-sample t-test on raw against CUPED-adjusted .
rng = np.random.default_rng(42)treat = rng.binomial(1, 0.5, size=len(eligible))y_obs = y_base + 0.25 * treat
# Pooled theta (computed without looking at treatment labels)theta = 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 summarize_diff(y: np.ndarray, t: np.ndarray, name: str) -> tuple[float, float]: y1, y0 = y[t == 1], y[t == 0] diff = float(y1.mean() - y0.mean()) se = float(np.sqrt(y1.var(ddof=1) / len(y1) + y0.var(ddof=1) / len(y0))) pval = float(stats.ttest_ind(y1, y0, equal_var=False).pvalue) print(f"{name:<6} diff={diff:+.3f} SE={se:.4f} p={pval:.4f}") return diff, se
_, se_raw = summarize_diff(y_obs, treat, "Raw")_, se_cuped = summarize_diff(y_cuped, treat, "CUPED")var_reduction = 1.0 - (se_cuped / se_raw) ** 2print(f"theta = {theta:.3f} | empirical variance reduction = {var_reduction:.1%}")Raw diff=+0.212 SE=0.1054 p=0.0442CUPED diff=+0.335 SE=0.0712 p=0.0000theta = 0.607 | empirical variance reduction = 54.3%Look at what happened: the raw t-test has a wide standard error (SE = 0.1054) and barely crosses p = 0.05 (p = 0.0442) because customer-to-customer spending heterogeneity adds heavy noise. CUPED cuts the variance by 54.3%, drops the standard error to 0.0712, drives , and delivers the equivalent of more than double the sample size at zero extra traffic cost.
Common mistakes:
- Fitting a separate inside treatment and control, which can introduce small-sample bias; always estimate one pooled across all users (or use cross-fitting).
- Using a variable measured after randomization as , which absorbs part of the treatment effect.
Example 3 — Compare Thompson sampling against a fixed A/B test
Section titled “Example 3 — Compare Thompson sampling against a fixed A/B test”Goal: Simulate 5,000 checkout visitors choosing among 3 variants with true conversion rates [0.06, 0.10, 0.14], averaging over 15 independent trials to compare a fixed uniform 3-way A/B test, -greedy, UCB1 and Thompson sampling on cumulative regret and total conversions.
Step 1 — Implement the four allocation strategies
Section titled “Step 1 — Implement the four allocation strategies”true_rates = np.array([0.06, 0.10, 0.14])best_rate = float(true_rates.max())n_visitors, n_arms, n_trials = 5_000, len(true_rates), 15
def run_bandit(strategy: str, seed: int) -> tuple[np.ndarray, np.ndarray, int]: rng = np.random.default_rng(seed) pulls = np.zeros(n_arms, dtype=int) wins = np.zeros(n_arms, dtype=int) regret = np.zeros(n_visitors, dtype=float) cum_regret = 0.0
for t in range(1, n_visitors + 1): if strategy == "fixed_ab": arm = (t - 1) % n_arms elif strategy == "eps_greedy": if t <= n_arms: arm = t - 1 elif rng.random() < 0.10: arm = int(rng.integers(n_arms)) else: arm = int(np.argmax(wins / pulls)) elif strategy == "ucb1": if t <= n_arms: arm = t - 1 else: ucb = (wins / pulls) + np.sqrt(2.0 * np.log(t) / pulls) arm = int(np.argmax(ucb)) elif strategy == "thompson": samples = rng.beta(1 + wins, 1 + pulls - wins) arm = int(np.argmax(samples)) else: raise ValueError(f"Unknown strategy: {strategy}")
reward = int(rng.random() < true_rates[arm]) pulls[arm] += 1 wins[arm] += reward cum_regret += best_rate - true_rates[arm] regret[t - 1] = cum_regret
return regret, pulls, int(wins.sum())
results = {}for name in ["fixed_ab", "eps_greedy", "ucb1", "thompson"]: runs = [run_bandit(name, seed=42 + s) for s in range(n_trials)] mean_reg = np.mean([r[0] for r in runs], axis=0) mean_pulls = np.round(np.mean([r[1] for r in runs], axis=0)).astype(int) mean_conv = float(np.mean([r[2] for r in runs])) results[name] = (mean_reg, mean_pulls, mean_conv) print( f"{name:<11} conv={mean_conv:>5.1f} regret={mean_reg[-1]:>5.1f} " f"pulls={mean_pulls.tolist()}" )fixed_ab conv=498.9 regret=200.0 pulls=[1667, 1667, 1666]eps_greedy conv=657.3 regret= 43.6 pulls=[274, 541, 4184]ucb1 conv=591.4 regret=108.7 pulls=[690, 1339, 2972]thompson conv=671.7 regret= 25.2 pulls=[124, 382, 4494]A fixed 3-way A/B test keeps sending two-thirds of all traffic to inferior variants, accumulating 200 lost conversions of expected regret. Thompson sampling concentrates nearly 90% of visitors onto the 14% winner, cutting regret by 87% relative to fixed A/B and gaining over 170 additional conversions.
Step 2 — Plot cumulative regret curves
Section titled “Step 2 — Plot cumulative regret curves”fig, ax = plt.subplots(figsize=(6.8, 3.8))styles = { "fixed_ab": ("Fixed 3-way A/B", "#7570b3", "--"), "eps_greedy": ("Epsilon-greedy (0.10)", "#d95f02", "-."), "ucb1": ("UCB1", "#e7298a", ":"), "thompson": ("Thompson sampling", "#1b9e77", "-"),}for name, (label, color, ls) in styles.items(): ax.plot(results[name][0], label=label, color=color, linestyle=ls, linewidth=2)ax.set_xlabel("Visitors")ax.set_ylabel("Mean cumulative regret (conversions)")ax.set_title("Cumulative regret across 5,000 visitors (rates 6%, 10%, 14%)")ax.grid(alpha=0.3)ax.legend()fig.tight_layout()plt.show()
Common mistakes:
- Reading a standard two-proportion p-value straight off Thompson sampling logs; adaptive sampling breaks fixed-sample p-value calibration.
- Forgetting warm-up pulls in UCB1 or -greedy, causing division by zero when
pulls == 0.
Example 4 — Estimate the causal effect of autopay on churn with IPW
Section titled “Example 4 — Estimate the causal effect of autopay on churn with IPW”Goal: Estimate whether has_autopay causally reduces churn in data/customers.csv after adjusting for observed confounders (payment_method, contract, plan, region, age, tenure_months, monthly_charges) using propensity score IPW.
Step 1 — Inspect the naive gap and confounding by payment method
Section titled “Step 1 — Inspect the naive gap and confounding by payment method”naive_rates = customers.groupby("has_autopay")["churned"].mean()naive_diff = float(naive_rates.loc[1] - naive_rates.loc[0])autopay_by_pay = ( customers.groupby("payment_method")["has_autopay"] .agg(["count", "mean"]) .rename(columns={"mean": "autopay_rate"}))autopay_by_pay["churn_rate"] = customers.groupby("payment_method")["churned"].mean()print(f"Naive churn diff (autopay=1 minus autopay=0): {naive_diff:+.4f}")print()print(autopay_by_pay.round(3))Naive churn diff (autopay=1 minus autopay=0): -0.0493
count autopay_rate churn_ratepayment_methodbank_transfer 1209 0.805 0.174credit_card 1360 0.756 0.158electronic_check 1563 0.160 0.248paypal 868 0.454 0.174Customers using electronic_check have both the lowest autopay enrollment (16.0%) and the highest churn rate (24.8%). That makes payment_method a classic confounder: it pulls down the apparent churn rate of the autopay group even if autopay itself had a smaller effect.
Step 2 — Fit the propensity model, check overlap and compute Hájek IPW
Section titled “Step 2 — Fit the propensity model, check overlap and compute Hájek IPW”Exclude post-treatment behavioral signals (support_tickets, logins_last_30d, avg_session_minutes) that could act as mediators or colliders, and estimate propensity scores from baseline account attributes only.
cat_cols = ["payment_method", "contract", "plan", "region"]num_cols = ["age", "tenure_months", "monthly_charges"]X_conf = customers[cat_cols + num_cols]t_auto = customers["has_autopay"].to_numpy()y_churn = customers["churned"].to_numpy()
pre = ColumnTransformer( [ ("cat", OneHotEncoder(drop="first", sparse_output=False), cat_cols), ("num", StandardScaler(), num_cols), ])ps_pipe = make_pipeline(pre, LogisticRegression(max_iter=1000))ps_pipe.fit(X_conf, t_auto)ps = ps_pipe.predict_proba(X_conf)[:, 1]
def hajek_ipw(y: np.ndarray, t: np.ndarray, e: np.ndarray) -> float: w1 = t / e w0 = (1 - t) / (1 - e) return float(np.sum(w1 * y) / np.sum(w1) - np.sum(w0 * y) / np.sum(w0))
ate_ipw = hajek_ipw(y_churn, t_auto, ps)ols_adj = smf.ols( "churned ~ has_autopay + C(payment_method) + C(contract) + C(plan)" " + C(region) + age + tenure_months + monthly_charges", data=customers,).fit(cov_type="HC3")
print(f"Propensity score range: [{ps.min():.3f}, {ps.max():.3f}]")print(f"Naive difference: {naive_diff:+.4f}")print(f"Hajek IPW ATE: {ate_ipw:+.4f}")print( f"OLS adjusted coef: {ols_adj.params['has_autopay']:+.4f} " f"(HC3 SE={ols_adj.bse['has_autopay']:.4f}, p={ols_adj.pvalues['has_autopay']:.4f})")Propensity score range: [0.087, 0.879]Naive difference: -0.0493Hajek IPW ATE: -0.0272OLS adjusted coef: -0.0213 (HC3 SE=0.0124, p=0.0860)Overlap is healthy (, nowhere near 0 or 1). Once we adjust for confounders, the estimated autopay effect shrinks almost in half — from -4.93 percentage points naive to -2.72 percentage points under Hájek IPW (and -2.13 pp under OLS adjustment).
Step 3 — Check covariate balance (SMD) and bootstrap a 95% CI
Section titled “Step 3 — Check covariate balance (SMD) and bootstrap a 95% CI”Compute the Standardized Mean Difference before and after IPW across all encoded confounders, then run a 200-replicate paired bootstrap (refitting the propensity score inside each replicate) for a 95% confidence interval.
X_design = pre.transform(X_conf)feat_names = [ name.split("__", 1)[1] for name in pre.get_feature_names_out()]weights = np.where(t_auto == 1, 1.0 / ps, 1.0 / (1.0 - ps))
def smd_vector( X_mat: np.ndarray, t: np.ndarray, w: np.ndarray | None = None) -> np.ndarray: m1 = t == 1 m0 = t == 0 if w is None: mu1, mu0 = X_mat[m1].mean(axis=0), X_mat[m0].mean(axis=0) v1, v0 = X_mat[m1].var(axis=0, ddof=1), X_mat[m0].var(axis=0, ddof=1) else: w1, w0 = w[m1], w[m0] mu1 = np.average(X_mat[m1], axis=0, weights=w1) mu0 = np.average(X_mat[m0], axis=0, weights=w0) v1 = np.average((X_mat[m1] - mu1) ** 2, axis=0, weights=w1) v0 = np.average((X_mat[m0] - mu0) ** 2, axis=0, weights=w0) return (mu1 - mu0) / np.sqrt(0.5 * (v1 + v0))
smd_raw = np.abs(smd_vector(X_design, t_auto))smd_ipw = np.abs(smd_vector(X_design, t_auto, weights))balance = pd.DataFrame( {"raw_abs_smd": smd_raw, "ipw_abs_smd": smd_ipw}, index=feat_names).sort_values("raw_abs_smd", ascending=False)print(balance.head(5).round(4))print(f"Max |SMD| raw: {smd_raw.max():.4f} -> after IPW: {smd_ipw.max():.4f}")
rng = np.random.default_rng(42)boot_ates = []n_rows = len(customers)for _ in range(200): idx = rng.integers(0, n_rows, size=n_rows) lr = LogisticRegression(max_iter=1000).fit(X_design[idx], t_auto[idx]) e_b = np.clip(lr.predict_proba(X_design[idx])[:, 1], 0.02, 0.98) boot_ates.append(hajek_ipw(y_churn[idx], t_auto[idx], e_b))ci_lo, ci_hi = np.percentile(boot_ates, [2.5, 97.5])print(f"IPW 95% bootstrap CI: [{ci_lo:+.4f}, {ci_hi:+.4f}]") raw_abs_smd ipw_abs_smdpayment_method_electronic_check 1.136 0.009payment_method_credit_card 0.585 0.003payment_method_paypal 0.138 0.002age 0.075 0.014plan_standard 0.068 0.004Max |SMD| raw: 1.1357 -> after IPW: 0.0137IPW 95% bootstrap CI: [-0.0539, -0.0024]IPW collapses the massive electronic_check imbalance from |SMD| = 1.14 down below 0.01, bringing every single confounder well under the 0.10 balance threshold.
Step 4 — Plot propensity overlap and covariate balance
Section titled “Step 4 — Plot propensity overlap and covariate balance”fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.0, 3.8))ax1.hist( ps[t_auto == 0], bins=25, alpha=0.6, density=True, label="No autopay", color="#d95f02",)ax1.hist( ps[t_auto == 1], bins=25, alpha=0.6, density=True, label="Autopay", color="#1b9e77",)ax1.set_xlabel("Estimated propensity score P(autopay=1 | X)")ax1.set_ylabel("Density")ax1.set_title("Propensity score overlap")ax1.legend()ax1.grid(alpha=0.25)
top_bal = balance.head(7).iloc[::-1]y_pos = np.arange(len(top_bal))ax2.scatter(top_bal["raw_abs_smd"], y_pos, label="Unweighted", color="#d95f02", s=50)ax2.scatter( top_bal["ipw_abs_smd"], y_pos, label="IPW", color="#1b9e77", s=50, marker="s")ax2.axvline(0.10, linestyle="--", color="#555555", label="0.10 threshold")ax2.set_yticks(y_pos)ax2.set_yticklabels(top_bal.index, fontsize=8)ax2.set_xlabel("Absolute Standardized Mean Difference")ax2.set_title("Covariate balance (Love plot)")ax2.legend(fontsize=8)ax2.grid(alpha=0.25)fig.tight_layout()plt.show()
Common mistakes:
- Including post-treatment outcomes or mediators in the propensity model.
- Using unnormalized Horvitz–Thompson weights when propensity scores approach 0 or 1, which explodes variance; always inspect overlap and use Hájek weights (plus trimming if needed).
Example 5 — Measure campaign and store-opening impact with Difference-in-Differences
Section titled “Example 5 — Measure campaign and store-opening impact with Difference-in-Differences”Goal: Use Difference-in-Differences with parallel-trends checks on two real business questions: (a) how many daily signups the April 2024 marketing campaign added in data/web_traffic.csv, and (b) whether opening store S12 in Denver on 2023-06-15 lifted total West-region orders in data/sales.csv.
Step 1 — Estimate the April 2024 marketing campaign lift on data/web_traffic.csv
Section titled “Step 1 — Estimate the April 2024 marketing campaign lift on data/web_traffic.csv”A major marketing campaign starts on Monday 2024-04-08 (ISO week 15 of 2024). Use ISO week 14 as the pre-period, ISO week 15 as the post-period, and the same calendar weeks in 2023 (when no April campaign ran) as the seasonal control group. First test parallel trends on weeks 13 → 14.
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([13, 14, 15])].copy()sub["treated"] = (sub["year"] == 2024).astype(int)
# Parallel trends check: week 13 -> week 14 (both pre-campaign)pre_wt = sub[sub["iso_week"].isin([13, 14])].copy()pre_wt["w14"] = (pre_wt["iso_week"] == 14).astype(int)pt_wt = smf.ols("signups ~ treated * w14", data=pre_wt).fit(cov_type="HC3")
# DiD: week 14 (pre) -> week 15 (campaign)did_wt_df = sub[sub["iso_week"].isin([14, 15])].copy()did_wt_df["post"] = (did_wt_df["iso_week"] == 15).astype(int)did_wt = smf.ols("signups ~ treated * post", data=did_wt_df).fit(cov_type="HC3")
print("Mean daily signups (row=treated 2024, col=post week 15):")print(did_wt_df.pivot_table(index="treated", columns="post", values="signups").round(2))print( f"Pre-trend check (w13->w14): diff={pt_wt.params['treated:w14']:+.2f}, " f"p={pt_wt.pvalues['treated:w14']:.4f}")print( f"Campaign DiD lift: {did_wt.params['treated:post']:+.2f} signups/day " f"(SE={did_wt.bse['treated:post']:.2f}, p={did_wt.pvalues['treated:post']:.4f})")Mean daily signups (row=treated 2024, col=post week 15):post 0 1treated0 58.43 56.861 77.14 206.00Pre-trend check (w13->w14): diff=+3.00, p=0.7383Campaign DiD lift: +130.43 signups/day (SE=44.14, p=0.0031)In the pre-period, 2024 and 2023 moved in lockstep (slope difference +3.0 signups/day, ), supporting parallel trends. Once the campaign launched in week 15, daily signups jumped by +130.4 above what the 2023 seasonal control predicts ().
Step 2 — Check net regional lift vs. cannibalization when store S12 opened
Section titled “Step 2 — Check net regional lift vs. cannibalization when store S12 opened”Store S12 (Denver, West region) opened on 2023-06-15. Compare daily orders in the West region (west = 1) against the other three regions (west = 0) over the 90 days before and 90 days after the opening.
sales["order_date"] = pd.to_datetime(sales["order_date"])daily_reg = ( sales.groupby(["order_date", "region"])["order_id"] .nunique() .reset_index(name="orders"))win = daily_reg[ (daily_reg["order_date"] >= "2023-03-17") & (daily_reg["order_date"] <= "2023-09-12")].copy()win["west"] = (win["region"] == "West").astype(int)win["post"] = (win["order_date"] >= "2023-06-15").astype(int)
pre_s = win[win["post"] == 0].copy()pre_s["day"] = (pre_s["order_date"] - pre_s["order_date"].min()).dt.dayspt_s = smf.ols("orders ~ west * day", data=pre_s).fit(cov_type="HC3")did_s = smf.ols("orders ~ west * post", data=win).fit(cov_type="HC3")
s12_orders = sales.loc[ (sales["store_id"] == "S12") & (sales["order_date"] <= "2023-09-12"), "order_id"].nunique()print(f"Orders processed by new store S12 in first 90 days: {s12_orders}")print(f"Pre-trend check (West vs others): p={pt_s.pvalues['west:day']:.4f}")print( f"West net DiD lift: {did_s.params['west:post']:+.3f} orders/day " f"(SE={did_s.bse['west:post']:.3f}, p={did_s.pvalues['west:post']:.4f})")Orders processed by new store S12 in first 90 days: 86Pre-trend check (West vs others): p=0.7142West net DiD lift: -0.171 orders/day (SE=0.368, p=0.6421)Look how valuable DiD is for avoiding false wins: S12 logged 86 orders in its first 90 days, so a naive store-only report might claim 86 net new orders. Yet the region-level DiD against East, North and South shows no statistically significant net regional lift () — much of S12’s volume shifted over from existing West stores or matched normal summer growth.
Common mistakes:
- Skipping the pre-trend check; if treated and control were already diverging before the intervention, the DiD estimate merely extrapolates that pre-existing divergence.
- Measuring DiD at the store level when neighboring stores share customers (a SUTVA spillover violation); aggregate to the market or region level to capture net lift.
Example 6 — Model count data with Poisson and Negative Binomial GLMs
Section titled “Example 6 — Model count data with Poisson and Negative Binomial GLMs”Goal: Fit Poisson and Negative Binomial models on two count targets — daily order counts in data/sales.csv (strongly overdispersed) and support_tickets in data/customers.csv — then compare dispersion, AIC/BIC and incidence rate ratios.
Step 1 — Fit Poisson vs. Negative Binomial on daily orders (data/sales.csv)
Section titled “Step 1 — Fit Poisson vs. Negative Binomial on daily orders (data/sales.csv)”daily = ( sales.groupby("order_date") .agg(orders=("order_id", "nunique"), avg_discount=("discount", "mean")) .reset_index())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_orders = "orders ~ year_t + C(dow) + C(month) + avg_discount"pois_orders = smf.glm( formula_orders, data=daily, family=sm.families.Poisson()).fit()nb_orders = smf.negativebinomial(formula_orders, data=daily).fit( method="bfgs", maxiter=300, disp=False)
disp_ratio = pois_orders.pearson_chi2 / pois_orders.df_residprint( f"Daily orders mean={daily['orders'].mean():.2f}, " f"var={daily['orders'].var():.2f}")print( f"Poisson AIC={pois_orders.aic:.1f} BIC={pois_orders.bic_llf:.1f} " f"Pearson/df={disp_ratio:.2f}")print( f"NegBin AIC={nb_orders.aic:.1f} BIC={nb_orders.bic:.1f} " f"alpha={nb_orders.params['alpha']:.4f}")Daily orders mean=20.35, var=104.04Poisson AIC=4598.3 BIC=4690.2 Pearson/df=1.53NegBin AIC=4502.0 BIC=4598.4 alpha=0.0237Even after controlling for day of week, month, linear growth and average discount, daily orders remain overdispersed (). The Negative Binomial model improves AIC by nearly 100 points and produces honest standard errors.
Step 2 — Interpret Incidence Rate Ratios and model support_tickets
Section titled “Step 2 — Interpret Incidence Rate Ratios and model support_tickets”Exponentiating log-link coefficients gives Incidence Rate Ratios (IRRs): multiplicative changes in the expected count per 1-unit increase in the predictor.
disc_irr = np.exp(0.10 * nb_orders.params["avg_discount"])print(f"Orders IRR for +1 year trend: {np.exp(nb_orders.params['year_t']):.3f}x")print(f"Orders IRR for +0.10 avg_discount: {disc_irr:.3f}x")
formula_tix = ( "support_tickets ~ C(contract) + C(plan) + tenure_months" " + monthly_charges + logins_last_30d")pois_tix = smf.glm(formula_tix, data=customers, family=sm.families.Poisson()).fit()nb_tix = smf.negativebinomial(formula_tix, data=customers).fit( method="bfgs", maxiter=300, disp=False)tix_disp = pois_tix.pearson_chi2 / pois_tix.df_residprint( f"\nTickets Poisson AIC={pois_tix.aic:.1f} (Pearson/df={tix_disp:.3f}) | " f"NegBin AIC={nb_tix.aic:.1f} (alpha={nb_tix.params['alpha']:.4f})")Orders IRR for +1 year trend: 1.207xOrders IRR for +0.10 avg_discount: 1.765x
Tickets Poisson AIC=14263.0 (Pearson/df=1.039) | NegBin AIC=14261.0 (alpha=0.0323)For support_tickets, Pearson/df is 1.04 and alpha is tiny (0.032), so Poisson and Negative Binomial agree closely (AIC differs by only 2 points). Checking the dispersion ratio tells you immediately whether Poisson is adequate or Negative Binomial is essential.
Common mistakes:
- Reading a log-link coefficient as “+0.20 orders”; on a log link, means +22.1% more expected orders.
- Relying on default Poisson p-values when
pearson_chi2 / df_residis well above 1.
Example 7 — Build Kaplan–Meier retention curves by contract type
Section titled “Example 7 — Build Kaplan–Meier retention curves by contract type”Goal: Implement the Kaplan–Meier estimator with Greenwood 95% confidence intervals in pure NumPy/pandas on data/customers.csv and compare customer retention across month-to-month, one-year and two-year contracts.
Step 1 — Write a clean Kaplan–Meier function with right censoring
Section titled “Step 1 — Write a clean Kaplan–Meier function with right censoring”Each row in data/customers.csv records tenure_months (time) and churned (1 = event observed, 0 = right-censored active customer).
def kaplan_meier(time: np.ndarray, event: np.ndarray) -> pd.DataFrame: """Compute Kaplan-Meier survival curve and Greenwood 95% CI.""" order = np.argsort(time) t_sorted, e_sorted = time[order], event[order] event_times = np.unique(t_sorted[e_sorted == 1])
rows = [(0.0, len(t_sorted), 0, 1.0, 0.0, 1.0, 1.0)] surv = 1.0 greenwood_sum = 0.0 for tj in event_times: n_risk = int(np.sum(t_sorted >= tj)) d_j = int(np.sum((t_sorted == tj) & (e_sorted == 1))) surv *= 1.0 - d_j / n_risk if n_risk > d_j: greenwood_sum += d_j / (n_risk * (n_risk - d_j)) se = surv * np.sqrt(greenwood_sum) ci_lo = max(0.0, surv - 1.96 * se) ci_hi = min(1.0, surv + 1.96 * se) rows.append((float(tj), n_risk, d_j, surv, se, ci_lo, ci_hi))
return pd.DataFrame( rows, columns=["time", "n_risk", "events", "survival", "se", "ci_lo", "ci_hi"] )
def survival_at(km_df: pd.DataFrame, month: float) -> float: return float(km_df.loc[km_df["time"] <= month, "survival"].iloc[-1])
km_curves: dict[str, pd.DataFrame] = {}for contract, grp in customers.groupby("contract"): km = kaplan_meier(grp["tenure_months"].to_numpy(), grp["churned"].to_numpy()) km_curves[str(contract)] = km print( f"{contract:<15} n={len(grp):>4d} events={int(grp['churned'].sum()):>3d} " f"S(12)={survival_at(km, 12):.3f} S(36)={survival_at(km, 36):.3f} " f"S(60)={survival_at(km, 60):.3f}" )month-to-month n=2784 events=823 S(12)=0.742 S(36)=0.557 S(60)=0.480one-year n=1225 events=108 S(12)=0.974 S(36)=0.888 S(60)=0.846two-year n= 991 events= 32 S(12)=0.995 S(36)=0.972 S(60)=0.952By month 12, only 74.2% of month-to-month customers remain active, compared to 97.4% of one-year and 99.5% of two-year customers. By month 60, month-to-month survival drops to 48.0%, whereas two-year contracts retain over 95%.
Step 2 — Plot the step curves with 95% confidence bands
Section titled “Step 2 — Plot the step curves with 95% confidence bands”fig, ax = plt.subplots(figsize=(7.0, 4.0))palette = {"month-to-month": "#d95f02", "one-year": "#7570b3", "two-year": "#1b9e77"}for contract, km in km_curves.items(): color = palette[contract] ax.step(km["time"], km["survival"], where="post", label=contract, color=color, lw=2) ax.fill_between( km["time"], km["ci_lo"], km["ci_hi"], step="post", alpha=0.18, color=color )ax.set_xlabel("Tenure (months)")ax.set_ylabel("Estimated survival probability S(t)")ax.set_title("Kaplan-Meier customer retention by contract type (95% Greenwood CI)")ax.set_ylim(0.35, 1.03)ax.grid(alpha=0.3)ax.legend()fig.tight_layout()plt.show()
Common mistakes:
- Averaging
tenure_monthsoverchurned == 1rows only; ignoring right-censored active customers creates severe survivorship/selection bias. - Plotting Kaplan–Meier curves with straight diagonal lines instead of
where="post"step functions; survival only drops at observed event times.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Adjusting for a collider or mediator | Estimated treatment effect flips sign or shrinks to zero even when a true effect exists | Draw the causal DAG first; adjust only for pre-treatment confounders |
| Peeking at an A/B test daily and stopping when | False-positive rate balloons from 5% to 20–30% | Wait for the fixed sample size or use sequential alpha-spending boundaries |
| Ignoring a Sample Ratio Mismatch (SRM) | Apparent huge lift disappears after shipping | Run stats.chisquare on group counts first; halt analysis if |
| Using a post-treatment variable in CUPED | Biased ATE that understates or reverses the true effect | Restrict CUPED covariates strictly to pre-experiment history |
| Running IPW without checking overlap or SMD | Huge standard errors and unstable ATE from weights of 100+ | Inspect propensity histograms, use Hájek IPW, trim extreme scores and verify max |
| Running DiD without checking pre-trends | Pre-existing growth differences masquerade as a treatment effect | Plot pre-period trends and test the pre-treatment group × time slope |
| Using Poisson GLM on overdispersed counts | Tiny p-values and overly narrow confidence intervals | Check pearson_chi2 / df_resid; switch to Negative Binomial when dispersion > 1.2 |
| Dropping censored rows in retention analysis | Grossly underestimated customer lifetime | Use Kaplan–Meier so right-censored units stay in the risk set until censoring |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Product engineering and feature flags: Experimentation platforms run automated SRM alerts, CUPED variance reduction and multi-armed bandit rollouts on every UI change and ranking tweak.
- Clinical trials and epidemiology: Kaplan–Meier curves, log-rank tests, propensity matching and O’Brien–Fleming interim stopping boundaries are standard regulatory tools for evaluating treatments.
- Public policy and economics: Difference-in-Differences and propensity weighting evaluate minimum-wage laws, transit expansions and education programs when randomized trials are impossible.
- Site reliability and hardware engineering: Survival analysis models time-to-failure of servers, SSDs and sensors where most machines are still running (right-censored) at analysis time.
Summary
Section titled “Summary”- Causal questions target potential outcomes (); naive group differences mix the true effect with selection bias.
- Causal DAGs tell you what to adjust for: adjust for confounders, leave mediators alone for total effects, and never condition on colliders.
- Guard every experiment with an SRM check, avoid naive peeking, shrink variance with CUPED using pre-experiment covariates, and consider Thompson sampling when short-term regret matters more than fixed-horizon inference.
- For observational data, propensity score IPW balances observed confounders (verify overlap and ), while Difference-in-Differences removes time-invariant unobserved differences provided parallel trends hold.
- GLMs extend linear regression to binary, count and skewed positive targets via link functions; prefer Negative Binomial over Poisson whenever counts are overdispersed.
- Kaplan–Meier estimates retention accurately in the presence of right censoring by keeping active customers in the risk set up to their censoring time.
Self-check questions
Section titled “Self-check questions”Q1. What is the fundamental problem of causal inference, and how does randomization address it?
Answer
For any individual unit, you can observe only or , never both. Randomization makes treatment assignment independent of potential outcomes, so the control group’s average outcome is an unbiased stand-in for the treated group’s unobserved counterfactual, making selection bias zero on average.
Q2. Why can adding more control variables to a regression sometimes make a causal estimate worse?
Answer
If an added variable is a collider (caused by both treatment and outcome), conditioning on it opens a spurious non-causal path and introduces collider bias. If it is a mediator (on the path from treatment to outcome), conditioning on it blocks part of the causal effect you want to measure.
Q3. Your 50/50 checkout A/B test ends with 5,210 users in control and 4,790 in treatment, and treatment shows a +1.8% conversion lift (). Should you ship?
Answer
No. A 5,210 vs. 4,790 split has a severe Sample Ratio Mismatch (, ). Randomization or event logging is broken, so the +1.8% lift is untrustworthy until the engineering bug is found and the test is re-run.
Q4. If a pre-experiment covariate has correlation with the experiment outcome , roughly what fraction of the required sample size does CUPED save?
Answer
CUPED reduces outcome variance by a factor of , which saves of the required sample size for the same statistical power.
Q5. Why is time_on_page_s from data/ab_test.csv not a valid CUPED covariate for that checkout experiment?
Answer
time_on_page_s was measured during the experiment and was itself affected by treatment (mean 82.7 s in control vs. 91.8 s in treatment). Adjusting for a post-treatment variable violates the CUPED requirement that and biases the treatment effect.
Q6. When should you prefer a fixed-horizon A/B test over a Thompson-sampling bandit?
Answer
Prefer a fixed-horizon A/B test when you need clean confidence intervals and p-values, want to monitor multiple guardrail metrics equally, or are making a long-term product decision where the cost of a short experiment is small compared to shipping a wrong change.
Q7. What two diagnostics must you inspect before trusting an Inverse Probability Weighting (IPW) causal estimate?
Answer
First, propensity score overlap (positivity): treated and control propensity distributions should overlap without extreme values near 0 or 1. Second, post-weighting covariate balance: the absolute Standardized Mean Difference () should drop below 0.10 for every confounder after weighting.
Q8. What assumption makes Difference-in-Differences valid, and how do you check whether it is plausible?
Answer
The parallel trends assumption: without treatment, treated and control groups would have changed by the same amount over time. You check its plausibility by plotting multiple pre-treatment periods and testing whether the pre-period group-by-time trend interaction is close to zero.
Q9. You fit a Poisson GLM to daily ticket counts and see pearson_chi2 / df_resid = 3.8. What does this mean and what should you change?
Answer
The data is strongly overdispersed: conditional variance is nearly four times the mean, violating the Poisson assumption and making Poisson standard errors too small. Switch to a Negative Binomial model (or quasi-Poisson) and compare AIC/BIC.
Q10. In data/customers.csv, why are active (churned == 0) customers kept in the Kaplan–Meier calculation instead of dropped?
Answer
Active customers are right-censored: they provide real information that they survived at least through their current tenure_months. Keeping them in the at-risk denominator up to their censoring time avoids downward survival bias.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Practice causal graphs, CUPED, bandits, IPW, DiD, GLMs and Kaplan–Meier in Module 49 exercises.
- Put the full observational and survival workflow together in the Module 49 mini-project.
- Keep formulas,
statsmodelssnippets and diagnostics handy in the Module 49 cheat sheet. - Ready to test everything across Modules 45–49? Continue to the Part 6 checkpoint.