Five questions every data project keeps asking
Projects rarely fail because nobody could compute an average. They fail because the conclusion was never earned: the experiment stopped the moment it looked promising, the sample was too small to detect anything, an observational association was narrated as a cause, or a model was declared better on a metric that could not tell the difference. Each failure below is paired with the tool that prevents it, with the calculations reproduced in Python.
- You will size, run and read an A/B test using a two-proportion z-test.
- You will run the power calculation before collecting data, not after the disappointment.
- You will match a causal question to a design that can actually answer it.
Prerequisites
- !Hypothesis testing and p-values
- !Confidence intervals for a proportion
- !Basic sampling distributions
What You'll Learn
- 1Pre-register an experiment with a metric, an alpha and a sample size
- 2Implement a two-proportion z-test and a power curve in Python
- 3Choose between randomization, matching, instruments and difference-in-differences
- 4Screen hundreds of features while controlling the false discovery rate
Matching the question to the tool
State the question in plain language before touching a dataset. The wording determines the design, and the design determines which numbers may appear in the conclusion.
| Question you are asked | Statistical tool | Failure it prevents |
|---|---|---|
| Did the new version help? | Two-sample proportion or mean test | Shipping a change driven by noise |
| How many users do we need? | Power analysis and effect size | Weeks of effort producing an inconclusive result |
| Did X cause Y? | Randomization, matching, instruments, difference-in-differences | Presenting correlation as causation |
| Which features deserve a place in the model? | Chi-square screening, permutation importance | Bloated models that memorize rare words |
| Is the model's score meaningful? | Cross-validation, AUC-ROC, calibration | Accuracy that a majority-class guess would match |
Designing an experiment that can finish
An experiment is a contract written before the data arrives: fix the primary metric, the null hypothesis of no difference, the significance level, the sample size, and the stopping time. Random assignment makes the two groups differ, on average, only in the treatment.
Two details decide whether the result survives review. First, randomize at the level of the entity that experiences the treatment â a user, not a request â otherwise one person's variants contaminate each other. Second, never stop early because the p-value crossed 0.05: repeated peeking inflates the false positive rate far above the nominal level, so run for the pre-computed sample or use a sequential design built for it.
Here is the pooled proportion across both groups, is the difference worth detecting, and corresponds to the desired power, conventionally 0.80.
The two-proportion test, computed end to end
Control converted 50 of 1,000 visitors; treatment converted 70 of 1,000. The code below reproduces the statistic, the confidence interval for the difference, and the decision, without a black-box test function.
import math
from scipy.stats import norm
c1, n1, c2, n2 = 50, 1000, 70, 1000
p1, p2 = c1 / n1, c2 / n2
p_pool = (c1 + c2) / (n1 + n2)
se = math.sqrt(p_pool * (1 - p_pool) * (1 / n1 + 1 / n2))
z = (p1 - p2) / se
p_value = 2 * norm.sf(abs(z))
se_diff = math.sqrt(p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2)
diff = p2 - p1
lo, hi = diff - 1.96 * se_diff, diff + 1.96 * se_diff
print(f"control {p1:.3f} treatment {p2:.3f}")
print(f"z = {z:.3f} p-value = {p_value:.3f}")
print(f"lift = {diff:.3f} 95% CI = [{lo:.3f}, {hi:.3f}]")
The output gives and a two-sided , so the difference is not significant at . The confidence interval for the lift runs from about to , which is the honest summary: the data are compatible with no effect and with a gain of up to four percentage points. A point estimate alone would have hidden that range.
Power: the calculation that must happen first
Power is the probability of detecting an effect you care about, given the sample you will actually collect. It depends on four things â effect size , variance, significance level, sample size â and fixing three determines the fourth.
import math
from scipy.stats import norm
def n_per_group(p1, p2, alpha=0.05, power=0.80):
"""Sample size per arm for a two-sided two-proportion test."""
z_a = norm.ppf(1 - alpha / 2)
z_b = norm.ppf(power)
p_bar = (p1 + p2) / 2
num = (z_a * math.sqrt(2 * p_bar * (1 - p_bar))
+ z_b * math.sqrt(p1 * (1 - p1) + p2 * (1 - p2))) ** 2
return math.ceil(num / (p2 - p1) ** 2)
def achieved_power(p1, p2, n, alpha=0.05):
z_a = norm.ppf(1 - alpha / 2)
p_bar = (p1 + p2) / 2
se_null = math.sqrt(2 * p_bar * (1 - p_bar) / n)
se_alt = math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / n)
return norm.sf((z_a * se_null - abs(p2 - p1)) / se_alt)
need = n_per_group(0.10, 0.15)
print("per group:", need)
for n in (200, need, 2000):
print(f"n={n:5d} power={achieved_power(0.10, 0.15, n):.2f}")
Detecting a move from 10% to 15% at 80% power needs roughly 686 users per group. The same code aimed at a one-point move, 10% to 11%, needs about fifteen thousand per group â the reason effect size, not ambition, sets the budget. For means, Cohen's plays the same role: the raw difference divided by the pooled standard deviation.
â ī¸Underpowered studies are worse than none
A study with 40% power that fails to reject the null says almost nothing, yet costs the same to run and still gets reported. If the required sample exceeds what you can collect, enlarge the effect, lengthen the window, or admit the experiment cannot answer the question.
From correlation to causation: the method menu
Observational data cannot randomize, so each method buys identification with an assumption that cannot be tested directly. Knowing which assumption carries the claim is the entire game.
| Method | What it does | Assumption you inherit | Use when |
|---|---|---|---|
| Randomized experiment | Breaks confounding by design | Random assignment actually happened | You control assignment â the default |
| Propensity score matching | Rebuilds a control group from observables | No unmeasured confounders | Rich pre-treatment covariates exist |
| Instrumental variables | Uses exogenous variation in exposure | The instrument affects the outcome only through the treatment | A confounder cannot be measured |
| Difference-in-differences | Compares pre and post changes against a control | Parallel trends without the treatment | Before/after data with a comparison group |
A number without its identifying assumption is a correlation with a caption.
Screening features without drowning in p-values
Testing 500 words for association with a label at produces about 25 "significant" features even when nothing is related to anything. The Benjamini-Hochberg procedure fixes this: rank the p-values and keep those where the -th smallest is at most , controlling the expected proportion of false discoveries among the survivors.
import numpy as np
from scipy.stats import chi2_contingency
def screen_features(X, y, alpha=0.05):
"""X is a binary n-by-p matrix, y is a binary label vector."""
n, p = X.shape
pvals, effect = np.empty(p), np.empty(p)
for j in range(p):
table = np.array([
[np.sum((X[:, j] == 1) & (y == 1)), np.sum((X[:, j] == 0) & (y == 1))],
[np.sum((X[:, j] == 1) & (y == 0)), np.sum((X[:, j] == 0) & (y == 0))],
])
chi2, pvals[j], _, _ = chi2_contingency(table, correction=False)
effect[j] = np.sqrt(chi2 / table.sum()) # Cramer's V
order = np.argsort(pvals)
ranked = pvals[order]
passes = ranked <= alpha * np.arange(1, p + 1) / p
kept = order[np.flatnonzero(passes)] if passes.any() else np.array([], int)
return np.sort(kept), pvals, effect
rng = np.random.default_rng(4)
n, p = 800, 500
X = (rng.random((n, p)) < 0.06).astype(int)
true_cols = [17, 88, 203, 401]
y = (X[:, true_cols].sum(axis=1) + rng.normal(0, 1, n) >= 1.5).astype(int)
kept, pvals, effect = screen_features(X, y)
print("kept:", kept)
print("true:", true_cols)
print("false discoveries:", sorted(set(kept) - set(true_cols)))
Ranking by p-value alone favors features that are merely common, so pair selection with an effect size such as Cramer's . Under false discovery control this run recovers all four informative columns with no false discoveries; without the correction, dozens of random words memorize themselves into the training set.
Evaluation numbers a stakeholder can act on
Judging a fitted model needs the same discipline. Accuracy answers "how often are we right", which is useless when 95% of cases are one class. AUC answers "does the model rank a random positive above a random negative", and calibration answers "when it says 80%, is it right 80% of the time". Product decisions usually need the third.
| Metric | Question it answers | Blind spot |
|---|---|---|
| Accuracy | How often is the top-line prediction correct? | Inflated by class imbalance |
| AUC-ROC | Does the model rank positives above negatives? | Can look fine while probabilities are miscalibrated |
| Precision-recall AUC | How good is retrieval of the rare class? | Depends on deployment prevalence |
| Calibration error | Do predicted probabilities match observed rates? | Says nothing about ranking quality |
Report a cross-validated estimate with its spread, a baseline the model must beat, and â for any probabilistic output â a calibration check on held-out data.
What goes into the write-up
- The question, the metric, the alpha and the sample size, exactly as fixed before the run.
- The design: assignment mechanism, unit of randomization, duration, guardrail metrics.
- The estimate with a confidence interval, never a bare point estimate or bare p-value, in units a reader can act on.
- For observational work, the identifying assumption and the evidence supporting it.
- For feature screening, the correction applied and the number of tests performed.
Common Mistakes
Peeking at the dashboard daily and stopping when p drops below 0.05
Fix: Pre-compute the sample size and run to completion, or use sequential testing that spends alpha deliberately.
Quoting a 40% relative lift with no interval and no absolute numbers
Fix: Report absolute difference, relative lift and the confidence interval together; the interval shows what is still plausible.
Describing an observational difference as the impact of a feature
Fix: Name the confounder you cannot rule out and reach for matching, an instrument or difference-in-differences.
Testing hundreds of features at the uncorrected 0.05 level
Fix: Apply Benjamini-Hochberg or Bonferroni, and report how many hypotheses were tested.
Reporting accuracy on a 95-to-5 imbalanced problem
Fix: Use precision, recall, AUC or PR-AUC, and compare against the majority-class baseline.
Best Practices
- Pre-register the metric, alpha, sample size and stopping rule before collection
- Randomize at the level of the entity that experiences the treatment
- Report effect sizes and confidence intervals alongside every p-value
- Size every experiment with a power calculation
- Control the false discovery rate whenever more than a handful of tests run
Interview Questions
Q1: Why is stopping an experiment early a problem?
Each look at the data is another chance to cross the threshold by luck. Repeated testing at a fixed alpha inflates the true false positive rate well above 5%, so you need a pre-set sample size or a sequential method that controls error spending.
Q2: You observe a correlation in production logs. What would convince you it is causal?
A randomized experiment is the strongest evidence. Short of that, a credible instrument, a difference-in-differences design with parallel pre-trends, or propensity matching on rich pre-treatment covariates â each with its assumption stated explicitly.
Q3: How do you choose a sample size?
Start from the smallest effect worth detecting, pick alpha and power, then compute the required n from the variance. If the answer exceeds what you can collect, the effect is too small for that design.
Q4: You run 1,000 significance tests and get 60 hits. What now?
About 50 are expected by chance alone. Rank the p-values and apply Benjamini-Hochberg to control the false discovery rate, then check effect sizes for the survivors.