Skip to main content

13  Hypothesis testing and statistical power

An experiment often starts with a question about the population: does a new calibration method reduce average error, or is the observed improvement compatible with chance? A hypothesis test constructs a decision rule before observing the outcome. Its quality is judged by its behavior under both the hypothesized model and realistic alternatives.

13.1 Hypotheses, statistics and rejection rules

Let \(\Theta_0,\Theta_1\) be distinct subsets of a parameter space. The null hypothesis is \(H_0:\theta\in\Theta_0\), and the alternative is \(H_1:\theta\in\Theta_1\). A test statistic \(T(X)\) maps observed data into a number that measures discrepancy from the null in a specified direction. A rejection region \(R\) defines the test: reject \(H_0\) when \(T\in R\).

The size of the test is \(\sup_{\theta\in\Theta_0}P_\theta(T\in R)\). A level-\(\alpha\) test has size at most \(\alpha\). Its power function is

\[ \pi(\theta)=P_\theta(T\in R). \]

For \(\theta\) in the alternative, the type-II error probability is \(\beta(\theta)=1-\pi(\theta)\). Type-I error is rejection when the null holds; type-II error is nonrejection when a particular alternative holds. A low type-I error rate alone is insufficient: the rule that never rejects has size zero and power zero.

13.2 One- and two-sided tests

If iid normal data have known \(\sigma\), then for \(H_0:\mu=\mu_0\),

\[ Z=\frac{\sqrt n(\bar X-\mu_0)}{\sigma}\sim N(0,1) \]

under the null. Against \(\mu>\mu_0\), reject when \(Z>z_{1-\alpha}\); against \(\mu<\mu_0\), reject when \(Z<z_{\alpha}\). For \(\mu\ne\mu_0\), reject when \(|Z|>z_{1-\alpha/2}\). These regions allocate all or half of the allowed false-positive probability to each relevant tail.

The p-value is the null probability of a statistic at least as extreme as observed in the chosen test ordering. For observed \(z\),

\[ p_{\rm upper}=1-\Phi(z),\quad p_{\rm lower}=\Phi(z),\quad p_{\rm two}=2[1-\Phi(|z|)]. \]

More generally a valid p-value obeys \(P_\theta(p\le a)\le a\) for every null parameter and \(a\in[0,1]\). For a continuous statistic with strictly increasing null CDF \(F_0\) and upper-tail test, \(p=1-F_0(T)\) is uniform under the simple null by the probability integral transform. Thus rejecting at \(p\le\alpha\) gives exact size \(\alpha\). Discrete p-values are generally super-uniform rather than exactly uniform: attainable tail probabilities occur in steps.

The p-value supposes the null and other model assumptions are true. It is not \(P(H_0\mid X)\), nor the probability of getting the same outcome again, nor the size of an effect.

13.2.1 Example: a one-sample t-test

A monitoring team records \(n=20\) independent calibration errors, with \(\bar x=0.36\) and \(s=0.80\). Under a normal model, test \(H_0:\mu=0\) against \(H_1:\mu\ne0\) at \(\alpha=0.05\).

\[ t_{\rm obs}=\frac{0.36}{0.8/\sqrt{20}}\approx2.012. \]

The null reference is \(t_{19}\), not a standard normal. The two-sided p-value is \(2P(t_{19}\ge2.012)\).

from scipy import stats

n, m, s = 20, .36, .8
t = m/(s/n**.5)
p = 2*stats.t.sf(abs(t),df=n-1)
critical = stats.t.ppf(.975,n-1)
ci = (m-critical*s/n**.5, m+critical*s/n**.5)
print("t =",t,"p =",p,"95% CI =",ci)

At level .05 the test does not reject; the confidence interval includes zero. This does not establish that the mean is precisely zero. The interval communicates what positive and negative effects remain compatible with the data under the model.

13.3 Test–interval duality

In general, suppose for each candidate \(\theta_0\) we have a level-\(\alpha\) test of \(H_0:\theta=\theta_0\). Define \(C(X)\) to be the set of \(\theta_0\) whose tests do not reject. Then for the true parameter \(\theta\),

\[ P_\theta(\theta\in C(X))=1-P_\theta(\text{reject its null})\ge1-\alpha. \]

This proves that inverting tests yields a confidence set. In the normal-mean two-sided test the nonrejection inequality inverts to the interval in Chapter 12. A two-sided test and its matching interval are therefore two views of the same procedure.

13.4 An exact binomial test

Suppose a system is designed to succeed independently on 80% of trials. In a preplanned sample of 15 trials only eight succeed. Against the alternative \(p<0.8\), use \(S=\sum X_i\) with null distribution \(\operatorname{Binomial}(15,.8)\). Small counts are the extreme direction, so

\[ p_{\rm value}=P_{.8}(S\le8)=\sum_{k=0}^8\binom{15}{k}.8^k.2^{15-k}. \]

from scipy import stats

print(stats.binom.cdf(8,15,.8))
print(stats.binomtest(8,15,.8,alternative="less").pvalue)

This uses the exact finite-sample distribution rather than a normal approximation. For a two-sided discrete test different conventions may define extremeness differently, so specify the chosen method (SciPy’s exact two-sided binomial test uses probability ordering).

13.5 Statistical power and sample size

Consider the upper-tail known-variance normal-mean test. Under an actual mean \(\mu=\mu_0+\delta\),

\[ Z\sim N\left(\frac{\sqrt n\,\delta}{\sigma},1\right). \]

Consequently the power at shift \(\delta\) is

\[ \pi(\delta)=1-\Phi\left(z_{1-\alpha}-\frac{\sqrt n\,\delta}{\sigma}\right). \]

At \(\delta=0\) the power equals \(\alpha\); for a fixed positive shift it increases to one as \(n\) grows. To attain target power \(1-\beta\) at a specified \(\delta>0\), solve the inequality

\[ \frac{\sqrt n\,\delta}{\sigma}\ge z_{1-\alpha}+z_{1-\beta}. \]

Thus the planned sample size is

\[ n\ge\left[\frac{\sigma(z_{1-\alpha}+z_{1-\beta})}{\delta}\right]^2. \]

For a one-sided test at .05, 80% power and a meaningful standardized shift \(\delta/\sigma=.4\), the requirement is \(\lceil((1.645+.842)/.4)^2\rceil=39\). This assumes the design’s \(\sigma\) and effect size are correctly specified. A small p-value from a huge sample can correspond to a practically negligible effect; statistical significance is not practical importance.

Power curves for ten, twenty-five and one hundred observations all equal 0.05 at zero shift and rise faster for larger samples.
Figure 13.1: Rejection probability rises as the true mean moves toward the prespecified alternative, and it rises faster with a larger sample.

13.6 Why likelihood ratios produce powerful tests

For simple hypotheses \(H_0:f_0\) and \(H_1:f_1\), the Neyman–Pearson lemma states that a likelihood-ratio test is most powerful among tests of the same level. Let a possibly randomized test \(\phi(x)\in[0,1]\) specify the conditional probability of rejecting. Construct \(\phi^*\) to reject when \(f_1(x)>cf_0(x)\) and not reject when \(f_1(x)<cf_0(x)\), randomizing on the equality to obtain size \(\alpha\) if necessary.

For any competitor \(\phi\) of size at most \(\alpha\), pointwise

\[ (\phi^*(x)-\phi(x))(f_1(x)-cf_0(x))\ge0. \]

Indeed the first factor is nonnegative where \(\phi^*=1\), and nonpositive where \(\phi^*=0\), matching the sign of the second factor. Integrating gives

\[ E_1[\phi^*]-E_1[\phi]\ge c(E_0[\phi^*]-E_0[\phi])\ge0. \]

Thus no level-\(\alpha\) competitor has greater power at that simple alternative. General composite alternatives can require more complex compromises.

For nested composite parametric models define the likelihood-ratio statistic

\[ D=2\left[\sup_{\theta\in\Theta}\ell(\theta)-\sup_{\theta\in\Theta_0}\ell(\theta)\right]. \]

It is nonnegative because the unrestricted parameter set contains the null set. Wilks’ theorem states that under suitable regularity for an interior true parameter and smooth nested models, \(D\xrightarrow d\chi^2_r\), where \(r\) is the difference in parameter dimensions. This provides an asymptotic p-value. Boundary parameters, unidentified nuisance parameters, and sparse data can invalidate this approximation.

13.7 Permutation tests

Suppose two groups arise from identical distributions under the null, and their labels are exchangeable under the sampling design. A difference in means can be calibrated by shuffling group assignments while preserving group sizes. Conditional on the pooled values, each labeling is equally probable under the null. Enumerating all labelings therefore gives an exact discrete reference distribution.

When only \(B\) random permutations are used, a common valid Monte Carlo p-value includes the observed arrangement among candidates:

\[ p=\frac{1+\#\{b:|T_b|\ge|T_{\rm obs}|\}}{B+1}. \]

The procedure is justified by exchangeability of the observed statistic and random permutation statistics under the null (with uniform permutations including the identity); using \(\ge\) treats ties conservatively. It is not automatically valid under unequal variances when only equality of means is hypothesized, nor for dependent observations without an appropriate exchangeability structure.

flowchart TD
    A["Specify null, alternative, size"] --> B{"Reference distribution?"}
    B -->|Exact model| C["Exact test"]
    B -->|Regular large sample| D["Asymptotic test"]
    B -->|Exchangeable labels| E["Permutation test"]
    C --> F["Report effect, interval, p-value"]
    D --> F
    E --> F

13.8 Multiple comparisons

Testing \(m\) true nulls at .05 independently produces probability \(1-(.95)^m\) of at least one false rejection. Even without independence the union bound gives

\[ P(\text{any false rejection})\le\sum_{j\in I_0}P(\text{reject }H_{0j}). \]

Testing each at level \(\alpha/m\) therefore controls the familywise error rate at most \(\alpha\) (Bonferroni). False discovery rate is a different target: \(E[V/\max(R,1)]\), where \(V\) is false rejections and \(R\) total rejections. The Benjamini–Hochberg procedure sorts valid p-values and finds the largest \(k\) with \(p_{(k)}\le kq/m\), rejecting ranks \(1,\dots,k\); it controls FDR at most \(q\) under independent p-values and certain positive-dependence conditions. Decide the family and the error objective before looking for favorable results.

Repeated unplanned peeking, selecting a tail after seeing the sign, and trying many models until one is significant can change the actual error rate even if each individual p-value formula is correct.

13.9 Practice problems

Work in your browser with Google Colab, or download the notebooks for Jupyter.

Practice notebook

Open in Colab Download .ipynb

Worked solutions

Open in Colab Download .ipynb

13.9.1 Exercise 1: Calibrate a rejection rule

For \(Z\sim N(0,1)\) under \(H_0\), an investigator proposes rejection when \(|Z|>1.645\). Compute its actual size. Find the correct cutoff for a two-sided level-.05 test.

The size is \(2[1-\Phi(1.645)]\approx.10\). A two-sided .05 test places .025 in each tail, so reject when \(|Z|>1.960\).

13.9.2 Exercise 2: Plan power

Suppose standard deviation is four, and you want 90% power to detect a true increase of two using a one-sided test at .01. Express the sample size and approximate it.

Use \(n\ge[4(z_{.99}+z_{.9})/2]^2=[2(2.3263+1.2816)]^2\approx52.07\). Rounded up, \(n=53\).

13.9.3 Exercise 3: Connect errors to decisions

A level-.05 test of a simple null has power .82 at an alternative of interest. What are its type-I and type-II probabilities? Does nonrejection demonstrate the null?

The type-I probability is at most .05, with equality if the test has exact size. At the selected alternative, type-II probability is \(1-.82=.18\). Nonrejection is compatible with either hypothesis; even when that alternative is true, about 18% of repetitions fail to reject.

13.9.4 Exercise 4: Verify a power curve (Python)

For known standard deviation one and sample size 25, simulate 20,000 experiments at mean shifts \(0,.1,.2,.4,.6\). Use an upper-tail .05 z-test. Compare observed rejection rates with the exact formula, and plot both.

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

rng = np.random.default_rng(1301)
n = 25
c = stats.norm.ppf(.95)
delta = np.array([0,.1,.2,.4,.6])
emp = []
for d in delta:
    x = rng.normal(d,1,(20_000,n))
    emp.append(np.mean(np.sqrt(n)*x.mean(axis=1)>c))
theory = stats.norm.sf(c-np.sqrt(n)*delta)
print(np.column_stack([delta,emp,theory]))
plt.plot(delta,theory,label="Exact")
plt.scatter(delta,emp,label="Simulation")
plt.xlabel("True mean shift")
plt.ylabel("Rejection probability")
plt.legend()
plt.show()
assert np.max(abs(np.array(emp)-theory)) < .02

13.9.5 Exercise 5: Implement a permutation test (Python)

Generate two independent samples of 12 observations from standard normal distributions; add 0.7 to the second group. Compute a two-sided permutation p-value for the observed mean difference using 4,999 shuffled assignments. Report the effect estimate alongside its p-value.

import numpy as np

rng = np.random.default_rng(1302)
a, b = rng.normal(0,1,12),rng.normal(.7,1,12)
pooled = np.r_[a,b]
obs = b.mean()-a.mean()
extreme = 0
B = 4999
for _ in range(B):
    q = rng.permutation(pooled)
    t = q[12:].mean()-q[:12].mean()
    extreme += abs(t)>=abs(obs)-1e-12
p = (1+extreme)/(B+1)
print("Mean difference:",obs,"Permutation p:",p)

Under identical iid group distributions the labels are exchangeable, providing the null calibration. The simulation generates a particular random sample; the observed p-value need not be small even when the true difference is nonzero.

13.9.6 Exercise 6: Simulate the multiple-testing problem (Python)

Generate 40,000 sets of 30 independent uniform null p-values. Estimate the probability of at least one rejection when every test uses .05, then after Bonferroni correction. Compare to exact independent-model probabilities.

import numpy as np

rng = np.random.default_rng(1303)
m, alpha = 30, .05
p = rng.random((40_000,m))
for a in [alpha,alpha/m]:
    print("Individual cutoff:",a,
          "simulated familywise error:",np.any(p<=a,axis=1).mean(),
          "exact:",1-(1-a)**m)

The unadjusted familywise error is \(1-.95^{30}\approx.785\). Bonferroni gives approximately .049, at most .05. The correction controls the chance of any false rejection even without independence, via the union bound.