29. Statistics and probability — Mini-project
The retention team of a subscription business has a budget for one campaign next quarter. Before they choose a target, they ask you a precise question: which customer attributes are related to churn, how strongly, and how sure are we?
Write a script, churn_drivers.py, that tests every candidate attribute in data/customers.csv against churned, with the right test for each variable type. It reports effect sizes and confidence intervals, corrects for multiple testing and ends with a short written summary that a manager can read in one minute.
The project uses the core of module 29: choosing a test, Welch t-tests, Mann–Whitney U, chi-square tests, Cohen’s d, Cramér’s V, Wilson and Welch confidence intervals, and the Benjamini–Hochberg correction.
Dataset
Section titled “Dataset”data/customers.csv has 5,000 customers and 15 columns. The snapshot date is 2024-12-31. churned is 1 for customers who left in the last month (19.26% of all customers). The data dictionary describes every column.
Candidate attributes:
| Type | Columns |
|---|---|
| Numeric | age, tenure_months, monthly_charges, support_tickets, logins_last_30d, avg_session_minutes |
| Categorical | region, plan, contract, payment_method, has_autopay |
Leave out customer_id, signup_date (it duplicates tenure) and total_charges (about tenure × charges, with 10 blanks).
Requirements
Section titled “Requirements”Your script must:
- Load the data and print the overall churn rate with a 95% Wilson confidence interval.
- For each numeric attribute, compare churners and stayers with a Welch t-test and a Mann–Whitney U test. Report the two means, the difference in means with its 95% CI, both p-values and Cohen’s d.
- For each categorical attribute, run a chi-square test of independence. Report χ², df, the p-value, the smallest expected count and Cramér’s V.
- Collect the 11 primary p-values (Welch for numeric, chi-square for categorical) and adjust them with Benjamini–Hochberg. Mark each attribute as significant at an FDR of 5%.
- Print two ranked tables: numeric attributes by , categorical attributes by V. Every line must be at most 100 characters.
- For the strongest categorical driver, print the churn rate of each level with a 95% Wilson CI.
- End with
assertchecks: for example, that adjusted p-values are never smaller than raw ones, and that the overall CI contains the churn rate. - Write 4–6 sentences of findings. Separate “related to churn” from “causes churn”.
Step plan
Section titled “Step plan”-
Load and frame. Read the CSV. Build a boolean
is_churner. Compute the overall rate and its Wilson interval withproportion_confint(..., method="wilson"). -
Write two helper functions.
numeric_test(col)returns a dict with the means, the Welch difference and CI (ttest_ind(..., equal_var=False).confidence_interval()), both p-values and Cohen’s d.categorical_test(col)builds apd.crosstaband returns χ², df, p, the smallest expected count and V (stats.contingency.association). -
Run the tests. Loop over the two lists of columns. Put the results in two DataFrames.
-
Correct for multiple testing. Concatenate the primary p-values in one array, call
multipletests(p, method="fdr_bh")and write the adjusted values back to each table. -
Rank and print. Sort by
abs(d)and byV. Format numbers with f-strings orround, and check the width. -
Zoom in. For the strongest categorical attribute, use
groupby(...).agg(["sum", "count"])andproportion_confinton the arrays of counts. -
Check. Add asserts that catch mistakes: the BH values are ≥ the raw ones, every CI contains its estimate, Cohen’s d has the same sign as the difference in means.
-
Write the findings. Use the effect sizes to rank, the CIs to state the precision and the word “associated” for observational results.
A skeleton to start from:
import numpy as npimport pandas as pdfrom scipy import statsfrom statsmodels.stats.multitest import multipletestsfrom statsmodels.stats.proportion import proportion_confint
NUMERIC = ["age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]CATEGORICAL = ["region", "plan", "contract", "payment_method", "has_autopay"]
customers = pd.read_csv("data/customers.csv")is_churner = customers["churned"] == 1# TODO: overall rate and Wilson CI
def numeric_test(col: str) -> dict: # TODO: Welch t-test, CI, Mann-Whitney U, Cohen's d ...
def categorical_test(col: str) -> dict: # TODO: crosstab, chi2_contingency, smallest expected count, Cramer's V ...
# TODO: run the tests, BH-adjust, rank, print, zoom in, assertRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Right test per variable type | 3 | Welch + Mann–Whitney for numeric, chi-square for categorical; equal_var=False |
| Effect sizes | 3 | Cohen’s d and Cramér’s V for every attribute, used for the ranking |
| Confidence intervals | 2 | Wilson for rates, Welch CI for differences in means |
| Multiple testing | 2 | BH applied once to the 11 primary p-values |
| Assumption checks | 1 | The smallest expected count is reported and ≥ 5 |
| Output | 2 | Two ranked tables, lines ≤ 100 characters, no warnings |
| Self-checks | 1 | At least three meaningful asserts |
| Findings | 2 | 4–6 sentences; ranks by effect size; no causal claims |
| Total | 16 | 13 or more: you are ready for module 30 |
Stretch goals
Section titled “Stretch goals”- Test a hypothesis: age may have a U-shaped relationship with churn, with young and old customers churning more. A t-test of means can miss such a pattern. Cut
ageinto bins (pd.cut(customers["age"], [17, 25, 35, 50, 65, 80])) and run a chi-square test on the bins. - Bootstrap a 95% CI for Cramér’s V of
contract, usingstats.bootstrapwithpaired=Trueon the two columns (encode them as integer codes first). - Add a logistic regression with
smf.logit("churned ~ tenure_months + C(contract) + support_tickets", data=customers)and compare which attributes stay significant when they are adjusted for each other. - Turn the two helpers into a small
ChurnReportclass with ato_markdown()method that writes the tables tooutput/churn_report.md.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your formatting can differ; your numbers must not.
Reference solution
import numpy as npimport pandas as pdfrom scipy import statsfrom statsmodels.stats.multitest import multipletestsfrom statsmodels.stats.proportion import proportion_confint
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)
NUMERIC = ["age", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "avg_session_minutes"]CATEGORICAL = ["region", "plan", "contract", "payment_method", "has_autopay"]
customers = pd.read_csv("data/customers.csv")is_churner = customers["churned"] == 1k, n = int(is_churner.sum()), len(customers)low, high = proportion_confint(k, n, method="wilson")print( f"customers {n:,} | churners {k:,} | rate {k / n:.2%}" f" (95% CI {low:.2%} to {high:.2%})")
def numeric_test(col: str) -> dict: """Welch t-test, Mann-Whitney U and Cohen's d: churners vs stayers.""" a, b = customers.loc[is_churner, col], customers.loc[~is_churner, col] welch = stats.ttest_ind(a, b, equal_var=False) ci = welch.confidence_interval() mw = stats.mannwhitneyu(a, b, alternative="two-sided") n1, n2 = len(a), len(b) pooled = np.sqrt(((n1 - 1) * a.var() + (n2 - 1) * b.var()) / (n1 + n2 - 2)) return { "feature": col, "mean_churn": a.mean(), "mean_stay": b.mean(), "diff": a.mean() - b.mean(), "ci_low": ci.low, "ci_high": ci.high, "p": welch.pvalue, "p_mw": mw.pvalue, "d": (a.mean() - b.mean()) / pooled, }
def categorical_test(col: str) -> dict: """Chi-square test of independence with Cramer's V.""" table = pd.crosstab(customers[col], customers["churned"]) res = stats.chi2_contingency(table) return { "feature": col, "levels": table.shape[0], "chi2": res.statistic, "df": res.dof, "p": res.pvalue, "min_expected": res.expected_freq.min(), "V": stats.contingency.association(table, method="cramer"), }customers 5,000 | churners 963 | rate 19.26% (95% CI 18.19% to 20.38%)num = pd.DataFrame([numeric_test(c) for c in NUMERIC])cat = pd.DataFrame([categorical_test(c) for c in CATEGORICAL])
# One BH correction over the 11 primary p-values (Welch and chi-square).p_all = np.concatenate([num["p"].to_numpy(), cat["p"].to_numpy()])reject, p_bh, _, _ = multipletests(p_all, alpha=0.05, method="fdr_bh")num["p_bh"], num["sig"] = p_bh[: len(num)], reject[: len(num)]cat["p_bh"], cat["sig"] = p_bh[len(num):], reject[len(num):]
num = num.sort_values("d", key=abs, ascending=False).reset_index(drop=True)cat = cat.sort_values("V", ascending=False).reset_index(drop=True)
print("Numeric attributes (churners minus stayers), ranked by |d|")for r in num.itertuples(): print(f"{r.feature:<20} {r.mean_churn:6.2f} vs {r.mean_stay:6.2f} " f"diff {r.diff:+6.2f} [{r.ci_low:+6.2f}, {r.ci_high:+6.2f}] " f"d {r.d:+.2f} p_bh {r.p_bh:.1e} {'*' if r.sig else ''}")print()print("Categorical attributes, ranked by Cramer's V")for r in cat.itertuples(): print(f"{r.feature:<15} chi2 {r.chi2:7.1f} df {r.df} min_exp {r.min_expected:6.1f} " f"V {r.V:.3f} p_bh {r.p_bh:.1e} {'*' if r.sig else ''}")Numeric attributes (churners minus stayers), ranked by |d|tenure_months 11.72 vs 25.79 diff -14.07 [-15.12, -13.01] d -0.74 p_bh 1.0e-129 *support_tickets 1.74 vs 1.12 diff +0.62 [ +0.53, +0.72] d +0.54 p_bh 1.6e-34 *monthly_charges 66.58 vs 59.47 diff +7.11 [ +5.35, +8.87] d +0.31 p_bh 1.0e-14 *logins_last_30d 10.20 vs 12.11 diff -1.90 [ -2.44, -1.37] d -0.24 p_bh 7.0e-12 *avg_session_minutes 13.50 vs 14.53 diff -1.03 [ -1.56, -0.51] d -0.13 p_bh 1.4e-04 *age 41.26 vs 42.50 diff -1.24 [ -2.26, -0.23] d -0.10 p_bh 1.8e-02 *
Categorical attributes, ranked by Cramer's Vcontract chi2 439.7 df 2 min_exp 190.9 V 0.297 p_bh 1.8e-95 *plan chi2 85.9 df 2 min_exp 190.7 V 0.131 p_bh 6.1e-19 *payment_method chi2 45.5 df 3 min_exp 167.2 V 0.095 p_bh 1.1e-09 *has_autopay chi2 19.2 df 1 min_exp 453.6 V 0.062 p_bh 1.7e-05 *region chi2 2.9 df 3 min_exp 210.1 V 0.024 p_bh 4.0e-01top = cat.loc[0, "feature"]counts = customers.groupby(top)["churned"].agg(["sum", "count"])lo, hi = proportion_confint(counts["sum"], counts["count"], method="wilson")zoom = pd.DataFrame({ "churned": counts["sum"], "customers": counts["count"], "rate": counts["sum"] / counts["count"], "ci_low": lo, "ci_high": hi,}).round(3)print(f"Churn rate by {top} (95% Wilson CI)")print(zoom)print()agree = ((num["p_mw"] <= 0.05) == (num["p"] <= 0.05)).all()print(f"Mann-Whitney and Welch agree at 5% for all {len(num)} attributes: {agree}")
assert low < k / n < highassert (num["p_bh"] >= num["p"]).all() and (cat["p_bh"] >= cat["p"]).all()assert (np.sign(num["d"]) == np.sign(num["diff"])).all()assert (num["ci_low"] <= num["diff"]).all() and (num["diff"] <= num["ci_high"]).all()assert (cat["min_expected"] >= 5).all()Churn rate by contract (95% Wilson CI) churned customers rate ci_low ci_highcontractmonth-to-month 823 2784 0.296 0.279 0.313one-year 108 1225 0.088 0.074 0.105two-year 32 991 0.032 0.023 0.045
Mann-Whitney and Welch agree at 5% for all 6 attributes: TrueFindings (as a manager would read them):
- Contract type is the strongest driver (Cramér’s V = 0.30). Month-to-month customers churn at 29.6% (95% CI 27.9% to 31.3%), against 8.8% on one-year and 3.2% on two-year contracts.
- Tenure is the strongest numeric driver (d = −0.74). Churners have been customers about 14 months less than stayers (CI 13.0 to 15.1 months). Support tickets follow (d = +0.54, about 0.6 more tickets).
- Monthly charges, logins, session length and age have small effects (|d| from 0.10 to 0.31). Plan, payment method and autopay have weak associations (V from 0.06 to 0.13). Region shows no evidence of a relationship (BH-adjusted p = 0.40).
- Ten of the eleven attributes stay significant after the BH correction. With 5,000 customers, significance is easy; the ranking by effect size is what should guide the campaign.
- These are associations, not causes. Contract and tenure overlap strongly: 91% of customers with 6 months or less are on month-to-month contracts. To learn whether a contract upgrade prevents churn, offer it to a random half of new month-to-month customers and compare.
How it works:
- Framing. The overall churn rate and its Wilson CI set the baseline that every other number is compared with.
- Numeric attributes. Welch’s t-test gives a p-value and a CI for the difference in means without assuming equal variances. The Mann–Whitney test is a robustness check for the skewed counts (tickets, logins). Cohen’s d puts all six attributes on one unit-free scale, so they can be ranked.
- Categorical attributes.
chi2_contingencytests each crosstab, andexpected_freq.min()checks its assumption. Cramér’s V ranks the strength of the associations, because χ² grows with the number of levels and the sample size. - Multiple testing. Eleven primary tests run at once. One BH correction over all of them controls the false discovery rate at 5%. With effects this strong, the correction changes little, but on a weaker dataset it is what keeps the report honest.
- Zoom-in.
proportion_confintaccepts arrays, so one call gives the Wilson interval for every level. - Checks. The asserts encode facts that must hold for any data: adjusted p-values are never smaller than raw ones, an interval contains its estimate and the sign of d follows the sign of the difference.
Alternative: a single logistic regression (smf.logit) of churn on all attributes estimates each effect adjusted for the others. It answers a different question: “does tenure still matter among customers with the same contract?” Module 36 covers logistic regression for prediction. Use both views: the one-variable tests for screening, the joint model for the story.