Skip to content

49. Causal inference, GLMs and advanced experimentation — Mini-project

The subscription growth team is debating three retention investments for next quarter:

  1. Incentivize autopay enrollment — based on a dashboard showing 16.9% churn with autopay vs. 21.9% without autopay.
  2. Prioritize early-tenure retention by contract — deciding which contract cohort loses customers fastest over the first 36 months.
  3. Reduce support ticket volume — identifying which account attributes drive higher support_tickets counts.

Your job is to write retention_decision_report.py on data/customers.csv. You will separate confounding from plausible causal impact using propensity score IPW (with overlap checks, SMD covariate balance and a bootstrap CI), compute Kaplan–Meier survival curves with Greenwood 95% confidence intervals by contract type, and compare Poisson vs. Negative Binomial GLMs for support_tickets — ending with a clear executive recommendation.

data/customers.csv contains 5,000 subscription customers as of snapshot date 2024-12-31 (see the data dictionary).

Role Columns Notes
Treatment & outcome (Part 1) has_autopay, churned Binary 0/1
Pre-treatment confounders (Part 1) payment_method, contract, plan, region, age, tenure_months, monthly_charges Exclude post-treatment behavioral signals (logins_last_30d, support_tickets, avg_session_minutes)
Survival analysis (Part 2) tenure_months, churned, contract churned == 0 is right-censored
Count GLM (Part 3) support_tickets vs. contract, plan, tenure_months, monthly_charges, logins_last_30d, has_autopay Non-negative integer count

Your script must:

  1. Confounding audit: print the naive churn difference (has_autopay == 1 minus 0) and a breakdown of autopay_rate and churn_rate by payment_method.
  2. Propensity score model & overlap: fit a logistic regression propensity model for has_autopay on the seven pre-treatment confounders, print the min/max propensity scores and confirm common support (0.05 < min, max < 0.95).
  3. Covariate balance (SMD): compute absolute Standardized Mean Differences before and after Hájek IPW for every encoded confounder, print the top 5 most imbalanced raw features and verify max(|SMD|) < 0.10 after weighting.
  4. Causal effect & uncertainty: compute the Hájek IPW ATE, a 200-replicate paired bootstrap 95% CI (refitting the propensity model inside each replicate), and compare against an HC3-robust OLS adjusted estimate.
  5. Kaplan–Meier retention: implement kaplan_meier(time, event) in pure NumPy/pandas (handling right-censored rows), print S(6), S(12), S(24) and S(36) with 95% Greenwood CIs for each contract type, and save/show a two-panel figure (propensity overlap + KM survival curves).
  6. Count GLM comparison: fit a Poisson GLM and a Negative Binomial model for support_tickets, report pearson_chi2 / df_resid, AIC, dispersion alpha, and exponentiated Incidence Rate Ratios (IRRs) with 95% CIs for the key predictors.
  7. Self-checks: end with assert statements verifying balance improvement, CI ordering, monotonic survival curves and valid GLM dispersion metrics.
  8. Executive summary: print a concise 3-bullet recommendation grounded in your numbers (explicitly distinguishing observational adjustment from a randomized trial).
  1. Load and audit confounding. Read data/customers.csv. Compute the naive churn gap and inspect payment_method as a confounder.

  2. Build the propensity pipeline. One-hot encode categorical confounders (drop="first") and standardize numeric confounders inside a ColumnTransformer, then fit LogisticRegression(max_iter=1000) to get ps = P(has_autopay=1 | X).

  3. Compute Hájek IPW and balance diagnostics. Write hajek_ipw(y, t, e) and smd_vector(X, t, w). Verify that weighting collapses the raw electronic_check imbalance below 0.10.

  4. Bootstrap the IPW interval. Resample rows with replacement 200 times (np.random.default_rng(42)), refit the logistic propensity model inside each draw, clip extreme scores to [0.02, 0.98], and take the 2.5th and 97.5th percentiles.

  5. Run Kaplan–Meier by contract. Write kaplan_meier(time, event) with Greenwood standard errors. Extract S(6), S(12), S(24) and S(36) per contract.

  6. Plot the two-panel executive visual. Left panel: overlapping propensity score histograms (has_autopay == 0 vs. 1). Right panel: Kaplan–Meier step curves (where="post") with shaded 95% Greenwood bands.

  7. Fit and compare count GLMs. Fit smf.glm(..., family=sm.families.Poisson()) and smf.negativebinomial(...).fit(method="bfgs", maxiter=300, disp=False) on support_tickets. Print dispersion, AIC, and IRRs (np.exp(params)).

  8. Assert and summarize. Add strict assert checks and print a 3-bullet executive decision summary.

Starter skeleton:

retention_decision_report.py (starter)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
customers = pd.read_csv("data/customers.csv")
CAT_CONFOUNDERS = ["payment_method", "contract", "plan", "region"]
NUM_CONFOUNDERS = ["age", "tenure_months", "monthly_charges"]
def hajek_ipw(y: np.ndarray, t: np.ndarray, e: np.ndarray) -> float:
# TODO: normalized IPW difference in means
...
def kaplan_meier(time: np.ndarray, event: np.ndarray) -> pd.DataFrame:
# TODO: product-limit survival curve + Greenwood 95% CI
...
# TODO: propensity model, SMD balance, bootstrap CI, KM summary, plot, count GLMs, asserts
Criterion Points Full points when
Confounding & overlap audit 2 Reports naive gap, payment-method breakdown and propensity min/max overlap
IPW balance diagnostics 3 Computes weighted/unweighted SMD for all confounders; confirms max ∣SMD∣<0.10\lvert\text{SMD}\rvert \lt 0.10
Causal estimate & CI 3 Reports Hájek IPW ATE, 200-run bootstrap 95% CI (refitting PS inside) and HC3 OLS comparison
Kaplan–Meier & figure 3 Pure NumPy/pandas KM with Greenwood CIs, monotonic curves, clean two-panel plot
Count GLM comparison 3 Compares Poisson vs. Negative Binomial on dispersion and AIC; reports IRRs
Self-checks & summary 2 Meaningful assert checks and a concise, non-overclaiming executive summary
Total 16 13 or more: ready for the Part 6 checkpoint
  1. Doubly robust (AIPW) check: add an Augmented IPW estimator combining the logistic propensity model with a logistic outcome model for churned and check whether it agrees with Hájek IPW and OLS.
  2. Two-sample log-rank test: compute the log-rank chi-square statistic comparing month-to-month vs. one-year survival curves from scratch.
  3. Heterogeneous effects: estimate the IPW ATE of has_autopay separately inside month-to-month vs. annual (one-year / two-year) contracts to see where autopay matters most.
  4. Experiment sizing with CUPED: design a follow-up randomized autopay-nudge A/B test using NormalIndPower (from module 29) to detect a -2.5 percentage-point churn reduction at 80% power.
Reference solution
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
CAT_COLS = ["payment_method", "contract", "plan", "region"]
NUM_COLS = ["age", "tenure_months", "monthly_charges"]
def hajek_ipw(y: np.ndarray, t: np.ndarray, e: np.ndarray) -> float:
w1 = t / e
w0 = (1.0 - t) / (1.0 - e)
return float((w1 @ y) / w1.sum() - (w0 @ y) / w0.sum())
def smd_vector(
X_mat: np.ndarray, t: np.ndarray, w: np.ndarray | None = None
) -> np.ndarray:
m1, m0 = t == 1, 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))
def kaplan_meier(time: np.ndarray, event: np.ndarray) -> pd.DataFrame:
order = np.argsort(time)
t_s, e_s = time[order], event[order]
event_times = np.unique(t_s[e_s == 1])
rows = [(0.0, len(t_s), 0, 1.0, 0.0, 1.0, 1.0)]
surv, gw = 1.0, 0.0
for tj in event_times:
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 = max(0.0, surv - 1.96 * se)
hi = min(1.0, surv + 1.96 * se)
rows.append((float(tj), n_risk, d_j, surv, se, lo, hi))
return pd.DataFrame(
rows, columns=["time", "n_risk", "events", "survival", "se", "ci_lo", "ci_hi"]
)
# 1. Confounding audit
t_auto = customers["has_autopay"].to_numpy()
y_churn = customers["churned"].to_numpy()
naive_diff = float(y_churn[t_auto == 1].mean() - y_churn[t_auto == 0].mean())
pay_tbl = customers.groupby("payment_method").agg(
n=("churned", "count"),
autopay_rate=("has_autopay", "mean"),
churn_rate=("churned", "mean"),
)
print("=== PART 1: AUTOPAY CAUSAL ANALYSIS ===")
print(f"Naive churn diff (autopay=1 - 0): {naive_diff:+.4f}")
print(pay_tbl.round(3))
# 2. Propensity score model & overlap
pre = ColumnTransformer(
[
("cat", OneHotEncoder(drop="first", sparse_output=False), CAT_COLS),
("num", StandardScaler(), NUM_COLS),
]
)
X_conf = customers[CAT_COLS + 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]
print(f"\nPropensity overlap: min={ps.min():.3f}, max={ps.max():.3f}")
# 3. Balance check (SMD)
X_mat = pre.transform(X_conf)
names = [col.split("__", 1)[1] for col in pre.get_feature_names_out()]
w_ipw = np.where(t_auto == 1, 1.0 / ps, 1.0 / (1.0 - ps))
smd_raw = np.abs(smd_vector(X_mat, t_auto))
smd_adj = np.abs(smd_vector(X_mat, t_auto, w_ipw))
bal = pd.DataFrame({"raw_smd": smd_raw, "ipw_smd": smd_adj}, index=names).sort_values(
"raw_smd", ascending=False
)
print(bal.head(5).round(4))
print(f"Max |SMD|: {smd_raw.max():.4f} (raw) -> {smd_adj.max():.4f} (IPW)")
# 4. IPW ATE, bootstrap CI, and OLS comparison
ate_ipw = hajek_ipw(y_churn, t_auto, ps)
rng = np.random.default_rng(42)
n_rows = len(customers)
boot_ates = []
for _ in range(200):
idx = rng.integers(0, n_rows, size=n_rows)
lr = LogisticRegression(max_iter=1000).fit(X_mat[idx], t_auto[idx])
e_b = np.clip(lr.predict_proba(X_mat[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])
ols = 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"\nHajek IPW ATE: {ate_ipw:+.4f} (95% boot CI [{ci_lo:+.4f}, {ci_hi:+.4f}])")
print(
f"HC3 OLS coef: {ols.params['has_autopay']:+.4f} "
f"(SE={ols.bse['has_autopay']:.4f}, p={ols.pvalues['has_autopay']:.4f})"
)
# 5. Kaplan-Meier retention by contract
print("\n=== PART 2: KAPLAN-MEIER SURVIVAL BY CONTRACT ===")
km_map: dict[str, pd.DataFrame] = {}
for contract, grp in customers.groupby("contract"):
km = kaplan_meier(grp["tenure_months"].to_numpy(), grp["churned"].to_numpy())
km_map[str(contract)] = km
vals = []
for m in (6, 12, 24, 36):
row = km.loc[km["time"] <= m].iloc[-1]
vals.append(f"S({m})={row['survival']:.3f}")
print(f"{contract:<15} {' '.join(vals)}")
# 6. Two-panel figure
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.2, 4.0))
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("Propensity score P(autopay=1 | X)")
ax1.set_ylabel("Density")
ax1.set_title("Propensity score overlap")
ax1.legend()
ax1.grid(alpha=0.25)
colors = {"month-to-month": "#d95f02", "one-year": "#7570b3", "two-year": "#1b9e77"}
for contract, km in km_map.items():
c = colors[contract]
ax2.step(km["time"], km["survival"], where="post", label=contract, color=c, lw=2)
ax2.fill_between(
km["time"], km["ci_lo"], km["ci_hi"], step="post", alpha=0.18, color=c
)
ax2.set_xlabel("Tenure (months)")
ax2.set_ylabel("Survival probability S(t)")
ax2.set_title("Kaplan-Meier retention by contract")
ax2.set_ylim(0.35, 1.03)
ax2.legend()
ax2.grid(alpha=0.25)
fig.tight_layout()
plt.show()
# 7. Count GLMs on support_tickets
print("\n=== PART 3: SUPPORT TICKETS COUNT GLMs ===")
formula_tix = (
"support_tickets ~ C(contract) + C(plan) + tenure_months"
" + monthly_charges + logins_last_30d + has_autopay"
)
pois = smf.glm(formula_tix, data=customers, family=sm.families.Poisson()).fit()
nb = smf.negativebinomial(formula_tix, data=customers).fit(
method="bfgs", maxiter=300, disp=False
)
disp = pois.pearson_chi2 / pois.df_resid
print(f"Poisson AIC={pois.aic:.1f} Pearson/df={disp:.3f}")
print(f"NegBin AIC={nb.aic:.1f} alpha={nb.params['alpha']:.4f}")
ci_nb = nb.conf_int()
irr_rows = []
key_terms = [
"C(contract)[T.one-year]",
"C(contract)[T.two-year]",
"has_autopay",
"tenure_months",
]
for term in key_terms:
irr_rows.append(
{
"term": term,
"IRR": np.exp(nb.params[term]),
"ci_lo": np.exp(ci_nb.loc[term, 0]),
"ci_hi": np.exp(ci_nb.loc[term, 1]),
"p": nb.pvalues[term],
}
)
print(pd.DataFrame(irr_rows).set_index("term").round(3))
# 8. Executive summary & asserts
print("\n=== EXECUTIVE SUMMARY ===")
print(
"- Autopay: naive -4.9 pp gap shrinks to -2.7 pp under IPW (CI [-5.4, -0.2] pp);\n"
" run a randomized autopay-nudge test before scaling incentives."
)
print(
"- Retention: month-to-month S(12)=74.2% vs 97.4%+ for annual contracts;\n"
" focus onboarding and upgrade offers on the first 12 months."
)
print(
"- Tickets: near-equidispersed (Pearson/df=1.04); longer tenure lowers tickets\n"
" slightly (IRR=0.994/mo, p<0.001), while autopay/contract IRRs sit near 1.0."
)
assert 0.05 < ps.min() and ps.max() < 0.95
assert smd_adj.max() < 0.10 < smd_raw.max()
assert ci_lo < ate_ipw < ci_hi
for km in km_map.values():
assert np.all(np.diff(km["survival"].to_numpy()) <= 1e-12)
assert disp > 0 and nb.params["alpha"] >= 0
Output
=== PART 1: AUTOPAY CAUSAL ANALYSIS ===
Naive churn diff (autopay=1 - 0): -0.0493
n autopay_rate churn_rate
payment_method
bank_transfer 1209 0.805 0.174
credit_card 1360 0.756 0.158
electronic_check 1563 0.160 0.248
paypal 868 0.454 0.174
Propensity overlap: min=0.087, max=0.879
raw_smd ipw_smd
payment_method_electronic_check 1.136 0.009
payment_method_credit_card 0.585 0.003
payment_method_paypal 0.138 0.002
age 0.075 0.014
plan_standard 0.068 0.004
Max |SMD|: 1.1357 (raw) -> 0.0137 (IPW)
Hajek IPW ATE: -0.0272 (95% boot CI [-0.0539, -0.0024])
HC3 OLS coef: -0.0213 (SE=0.0124, p=0.0860)
=== PART 2: KAPLAN-MEIER SURVIVAL BY CONTRACT ===
month-to-month S(6)=0.819 S(12)=0.742 S(24)=0.628 S(36)=0.557
one-year S(6)=0.989 S(12)=0.974 S(24)=0.935 S(36)=0.888
two-year S(6)=0.997 S(12)=0.995 S(24)=0.988 S(36)=0.972
=== PART 3: SUPPORT TICKETS COUNT GLMs ===
Poisson AIC=14265.0 Pearson/df=1.039
NegBin AIC=14263.0 alpha=0.0323
IRR ci_lo ci_hi p
term
C(contract)[T.one-year] 0.942 0.881 1.007 0.079
C(contract)[T.two-year] 0.999 0.924 1.080 0.977
has_autopay 1.004 0.954 1.057 0.877
tenure_months 0.994 0.993 0.996 0.000
=== EXECUTIVE SUMMARY ===
- Autopay: naive -4.9 pp gap shrinks to -2.7 pp under IPW (CI [-5.4, -0.2] pp);
run a randomized autopay-nudge test before scaling incentives.
- Retention: month-to-month S(12)=74.2% vs 97.4%+ for annual contracts;
focus onboarding and upgrade offers on the first 12 months.
- Tickets: near-equidispersed (Pearson/df=1.04); longer tenure lowers tickets
slightly (IRR=0.994/mo, p<0.001), while autopay/contract IRRs sit near 1.0.
Two-panel decision chart: left displays well-overlapping propensity score densities for autopay vs non-autopay customers; right shows Kaplan-Meier retention curves separating month-to-month from one-year and two-year contracts.
Reference solution diagnostics: propensity score overlap and contract retention curves.