Master the science of experiment design and sample size determination
Statistical Power is the probability of correctly rejecting a false null hypothesis. It represents your ability to detect a true effect when one exists. Power = 1 - β, where β is the Type II error rate (false negative).
\[\text{Power} = P(\text{Reject } H_0 | H_1 \text{ is true})\]
\[\text{Power} = 1 - \beta\]
| H₀ True | H₀ False | |
|---|---|---|
| Reject H₀ | Type I (α) | Correct (Power) |
| Fail to Reject | Correct (1-α) | Type II (β) |
Power analysis involves four interconnected parameters: Sample Size (n), Effect Size (d or δ), Significance Level (α), and Power (1-β). Given any three, you can calculate the fourth.
\[d = \frac{\mu_1 - \mu_2}{\sigma_{pooled}}\]
\[\sigma_{pooled} = \sqrt{\frac{(n_1-1)s_1^2 + (n_2-1)s_2^2}{n_1 + n_2 - 2}}\]
\[n = 2 \cdot \left(\frac{(z_{1-\alpha/2} + z_{1-\beta})}{d}\right)^2\]
\[h = 2 \cdot (\arcsin\sqrt{p_1} - \arcsin\sqrt{p_2})\]
Used for comparing two proportions in A/B tests
Cohen's conventions:
\[f = \sqrt{\frac{\eta^2}{1 - \eta^2}}\]
Small: 0.1 | Medium: 0.25 | Large: 0.4
Minimum Detectable Effect (MDE) is the smallest effect size your experiment can reliably detect given your sample size, α, and power. It's a practical constraint, not a theoretical measure. Always frame MDE in business terms: "With 10K users per group, we can detect a 2% lift in conversion rate."
\[n = \frac{2\bar{p}(1-\bar{p})(z_{1-\alpha/2} + z_{1-\beta})^2}{(p_1 - p_2)^2}\]
where \(\bar{p} = (p_1 + p_2) / 2\) is the pooled proportion
# Sample Size Calculator for A/B Tests
import numpy as np
from scipy import stats
def sample_size_proportions(p1, p2, alpha=0.05, power=0.80):
"""
Calculate required sample size for a two-proportion z-test.
Parameters:
-----------
p1 : float - Baseline conversion rate (control)
p2 : float - Expected conversion rate (treatment)
alpha : float - Significance level (Type I error rate)
power : float - Statistical power (1 - Type II error rate)
Returns:
--------
n : int - Required sample size per group
"""
# Effect size (difference)
delta = abs(p2 - p1)
# Pooled proportion
p_pooled = (p1 + p2) / 2
# Pooled standard deviation
sigma = np.sqrt(2 * p_pooled * (1 - p_pooled))
# Z-values
z_alpha = stats.norm.ppf(1 - alpha / 2) # Two-tailed
z_beta = stats.norm.ppf(power)
# Sample size formula
n = ((z_alpha + z_beta) ** 2 * sigma ** 2) / (delta ** 2)
return int(np.ceil(n))
# Example: 5% baseline, detecting 1% absolute lift
baseline = 0.05
lift = 0.01
n = sample_size_proportions(baseline, baseline + lift)
print(f"Sample size needed per group: {n:,}")
# Output: Sample size needed per group: 3,842
from statsmodels.stats.power import TTestIndPower, NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
# Power analysis for t-test
analysis = TTestIndPower()
# Calculate sample size
effect_size = 0.5 # Cohen's d (medium effect)
alpha = 0.05
power = 0.80
n = analysis.solve_power(
effect_size=effect_size,
alpha=alpha,
power=power,
ratio=1.0, # Equal group sizes
alternative='two-sided'
)
print(f"Required n per group: {int(np.ceil(n))}")
# Calculate power for given sample size
power = analysis.solve_power(
effect_size=0.5,
nobs1=100,
alpha=0.05,
ratio=1.0,
alternative='two-sided'
)
print(f"Power with n=100: {power:.3f}")
# Power curve
import matplotlib.pyplot as plt
sample_sizes = np.arange(10, 200, 5)
powers = [analysis.solve_power(effect_size=0.5, nobs1=n, alpha=0.05)
for n in sample_sizes]
plt.figure(figsize=(10, 6))
plt.plot(sample_sizes, powers, 'b-', linewidth=2)
plt.axhline(y=0.8, color='r', linestyle='--', label='80% Power')
plt.xlabel('Sample Size per Group')
plt.ylabel('Statistical Power')
plt.title('Power Curve for d=0.5, α=0.05')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
| Effect Size (d) | α = 0.05, Power = 0.80 | α = 0.05, Power = 0.90 | α = 0.01, Power = 0.80 |
|---|---|---|---|
| 0.2 (Small) | 394 per group | 527 per group | 586 per group |
| 0.5 (Medium) | 64 per group | 86 per group | 95 per group |
| 0.8 (Large) | 26 per group | 34 per group | 38 per group |
def adjusted_sample_size(n_base,
attrition_rate=0.10,
non_compliance_rate=0.05,
clustering_deff=1.0):
"""
Adjust sample size for real-world factors.
Parameters:
-----------
n_base : int - Base sample size from power calculation
attrition_rate : float - Expected dropout rate
non_compliance_rate : float - Expected non-compliance rate
clustering_deff : float - Design effect for clustered data (1.0 = no clustering)
Returns:
--------
n_adjusted : int - Adjusted sample size
"""
# Adjust for attrition (need more to end with n_base)
n_attrition = n_base / (1 - attrition_rate)
# Adjust for non-compliance (dilutes effect size)
# If 5% don't comply, effective effect is 95% of true effect
# Need to increase n by (1/compliance)^2
compliance = 1 - non_compliance_rate
n_compliance = n_attrition / (compliance ** 2)
# Adjust for clustering (design effect)
# DEFF = 1 + (m-1)*ICC where m=cluster size, ICC=intraclass correlation
n_clustered = n_compliance * clustering_deff
return int(np.ceil(n_clustered))
# Example
n_base = 1000
n_adj = adjusted_sample_size(
n_base,
attrition_rate=0.15,
non_compliance_rate=0.10,
clustering_deff=1.5 # Moderate clustering
)
print(f"Base sample: {n_base:,}")
print(f"Adjusted sample: {n_adj:,}")
print(f"Inflation factor: {n_adj/n_base:.2f}x")
When data has hierarchical structure (users within companies, students within schools), observations are not independent:
\[DEFF = 1 + (m - 1) \cdot ICC\]
where m is the average cluster size and ICC is the intraclass correlation coefficient. Multiply your base sample size by DEFF.
# Group Sequential Design with spending functions
from scipy import stats
import numpy as np
def obrien_fleming_bounds(alpha, n_looks):
"""
Calculate O'Brien-Fleming spending function boundaries.
These are conservative early stopping boundaries.
"""
information_fractions = np.linspace(1/n_looks, 1, n_looks)
boundaries = []
for t in information_fractions:
# O'Brien-Fleming spending function
z_bound = stats.norm.ppf(1 - alpha/2) / np.sqrt(t)
boundaries.append(z_bound)
return information_fractions, boundaries
# Example: 4 interim looks
fractions, bounds = obrien_fleming_bounds(0.05, 4)
print("O'Brien-Fleming Boundaries:")
print(f"{'Look':<6} {'Info Fraction':<15} {'Z-boundary':<12} {'p-value':<10}")
print("-" * 45)
for i, (f, b) in enumerate(zip(fractions, bounds), 1):
p = 2 * (1 - stats.norm.cdf(b))
print(f"{i:<6} {f:<15.2f} {b:<12.3f} {p:<10.5f}")
import numpy as np
from scipy import stats
def bayesian_sample_size(prior_prob_h1=0.5,
effect_size=0.5,
desired_bf=10,
alpha=0.05):
"""
Estimate sample size for desired Bayes Factor.
Uses simulation to find n where we expect BF > desired_bf
with high probability when H1 is true.
"""
def expected_bf(n, d, prior=0.5):
"""Approximate expected Bayes Factor under H1"""
# Simplified BIC approximation
# BF ≈ exp((t^2 - log(n))/2) for large n
t_expected = d * np.sqrt(n/2)
log_bf = (t_expected**2 - np.log(n)) / 2
return np.exp(log_bf)
# Binary search for required n
n_low, n_high = 10, 10000
while n_high - n_low > 1:
n_mid = (n_low + n_high) // 2
bf = expected_bf(n_mid, effect_size, prior_prob_h1)
if bf < desired_bf:
n_low = n_mid
else:
n_high = n_mid
return n_high
# Example
n = bayesian_sample_size(effect_size=0.5, desired_bf=10)
print(f"Sample size for BF > 10: {n} per group")
from statsmodels.stats.power import TTestIndPower
from statsmodels.stats.multitest import multipletests
import numpy as np
def power_with_bonferroni(effect_size, n, n_comparisons, alpha=0.05):
"""
Calculate power when using Bonferroni correction.
"""
analysis = TTestIndPower()
# Bonferroni-adjusted alpha
alpha_adj = alpha / n_comparisons
# Power at adjusted alpha
power = analysis.solve_power(
effect_size=effect_size,
nobs1=n,
alpha=alpha_adj,
alternative='two-sided'
)
return power
def sample_size_multiple_comparisons(effect_size, n_comparisons,
power=0.8, alpha=0.05):
"""
Calculate sample size needed for desired power with multiple comparisons.
"""
analysis = TTestIndPower()
alpha_adj = alpha / n_comparisons
n = analysis.solve_power(
effect_size=effect_size,
alpha=alpha_adj,
power=power,
alternative='two-sided'
)
return int(np.ceil(n))
# Example: Testing 5 metrics simultaneously
n_metrics = 5
effect = 0.5
# Without correction
n_single = sample_size_multiple_comparisons(effect, 1)
# With Bonferroni
n_bonf = sample_size_multiple_comparisons(effect, n_metrics)
print(f"Sample size for single comparison: {n_single}")
print(f"Sample size with {n_metrics} comparisons (Bonferroni): {n_bonf}")
print(f"Inflation factor: {n_bonf/n_single:.2f}x")
Power tells you if you'll detect an effect; precision tells you how well you'll estimate it. For business decisions, sometimes you need tight confidence intervals (precision) more than just significance. Calculate your expected CI width: \(2 \cdot z_{1-\alpha/2} \cdot \frac{\sigma}{\sqrt{n}}\). If the CI is too wide to be actionable, you need more data.
Answer:
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
p1, p2 = 0.05, 0.051
h = proportion_effectsize(p1, p2) # ≈ 0.0045
analysis = NormalIndPower()
n = analysis.solve_power(effect_size=h, alpha=0.05, power=0.8)
# n ≈ 770,000 per group!
Answer:
Post-hoc power analysis is calculating power after an experiment using the observed effect size. It's problematic because:
What to do instead:
Answer: This is a clustering problem. Sessions within users are correlated.
DEFF = 1 + (m - 1) × ICC
# m = average sessions per user
# ICC = intraclass correlation of outcome within user
import statsmodels.formula.api as smf
# Mixed effects model to estimate ICC
model = smf.mixedlm("outcome ~ 1", data, groups="user_id")
result = model.fit()
var_between = result.cov_re.iloc[0,0] # User variance
var_within = result.scale # Residual variance
ICC = var_between / (var_between + var_within)
# If m=5 sessions/user, ICC=0.3
DEFF = 1 + (5-1) * 0.3 # = 2.2
n_users = base_n * DEFF # 2.2x more users needed
Answer:
# Dunnett's test is more powerful than Bonferroni
from scipy import stats
# Bonferroni: α_adj = 0.05/10 = 0.005
# Requires ~1.5x sample size vs single comparison
# Dunnett's is ~10-20% more efficient than Bonferroni
# With 10 variants + 1 control
# For Bonferroni-adjusted power of 0.8:
n_per_arm = sample_size_multiple_comparisons(
effect_size=0.3,
n_comparisons=10
)
# Roughly 2x the single-comparison sample size
Answer: MDE should be driven by business value, not statistical convenience.
# Example: E-commerce checkout optimization
baseline_conversion = 0.03 # 3%
daily_visitors = 100_000
avg_order_value = 50
margin = 0.25
daily_revenue = daily_visitors * baseline_conversion * avg_order_value
# = $150,000/day
# 1% relative lift = 0.03% absolute = $1,500/day
# 5% relative lift = 0.15% absolute = $7,500/day
# If implementation costs $50K and margin is $7,500/day
# Break-even: 50,000 / 7,500 ≈ 7 days
# MDE should be at least 5% to be worthwhile
# But also consider confidence in estimate:
# Want effect > MDE with high probability
# So practical threshold might be 2-3x MDE