Sample Size & Power Analysis

Master the science of experiment design and sample size determination

1. Power Analysis Fundamentals

What is Statistical Power?

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).

Power Definition

\[\text{Power} = P(\text{Reject } H_0 | H_1 \text{ is true})\]

\[\text{Power} = 1 - \beta\]

  • β = Type II error rate (false negative)
  • Typical power target: 80% (β = 0.20)
  • High-stakes decisions: 90% (β = 0.10)
Error Types
H₀ True H₀ False
Reject H₀ Type I (α) Correct (Power)
Fail to Reject Correct (1-α) Type II (β)

Why Power Analysis Matters

Underpowered Studies
  • Waste resources on inconclusive results
  • Miss real effects (false negatives)
  • Overestimate effect sizes when significant
  • Lead to publication bias
Overpowered Studies
  • Waste resources on unnecessary samples
  • Detect trivially small effects
  • Ethical concerns (excess participants)
  • Delayed decision-making
Right-Sized Studies
  • Efficient use of resources
  • High probability of detecting MDE
  • Reliable effect size estimates
  • Timely business decisions

2. The Four Parameters

The Power Analysis Quartet

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.

Effect Size (Cohen's d)

\[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}}\]

Cohen's Conventions:
Small: d = 0.2 | Medium: d = 0.5 | Large: d = 0.8
Sample Size Formula (Two-sample t-test)

\[n = 2 \cdot \left(\frac{(z_{1-\alpha/2} + z_{1-\beta})}{d}\right)^2\]

  • \(z_{1-\alpha/2}\) = z-value for significance (e.g., 1.96 for α=0.05)
  • \(z_{1-\beta}\) = z-value for power (e.g., 0.84 for 80%)
  • d = effect size (Cohen's d)

Effect Sizes for Different Tests

Proportions (Cohen's h)

\[h = 2 \cdot (\arcsin\sqrt{p_1} - \arcsin\sqrt{p_2})\]

Used for comparing two proportions in A/B tests

Correlation (r)

Cohen's conventions:

  • Small: r = 0.1
  • Medium: r = 0.3
  • Large: r = 0.5
ANOVA (Cohen's f)

\[f = \sqrt{\frac{\eta^2}{1 - \eta^2}}\]

Small: 0.1 | Medium: 0.25 | Large: 0.4

Interview Insight: MDE vs Effect Size

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."

Interactive Power Analysis

Parameters
Calculated Power: --

3. Sample Size Calculations

Proportions Test (A/B Testing)

Sample Size for Two Proportions

\[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

Using statsmodels

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()

Quick Reference Table

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

4. Practical Considerations

Best Practices
  • Use historical data to estimate baseline rates and variance
  • Account for dropout/attrition by inflating sample size 10-20%
  • Consider multiple comparisons and adjust α accordingly
  • Plan for interim analyses with appropriate corrections
  • Document assumptions for stakeholder alignment
Common Pitfalls
  • Post-hoc power analysis - meaningless after data collected
  • Ignoring clustering in hierarchical data
  • Using Cohen's conventions blindly - context matters!
  • Assuming equal variances when they differ significantly
  • Forgetting one-sided vs two-sided test implications

Adjusting for Real-World Factors

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")
Design Effect for Clustered Data

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.

5. Advanced Topics

Sequential Analysis and Early Stopping

# 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}")

Bayesian Sample Size Determination

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")

Power for Multiple Comparisons

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")
Interview Insight: Power vs. Precision

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.

6. Interview Questions

Answer:

  1. Define parameters:
    • Baseline: p₁ = 0.05 (5%)
    • Treatment: p₂ = 0.05 × 1.02 = 0.051 (2% relative lift)
    • Absolute lift: 0.001 (0.1 percentage points)
  2. Calculate sample size:
    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!
  3. Calculate duration:
    • Need ~770K per group = 1.54M total
    • At 10K/day: 154 days (~5 months)
  4. Practical recommendation: A 2% relative lift on 5% baseline is tiny (0.1pp). Consider:
    • Is this effect size worth detecting?
    • Can we increase traffic or test multiple variants?
    • Use CUPED or other variance reduction

Answer:

Post-hoc power analysis is calculating power after an experiment using the observed effect size. It's problematic because:

  1. Mathematically redundant: Observed power is a 1-to-1 function of the p-value. A p=0.05 always gives ~50% post-hoc power, p=0.01 gives ~80%. It adds no new information.
  2. Circular reasoning: "We didn't find significance because we were underpowered" - but the observed effect includes sampling error, so you're using noisy data to explain noisy data.
  3. Misleading conclusions: Non-significant result with "low power" doesn't mean effect exists; it could be no effect at all.

What to do instead:

  • Report confidence intervals (shows precision)
  • Compare observed effect to practical significance thresholds
  • Do sensitivity analysis: "We had 80% power to detect d=0.5"

Answer: This is a clustering problem. Sessions within users are correlated.

  1. Calculate Design Effect:
    DEFF = 1 + (m - 1) × ICC
    # m = average sessions per user
    # ICC = intraclass correlation of outcome within user
  2. Estimate ICC from historical data:
    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)
  3. Inflate sample size:
    # 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
  4. Alternative: Aggregate to user level (average outcome per user) and use user-level power analysis.

Answer:

  1. Clarify objectives:
    • Test each variant vs control? (10 comparisons)
    • Find the best variant? (selection problem)
    • Any variant better than control? (union-intersection)
  2. For multiple comparisons vs control:
    # 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
  3. Practical recommendation:
    • Consider multi-armed bandit for exploration
    • Run sequential tests: screen with relaxed α, confirm winners
    • Control allocation: give control more traffic (√k rule)
  4. Sample size per arm:
    # 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.

  1. Cost-benefit analysis:
    # 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
  2. Consider implementation cost:
    • Engineering effort to implement change
    • Ongoing maintenance costs
    • Opportunity cost of test duration
  3. Set MDE at break-even point:
    # 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
  4. Rule of thumb: If detecting the MDE requires impractical sample sizes, either:
    • Accept that small effects aren't worth detecting
    • Increase traffic/test duration
    • Use variance reduction techniques
Key Takeaways
  • Power analysis is essential - do it before, not after
  • Four parameters are linked - n, effect size, α, power
  • MDE should be business-driven - not arbitrary conventions
  • Adjust for real-world factors - attrition, clustering, non-compliance
  • Multiple comparisons inflate n - plan for corrections
  • Precision matters too - CI width, not just significance