Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Hypothesis Testing

KTH JupyterHub Open In Colab Binder

Hypothesis testing is a statistical procedure used to determine if a sample data set provides sufficient evidence to reject a stated null hypothesis (H0H_0) in favor of an alternative hypothesis (H1H_1). This method is fundamental in science for drawing inferences about populations based on sample data. It allows researchers to judge whether their observations could plausibly have arisen by chance alone, if there were no genuine effect.

Statistical hypothesis test

Null Hypothesis (H0H_0) and Alternative Hypothesis (H1H_1)

In hypothesis testing, we begin by stating two competing hypotheses about a population or a set of populations:

The purpose of hypothesis testing is to assess whether the data provides enough evidence to reject H0H_0 in favor of H1H_1. This process involves comparing the observed data in a sample to what we would expect under H0H_0.

Test Statistics

A test statistic is a value calculated from sample data that allows us to make a decision about the hypotheses. One commonly used test statistic is the difference in means between two samples. For example, if we want to compare the average effect of a treatment versus a placebo, we calculate the difference in the sample means for the two groups. The test statistic helps determine how far the observed data deviates from what we would expect under H0H_0, which typically assumes that there is no difference in means between the groups.

Sampling Distribution under the Null Hypothesis

The sampling distribution under the null hypothesis is the distribution of the test statistic assuming that H0H_0 is true. This distribution helps us understand the range of possible values the test statistic can take if the null hypothesis is correct. By comparing the observed test statistic to this distribution, we can determine how likely it is to observe such a value by random chance alone. This comparison is essential for calculating the pp value.

pp value

The pp value represents the probability of obtaining the observed data, or something more extreme, if the null hypothesis were true. It is used as a measure of evidence against H0H_0:

Significance Level (α\alpha)

The significance level (denoted as α\alpha) is a predetermined threshold that determines whether the pp value is considered small enough to reject the null hypothesis. A common choice for α\alpha is 0.05, which means we are willing to accept a 5% chance of incorrectly rejecting H0H_0 (Type I error):

False Positives and False Negatives

In hypothesis testing, two types of errors can occur:

The two types of error trade off against each other: lowering α\alpha reduces the risk of false positives, but makes it harder to detect real effects, and so increases the risk of false negatives.

Limitations & Misinterpretations

While hypothesis testing is powerful, it has its limitations and can be easily misinterpreted:

Assessing Significance Using Permutation Testing

We can use permutation testing to evaluate significance. The null hypothesis is that there is no relationship between the measured values and the labels attached to them, such as between a measurement and the group of the sample it was made on, or between the dependent variable yy and the independent variable x\mathbf{x} of a regression. If so, any random pairing of values and labels is as likely as the observed one. Shuffling the labels many times, and recalculating the test statistic each time, therefore gives us the null distribution of the test statistic, to which we compare the observed value to compute a pp value.

Why Permutation Testing?

Permutation testing is non-parametric, meaning it doesn’t assume a specific distribution of the residuals or the coefficients. This makes it a powerful and flexible method, especially in cases where the assumptions of parametric tests (e.g., normality) might not hold. Further, we here use it as a pedagogic tool, to understand how frequentist hypothesis testing actually works.

Step-by-step Procedure

  1. Calculate the test statistic on the original data, e.g. the difference in means between two groups, or the loss of a model fitted to the data.

  2. Permute the labels (shuffle the group labels, or shuffle yy while keeping x\mathbf{x} unchanged) and recalculate the test statistic on the permuted data, refitting the model if there is one.

  3. Repeat the permutation process many times to build a distribution of the test statistic under the null hypothesis.

  4. Calculate the pp value as the fraction of permuted test statistics that are at least as extreme as the observed one.

Permutation Test for Comparing the Means of Two Samples

We first test whether two samples have different means. Here we shuffle the group labels, and use the absolute difference between the two sample means as test statistic. As a large difference in either direction counts as extreme, this is a two-sided test (see below).

Notebook Cell
<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>
Observed difference in means: 1.2441
p value from permutation test: 0.0180

Permutation Test for Model Significance

Next, we test whether a linear regression model explains any of the variation in yy, using the model’s SSE as test statistic. Here a small loss is extreme, so the pp value is the fraction of permuted losses that are at most as large as the observed loss.

<Figure size 640x480 with 1 Axes>
Observed loss: 49.7958
p value from permutation test: 0.0740

t-tests

When the population from which your samples are drawn is normally distributed, a t-test can be used to evaluate whether there is a significant difference between the means of two independent groups. Under these conditions the difference in sample means is normally distributed, and dividing it by its estimated standard error yields a t-statistic, which follows a t-distribution. It is the extra uncertainty from estimating the standard deviation from the data, rather than knowing it, that gives the t-distribution its heavier tails. This allows us to calculate the probability (pp value) of observing a difference as large as (or larger than) the one obtained, assuming the null hypothesis is true.

Below we use SciPy’s ttest_ind, which by default performs Student’s tt-test. Student’s test also assumes that the two groups have the same variance; with the argument equal_var=False, ttest_ind instead performs Welch’s tt-test, which does not.

p value: 0.0168

When the data really are normally distributed, the tt-test is the most powerful test of a difference in means, i.e. the one most likely to detect a real difference. A permutation test on the same data is usually almost as powerful; for our two samples, the tt-test gives p=0.017p = 0.017 and the permutation test p=0.018p = 0.018. The advantage of the tt-test shows up for very small samples. A permutation test can only produce as many distinct pp values as there are distinct ways to permute the labels, e.g. (63)=20\binom{6}{3} = 20 for three against three samples, so its smallest possible two-sided pp value is then 2/20=0.12/20 = 0.1, whereas a tt-test can produce arbitrarily small pp values. In return, the tt-test’s pp values are only accurate if the normality assumption holds, which is hard to check in small samples, while the permutation test makes no such assumption.

One- vs Two-sided tests

A one-sided test is used when we want to determine if there is a difference in a specific direction (e.g., whether one group mean is greater than the other). In contrast, a two-sided test checks if there is any difference between the groups, regardless of direction (i.e., whether one mean is greater or less than the other). A two-sided test is more conservative because it tests for deviations in both directions, while a one-sided test focuses on a predetermined outcome.

Below, we repeat the permutation test on the same two samples as before, but now test one-sidedly whether sample2 has a larger mean than sample1. The test statistic is Δ=xˉ2−xˉ1\Delta = \bar{x}_2 - \bar{x}_1, the mean of sample2 minus the mean of sample1, without taking absolute values:

<Figure size 640x480 with 1 Axes>
Loading...
Loading...
Loading...
Loading...

The one-sided test of H0:Δ≤0H_0: \Delta \le 0 against H1:Δ>0H_1: \Delta > 0 uses only the right tail of the null distribution: its pp value is the fraction of permutations where perm_sample2 - perm_sample1 is at least as large as the observed difference. As the observed difference lies in the predicted direction, this pp value (0.009) is about half of the two-sided one (0.022), which counts extreme differences in both tails. Had we instead predicted that sample2 has the smaller mean, i.e. tested H0:Δ≥0H_0: \Delta \ge 0, the pp value would have been close to 1. The direction of a one-sided test must therefore be decided before looking at the data; choosing it afterwards halves the pp value without justification.

When testing whether a drug is effective, the research question is directional, which can motivate a one-sided test. Note, however, that regulators of clinical trials usually require either a two-sided test at α=0.05\alpha = 0.05 or a one-sided test at α=0.025\alpha = 0.025, which amounts to the same evidence threshold, partly because a harmful effect of the drug is also important to detect. In differential gene expression analysis, you want to find both up- and downregulated genes, making a two-sided test the natural choice.

Power and sample size

The power of a test is the probability that it rejects H0H_0 when there really is a difference, i.e. the probability of avoiding a type II error. Power is a property of the experiment rather than of the data: it depends on how large the true difference is compared to the variation within the groups, on the number of samples per group, and on the significance level α\alpha.

Before an experiment we cannot know the true difference, but we can decide on the smallest difference that would matter, and take an estimate of the variation from earlier data or a pilot experiment. With those two numbers we can run the experiment many times on the computer, analyze each simulated experiment just as we plan to analyze the real one, and count how often we reach p<αp < \alpha. That fraction is the power.

To see the idea, we simulate 10,000 experiments with five samples per group, once in a world where H0H_0 is true and once in a world where the true means differ by one standard deviation (SD), and record the difference in means of each experiment:

<Figure size 640x480 with 1 Axes>
Fraction of experiments with a significant difference: 0.34

The grey histogram is the sampling distribution of the difference in means under H0H_0, and the dashed lines mark the differences that are extreme enough to give p<0.05p < 0.05. The orange histogram shows what we would observe if the true difference were one SD. Only the experiments beyond the dashed lines give a significant result; with five samples per group that is about a third of them, so two experiments out of three would miss the difference.

To plan an experiment, we repeat the simulation for different numbers of samples and pick the smallest number that reaches the power we want, often 80%. Here each simulated experiment is analyzed with the tt-test:

Difference 0.5 SD: 80% power with 66 samples per group
Difference 1.0 SD: 80% power with 18 samples per group
Difference 2.0 SD: 80% power with 6 samples per group
<Figure size 640x480 with 1 Axes>

A difference of one SD needs about 18 samples per group, half that difference needs nearly four times as many, and twice the difference only 6. Nothing in this recipe requires normal distributions: the simulated samples can just as well be drawn from pilot measurements, and each simulated experiment can be analyzed with a permutation test, at the cost of more computation.

The analytical sample-size formula

For a comparison of two means, the quantities that determine power are linked by a formula, which is what power calculators use. The difference in sample means has standard error σ2/n\sigma\sqrt{2/n}, where σ\sigma is the standard deviation within the groups and nn the number of samples per group. In a two-sided test at level α\alpha, the observed difference must exceed z1−α/2 σ2/nz_{1-\alpha/2}\,\sigma\sqrt{2/n}, where zqz_q is the qq quantile of the standard normal distribution; these are the dashed lines in the histogram above. If the true difference is δ\delta, the observed difference exceeds that threshold with probability 1−β1-\beta, the power, when δ/(σ2/n)=z1−α/2+z1−β\delta/(\sigma\sqrt{2/n}) = z_{1-\alpha/2} + z_{1-\beta}. Solving for nn gives

n≈2 (z1−α/2+z1−β)2d2,d=δσ,n \approx \frac{2\,(z_{1-\alpha/2} + z_{1-\beta})^2}{d^2}, \qquad d = \frac{\delta}{\sigma},

where dd is the difference measured in standard deviations, the standardized effect size. With α=0.05\alpha = 0.05 (z0.975=1.96z_{0.975} = 1.96) and 80% power (z0.8=0.84z_{0.8} = 0.84), a difference of one SD gives n≈2⋅2.82≈16n \approx 2 \cdot 2.8^2 \approx 16 samples per group, and α=0.001\alpha = 0.001 (z0.9995=3.29z_{0.9995} = 3.29) gives about 34. The formula is slightly optimistic compared to the simulation, as it treats σ\sigma as known, whereas the tt-test estimates it from the data. It also shows directly why halving the difference quadruples the number of samples needed.

Two consequences matter for genomics. With three samples per group, the power to detect a difference of one SD is only about 16%, and even a difference of two SD is missed in more than half of the experiments. And when thousands of genes are tested, each gene has to pass a much stricter threshold than α=0.05\alpha = 0.05 (see multiple hypothesis testing); at α=0.001\alpha = 0.001, a difference of one SD needs about 37 samples per group. As each gene has its own difference and variation, an experiment has high power for some genes and low power for others, which is what the next chapter shows on real data.

Overview of the workflow in frequentist testing procedures

We are interested in a parameter of a population, such as its mean μ, but can only observe a sample, from which we calculate a statistic, such as the sample mean X̄. The statistic differs from the parameter because of sampling errors, as the sample is only a subset of the population, and because of measurement errors. A statistical model of these errors, such as the null distributions above, is what allows us to use the statistic to draw conclusions about the population parameter.

Volcano Plots and Their Interpretation

A volcano plot is a type of scatter plot commonly used in genomics, proteomics, and other fields of biology to display the results of differential expression or differential abundance analysis. The plot provides a clear visual summary of large datasets, making it easier to identify statistically significant changes between two experimental conditions.

On a volcano plot, the x-axis shows the fold change between the two groups, usually as a log⁡2\log_2 value, and the y-axis shows the statistical significance of the change, usually as −log⁡10-\log_{10} of the pp value. Features (e.g., genes or proteins) far to the left or right have large fold changes, and features high up have small pp values. The most interesting features, with both a large effect size and high statistical confidence, are therefore found in the upper left and upper right corners. The name “volcano plot” comes from the characteristic shape of the point cloud, which resembles an erupting volcano.

Example Script for Generating a Volcano Plot

The script below simulates log2 expression values for 1,000 genes in two groups of five samples, and draws a volcano plot. Only about 10% of the genes are differentially expressed, with a random offset between the groups.

<Figure size 1000x600 with 1 Axes>
Genes without an effect: 894, of which 45 have p < 0.05 and 2 pass both thresholds

The genes that pass both the pp value threshold (red line) and the threshold of ±1\pm 1 on the log2 fold change (blue lines) are shown in orange. Of the 894 genes without an effect, 45 nevertheless reach p<0.05p < 0.05; they make up most of the grey points above the red line, and two of them even pass both thresholds. Such false positives are expected when testing many genes, as we have not corrected for multiple testing, something we will discuss in the chapter on multiple hypothesis corrections.

What you should know after reading this chapter

You should be able to:

  1. Define the null hypothesis H0H_0, the alternative hypothesis H1H_1, a test statistic and its sampling distribution under H0H_0, and identify them in a comparison of two groups such as treated and placebo patients.

  2. Define the pp value and the significance level α\alpha, and interpret a pp value correctly: it is neither the probability that H0H_0 is true nor a measure of effect size or practical significance.

  3. Define false positives (type I errors) and false negatives (type II errors), and explain how the choice of α\alpha trades one against the other.

  4. Describe the steps of a permutation test, both for a difference in means and for the SSE of a regression model. Calculate the permutation pp value as the fraction of permuted test statistics that are at least as extreme as the observed one.

  5. Explain how a tt-statistic is formed from the difference in means and its estimated standard error. Contrast the tt-test with a permutation test: assuming normality gives more power in small samples, but misleading pp values when the assumption fails.

  6. Contrast one-sided and two-sided tests, identify which tail or tails of the null distribution each one uses, and argue which one fits a given study, such as a drug trial or a differential expression analysis.

  7. Interpret a volcano plot, with the log⁡2\log_2 fold change on the x-axis and −log⁡10p-\log_{10} p on the y-axis, and identify the features that have both a large effect size and a small pp value.

  8. Define the power of a test, name what it depends on, and describe how simulation can estimate the power of a planned experiment, or the number of samples it needs, from an assumed difference and an estimate of the variation.