Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

More hypothesis tests

ProblemTest whether a sample is normal; whether groups have equal variances; whether groups or paired measurements differ, without assuming normality; compute exact p-values for small tables and counts; test any statistic by permutation; and control errors when many tests are made at once
Devised bySamuel Shapiro and Martin Wilk (1965), Patrick Royston (1992, 1995); Theodore Anderson and Donald Darling (1952); Ralph D’Agostino (1970) and Egon Pearson (1973); Carlos Jarque and Anil Bera (1980); Howard Levene (1960), Morton Brown and Alan Forsythe (1974); Maurice Bartlett (1937); Michael Fligner and Timothy Killeen (1976); William Kruskal and Allen Wallis (1952); Milton Friedman (1937); Frank Wilcoxon (1945); Ronald Fisher (1922, 1935); Sture Holm (1979); Yoav Benjamini and Yosef Hochberg (1995), Benjamini and Daniel Yekutieli (2001)
AccuracyStatistics and p-values agree with scipy.stats to or better, except Shapiro-Wilk at
Cost for the rank tests; the exact Wilcoxon distribution in ; Fisher’s and the binomial test in ; a permutation test costs one evaluation of the statistic per split
Read firstHypothesis tests, Probability distributions
APInormality (shapiro, anderson_normal, jarque_bera, normaltest, skewtest, kurtosistest), comparisons (levene, bartlett, fligner, kruskal, friedman, wilcoxon, fisher_exact, binomtest, permutation_test, adjust_p_values)

Overview

The hypothesis tests entry covered the classical tests of means and of goodness of fit. This one adds the tests that are needed around them:

  • Normality tests check the assumption behind t-tests and ANOVA.
  • Tests of equal variances check the other assumption of pooled t-tests and ANOVA.
  • Rank tests compare groups (Kruskal-Wallis), repeated measurements (Friedman) and paired differences (Wilcoxon) without assuming normality.
  • Exact tests give p-values without large-sample approximations: Fisher’s for 2 × 2 tables, and the binomial test.
  • Permutation tests give an exact p-value for any statistic, by recomputing it under every relabelling of the data.
  • Multiple-comparison adjustments control the error rate when many hypotheses are tested together.

Each follows the corresponding function of scipy.stats.

Where it is used

Further tests for the situations that the basic ones do not cover.

  • Checking assumptions. Tests of normality and equal variances decide whether a t-test or ANOVA is appropriate.
  • Comparing several groups. ANOVA and its non-parametric counterparts compare the output of several machines, materials or treatments.
  • Paired and ordinal data. Before-and-after measurements on the same units and rating-scale data.

History

Samuel Shapiro and Martin Wilk (1965) built their test from the regression of the ordered sample on the expected normal order statistics. Patrick Royston (1992, 1995) extended it to large samples with the approximations used by every implementation today. Theodore Anderson and Donald Darling (1952) weighted the distance between the empirical and the normal distribution function towards the tails. Ralph D’Agostino and Egon Pearson combined tests of skewness and kurtosis into one statistic, and Carlos Jarque and Anil Bera (1980) derived a simpler version for econometrics.

Maurice Bartlett’s test of equal variances (1937) is sensitive to non-normality. Howard Levene (1960), Morton Brown and Alan Forsythe (1974), and Michael Fligner and Timothy Killeen (1976) made robust alternatives. Rank tests began with Milton Friedman (1937) and Frank Wilcoxon (1945). William Kruskal and Allen Wallis (1952) extended Wilcoxon’s rank-sum test to many groups. Ronald Fisher introduced both the exact test for 2 × 2 tables and the logic of permutation tests in his “lady tasting tea” (1935). Carlo Bonferroni’s inequality (1936) gave the first protection against multiple comparisons. Sture Holm (1979) sharpened it. Yoav Benjamini and Yosef Hochberg (1995) changed the goal from avoiding any false rejection to controlling the false discovery rate, which suits studies of thousands of hypotheses.

The idea

Tests of normality

Each test measures a different departure from the normal distribution:

  • Shapiro-Wilk compares the ordered sample with the expected order statistics of a normal sample. Its statistic is the squared correlation of a normal probability plot. Near 1 means normal. Royston’s algorithm approximates the coefficients and transforms to approximate normality to give the p-value.
  • Anderson-Darling measures the squared distance between the empirical distribution function and the fitted normal, with weight , which emphasises the tails: . It is compared with Stephens’s tabulated critical values.
  • D’Agostino-Pearson transforms the sample skewness and kurtosis each to an approximately standard normal , and adds their squares: .
  • Jarque-Bera uses the same two moments without the transformations, , which is accurate only for large samples.

No test is best against every alternative. A simulation of 2000 samples of 50 shows how often each rejects at the 5% level:

Table 10.7. Power of the normality tests at the 5% level, n = 50.

samples of 50 fromShapiro-WilkAnderson-DarlingD’Agostino-PearsonJarque-Bera
normal (the null hypothesis)5.7%5.0%6.0%4.0%
Student t, 5 degrees of freedom (heavy tails)35.6%30.8%40.5%39.6%
gamma, shape 4 (skewed)69.3%57.9%53.5%48.3%
uniform (light tails)74.2%57.0%79.7%0.0%

Shapiro-Wilk is the best general choice. The moment tests do well against heavy tails, but Jarque-Bera never detects the light-tailed uniform distribution at this size: its kurtosis is below normal, and the approximation is poor for .

Equal variances

Bartlett’s test compares the pooled variance with the individual ones through their logarithms. It is optimal for normal data and misleading otherwise, because heavy tails mimic unequal variances. Levene’s test with Brown and Forsythe’s median centring runs a one-way ANOVA on the absolute deviations from each group’s median. The Fligner-Killeen test replaces those deviations by normal scores of their ranks. Both are robust to non-normality.

Rank tests

Replacing observations by their ranks makes a test’s null distribution independent of the data’s distribution:

  • Kruskal-Wallis compares the mean ranks of groups, , corrected for ties, approximately . It is the rank version of one-way ANOVA.
  • Friedman’s test ranks treatments within each of blocks (subjects measured repeatedly), and compares the treatments’ rank sums.
  • The Wilcoxon signed-rank test ranks the absolute paired differences and sums the ranks of the positive ones, . Under the null hypothesis of a distribution symmetric about zero, each rank is equally likely to carry either sign. The exact distribution of is that of the sum of a random subset of , which dynamic programming counts in . With ties, the library enumerates all sign changes for and otherwise uses the normal approximation, as SciPy does.

Exact tests

With both margins of a 2 × 2 table fixed, the top-left count follows a hypergeometric distribution. Fisher’s exact test sums the probabilities of all tables at least as extreme as the observed one. For the two-sided test, these are the tables no more probable than it. The binomial test does the same for successes in trials. Both are exact for any sample size, so they replace the tests when expected counts are small.

Permutation tests

If the two samples come from the same distribution, every way of dividing the pooled observations into groups of the original sizes is equally likely. A permutation test computes any statistic, such as the difference of means or medians or a ratio of variances, for each division. The p-value is the fraction at least as extreme as the observed one. With up to n_resamples divisions the test enumerates them all and is exact. Otherwise it samples random divisions and counts the observed one among them, so that the p-value is never zero.

Many tests at once

Testing 1000 true null hypotheses at 5% rejects about 50 of them. Two kinds of protection exist:

  • The family-wise error rate, the probability of any false rejection. Bonferroni multiplies each p-value by . Holm’s step-down version multiplies the -th smallest by and is uniformly more powerful.
  • The false discovery rate, the expected share of false rejections among all rejections. Benjamini-Hochberg multiplies the -th smallest p-value by (then enforces monotonicity). Benjamini-Yekutieli adds a factor that makes it valid under any dependence.

With 1000 t-tests, of which 100 have a real effect:

Table 10.8. Rejections at 5% among 1000 tests, 100 of them with a real effect.

adjustmentrejectionstrue effects found (of 100)false rejections (of 900 nulls)share of rejections that are false
none121774436.4%
Bonferroni32133.3%
Holm32133.3%
Benjamini-Hochberg2018210.0%
Benjamini-Yekutieli0000.0%

Without adjustment a third of the discoveries are false. The family-wise methods find almost nothing. Benjamini-Hochberg finds many true effects while keeping the share of false ones near the target.

Algorithm

Shapiro-Wilk (Royston’s AS R94), for :

  1. Compute , the coefficients and by polynomials in , and the others proportional to .
  2. Compute .
  3. For transform , otherwise , by fitted mean and standard deviation polynomials. The p-value is a normal upper tail.

Exact Wilcoxon: counts of subsets of summing to , by adding the ranks one at a time (c[s] += c[s − k]); the p-value is a sum of .

Permutation test: enumerate the subsets in lexicographic order, or shuffle by Fisher-Yates.

Benjamini-Hochberg: sort the p-values, form , take running minima from the largest down, and cap at 1.

Implementation

/// The Shapiro-Wilk test (SciPy's `shapiro`): `W` measures how well the ordered sample matches
/// the expected normal order statistics, `W = (Σ aᵢ x₍ᵢ₎)² / Σ (xᵢ − x̄)²`, with Royston's
/// approximations (AS R94) to the coefficients `aᵢ` and to the null distribution of `ln(1 − W)`.
/// Valid for 3 ≤ n ≤ 5000.
pub fn shapiro(x: &[f64]) -> Result<TestResult, ErrorsJSL> {
    let n = x.len();
    if !(3..=5000).contains(&n) || x.iter().any(|v| !v.is_finite()) {
        return Err(ErrorsJSL::InvalidInputRange("Shapiro-Wilk needs 3 to 5000 finite values"));
    }
    let xs = sorted(x);
    let nn2 = n / 2;
    let an = n as f64;
    // Coefficients for the lower half; a[i] pairs x₍ₙ₋ᵢ₎ with x₍ᵢ₎.
    let mut a = vec![0.0; nn2];
    if n == 3 {
        a[0] = 0.5f64.sqrt();
    } else {
        let an25 = an + 0.25;
        let m: Vec<f64> = (1..=nn2).map(|i| normal_quantile((i as f64 - 0.375) / an25, 0.0, 1.0)).collect();
        let summ2 = 2.0 * m.iter().map(|v| v * v).sum::<f64>();
        let ssumm2 = summ2.sqrt();
        let rsn = 1.0 / an.sqrt();
        let c1 = [0.0, 0.221157, -0.147981, -2.07119, 4.434685, -2.706056];
        let c2 = [0.0, 0.042981, -0.293762, -1.752461, 5.682633, -3.582633];
        let a1 = poly(&c1, rsn) - m[0] / ssumm2;
        let (i1, fac) = if n > 5 {
            let a2 = -m[1] / ssumm2 + poly(&c2, rsn);
            a[1] = a2;
            (2, ((summ2 - 2.0 * m[0] * m[0] - 2.0 * m[1] * m[1]) / (1.0 - 2.0 * a1 * a1 - 2.0 * a2 * a2)).sqrt())
        } else {
            (1, ((summ2 - 2.0 * m[0] * m[0]) / (1.0 - 2.0 * a1 * a1)).sqrt())
        };
        a[0] = a1;
        for i in i1..nn2 {
            a[i] = -m[i] / fac;
        }
    }
    let mean = xs.iter().sum::<f64>() / an;
    let ssq: f64 = xs.iter().map(|v| (v - mean) * (v - mean)).sum();
    if ssq == 0.0 {
        return Err(ErrorsJSL::InvalidInputRange("all values are equal"));
    }
    let num: f64 = (0..nn2).map(|i| a[i] * (xs[n - 1 - i] - xs[i])).sum();
    let w = (num * num / ssq).min(1.0);
    // The p-value.
    let pw = if n == 3 {
        let pi6 = 6.0 / std::f64::consts::PI;
        let stqr = (0.75f64).sqrt().asin();
        (pi6 * (w.sqrt().asin() - stqr)).max(0.0)
    } else {
        let w1 = (1.0 - w).ln();
        let (y, m, s) = if n <= 11 {
            let gamma = poly(&[-2.273, 0.459], an);
            if w1 >= gamma {
                return Ok(TestResult { statistic: w, p_value: 1e-99, degrees_of_freedom: f64::NAN });
            }
            (-(gamma - w1).ln(), poly(&[0.544, -0.39978, 0.025054, -6.714e-4], an), poly(&[1.3822, -0.77857, 0.062767, -0.0020322], an).exp())
        } else {
            let xx = an.ln();
            (w1, poly(&[-1.5861, -0.31082, -0.083751, 0.0038915], xx), poly(&[-0.4803, -0.082676, 0.0030302], xx).exp())
        };
        1.0 - normal_cdf((y - m) / s, 0.0, 1.0)
    };
    Ok(TestResult { statistic: w, p_value: pw, degrees_of_freedom: f64::NAN })
}
/// The Wilcoxon signed-rank test that the differences `d` (or `x − y`) are symmetric about zero
/// (SciPy's `wilcoxon` with its defaults: zeros dropped, no continuity correction). Without ties
/// or zeros the p-value is exact, from the distribution of `W⁺` computed by dynamic programming
/// over the ranks; with ties, by enumerating all sign changes when `n ≤ 13`, and otherwise from the
/// normal approximation with the tie correction. For the two-sided test the statistic is
/// `min(W⁺, W⁻)`, otherwise `W⁺`.
pub fn wilcoxon(d: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
    let n_all = d.len();
    let nonzero: Vec<f64> = d.iter().copied().filter(|v| *v != 0.0).collect();
    let n = nonzero.len();
    if n == 0 {
        return Err(ErrorsJSL::InvalidInputRange("all differences are zero"));
    }
    let abs: Vec<f64> = nonzero.iter().map(|v| v.abs()).collect();
    let r = rank(&abs);
    let r_plus: f64 = nonzero.iter().zip(&r).filter(|(v, _)| **v > 0.0).map(|(_, r)| r).sum();
    let r_minus: f64 = nonzero.iter().zip(&r).filter(|(v, _)| **v < 0.0).map(|(_, r)| r).sum();
    let has_ties = tie_sum(&abs) > 0.0;
    let has_zeros = n < n_all;
    let p = if !has_ties && !has_zeros {
        // Exact distribution of W⁺ = Σ of a random subset of 1..n.
        let max = n * (n + 1) / 2;
        let mut counts = vec![0.0f64; max + 1];
        counts[0] = 1.0;
        for k in 1..=n {
            for s in (k..=max).rev() {
                counts[s] += counts[s - k];
            }
        }
        let total = 2f64.powi(n as i32);
        let cdf = |w: usize| counts[..=w.min(max)].iter().sum::<f64>() / total;
        let sf = |w: usize| if w == 0 { 1.0 } else { 1.0 - cdf(w - 1) };
        let (lo, hi) = (r_plus.ceil() as usize, r_plus.floor() as usize);
        match alternative {
            Alternative::Less => cdf(lo),
            Alternative::Greater => sf(hi),
            Alternative::TwoSided => (2.0 * sf(hi).min(cdf(lo))).min(1.0),
        }
    } else if n_all <= 13 {
        // Permutation: every assignment of signs to the non-zero ranks.
        let eps = (100.0 * f64::EPSILON * r_plus).abs();
        let (mut le, mut ge) = (0usize, 0usize);
        for mask in 0..(1usize << n) {
            let w: f64 = (0..n).filter(|&i| mask >> i & 1 == 1).map(|i| r[i]).sum();
            if w <= r_plus + eps {
                le += 1;
            }
            if w >= r_plus - eps {
                ge += 1;
            }
        }
        let total = (1usize << n) as f64;
        let (pl, pg) = (le as f64 / total, ge as f64 / total);
        match alternative {
            Alternative::Less => pl,
            Alternative::Greater => pg,
            Alternative::TwoSided => (2.0 * pl.min(pg)).min(1.0),
        }
    } else {
        let nf = n as f64;
        let mn = nf * (nf + 1.0) * 0.25;
        let se = ((nf * (nf + 1.0) * (2.0 * nf + 1.0) - tie_sum(&abs) / 2.0) / 24.0).sqrt();
        let z = (r_plus - mn) / se;
        match alternative {
            Alternative::Less => normal_cdf(z, 0.0, 1.0),
            Alternative::Greater => normal_cdf(-z, 0.0, 1.0),
            Alternative::TwoSided => 2.0 * normal_cdf(-z.abs(), 0.0, 1.0),
        }
    };
    let statistic = if alternative == Alternative::TwoSided { r_plus.min(r_minus) } else { r_plus };
    Ok(TestResult { statistic, p_value: p, degrees_of_freedom: f64::NAN })
}
  • Every test returns the same TestResult as the classical tests: statistic, p-value and degrees of freedom.
  • anderson_normal returns critical values, not a p-value, as SciPy did before 1.17 introduced tabulated interpolation.
  • adjust_p_values covers SciPy’s false_discovery_control (Benjamini-Hochberg and -Yekutieli) and adds Bonferroni and Holm.

In practice

Every test is compared with scipy.stats from SciPy 1.17.1 on samples written by book/generator/data/make_more_tests_refs.py. The differences are relative:

Table 10.9. Hypothesis tests against SciPy.

test (SciPy reference)statisticp-valueSciPy’s p-value
shapiro, normal sample (n = 60)1e-101e-80.0912
shapiro, skewed sample (n = 60)6e-113e-90.0000
shapiro, small sample (n = 9)9e-112e-90.4375
shapiro, tiny sample (n = 4)2e-109e-100.9303
jarque_bera, normal1e-156e-150.0059
normaltest (D’Agostino-Pearson), normal6e-162e-150.0104
skewtest, normal4e-164e-150.0383
kurtosistest, normal1e-155e-150.0278
jarque_bera, skewed2e-154e-140.0000
normaltest (D’Agostino-Pearson), skewed3e-164e-150.0000
skewtest, skewed4e-167e-150.0000
kurtosistest, skewed5e-163e-150.0108
levene (median centred), three groups5e-169e-150.0325
bartlett, three groups000.0009
fligner, three groups3e-169e-160.0370
kruskal, three groups000.0987
friedman, 4 treatments × 10 blocks, with ties000.8451
wilcoxon, n = 20, exact, two-sided000.1327
wilcoxon, n = 20, exact, less000.9385
wilcoxon, n = 20, exact, greater000.0664
wilcoxon, n = 12 with ties (all sign changes)000.0957
wilcoxon, n = 40 with ties (normal approximation)01e-160.7587
fisher_exact [[8, 2], [1, 5]], two-sided08e-160.0350
fisher_exact [[8, 2], [1, 5]], less000.9991
fisher_exact [[8, 2], [1, 5]], greater07e-160.0245
fisher_exact [[12, 5], [9, 14]], two-sided03e-150.0624
fisher_exact [[12, 5], [9, 14]], less000.9897
fisher_exact [[12, 5], [9, 14]], greater01e-150.0488
fisher_exact [[0, 7], [6, 3]], two-sided01e-150.0114
fisher_exact [[0, 7], [6, 3]], less01e-150.0105
fisher_exact [[0, 7], [6, 3]], greater001.0000
binomtest k = 7, n = 20, p = 0.503e-150.2632
binomtest k = 3, n = 40, p = 0.207e-150.0479
binomtest k = 61, n = 100, p = 0.506e-140.0352
permutation_test, difference of means, 6435 splits, two-sided3e-1600.2794
permutation_test, difference of means, 6435 splits, less3e-1600.1397
permutation_test, difference of means, 6435 splits, greater3e-1600.8605
anderson_normal, normal: statistic, critical values5e-140
anderson_normal, skewed: statistic, critical values00
adjust_p_values, BenjaminiHochberg (false_discovery_control)1e-16
adjust_p_values, BenjaminiYekutieli (false_discovery_control)2e-16

Shapiro-Wilk differs at , because the normal quantiles inside Royston’s approximation come from a different (slightly less precise) inverse normal function. Every other test agrees to rounding, including the exact and permutation p-values.

Strengths

  • Exact p-values for the Wilcoxon, Fisher and binomial tests and for permutation tests of any statistic.
  • Robust alternatives for every classical assumption: rank tests for normality of the data, Levene and Fligner for equal variances.
  • False-discovery-rate control for large families of tests.

Weaknesses

  • No Cramér-von Mises test, Brunner-Munzel test, Tukey’s or Dunnett’s multiple-comparison procedures, or monte_carlo_test.
  • Permutation tests are for two independent samples. Paired designs use wilcoxon or a permutation of signs written by the caller.
  • Fisher’s exact test is for 2 × 2 tables only.

Exercises

  1. Show that is the squared correlation between the ordered sample and the coefficients , and therefore at most 1.
  2. Count by hand the distribution of for , and find the exact two-sided p-value when all four differences are positive.
  3. Show that the two-sided Fisher p-value for the table is .
  4. Why must a permutation test that samples random splits count the observed split? What is its smallest possible p-value with resamples?
  5. Show that Holm’s procedure rejects every hypothesis Bonferroni rejects.
Hints and answers
  1. The have and , so by the Cauchy-Schwarz inequality.
  2. The 16 subsets of give sums 0 to 10 with counts 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1. All positive gives , so and the two-sided p-value is .
  3. The top-left count has probability . The least probable tables are (observed) and , each with probability , and every other table is more probable, so the p-value is .
  4. Otherwise a p-value of exactly 0 could occur, which is never valid for a finite sample. Counting the observed split makes the test exact for the random procedure. The smallest p-value is .
  5. The smallest p-value is multiplied by in both. Holm then multiplies the others by smaller factors, and the running maximum never exceeds Bonferroni’s .

Further reading

  • P. Royston, “Remark AS R94: A remark on algorithm AS 181: The W-test for normality”, Applied Statistics 44 (1995) 547–551.
  • R. B. D’Agostino and M. A. Stephens (eds.), Goodness-of-Fit Techniques, Marcel Dekker, 1986.
  • M. Hollander, D. A. Wolfe and E. Chicken, Nonparametric Statistical Methods, 3rd ed., Wiley, 2014.
  • P. Good, Permutation, Parametric, and Bootstrap Tests of Hypotheses, 3rd ed., Springer, 2005.
  • Y. Benjamini and Y. Hochberg, “Controlling the false discovery rate: a practical and powerful approach to multiple testing”, Journal of the Royal Statistical Society B 57 (1995) 289–300.