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

Correlation and covariance

ProblemMeasure the strength of association between two variables, and test whether it could be chance
Devised byFrancis Galton (1888), “co-relation”; Karl Pearson (1896), the product-moment coefficient; R. A. Fisher (1915), its sampling distribution; Charles Spearman (1904), rank correlation; Maurice Kendall (1938), , and (1945) the tie-corrected
AccuracyCoefficients and p-values agree with SciPy to (table in the hypothesis tests entry)
CostPearson ; Spearman ; Kendall
Read firstDescriptive statistics
APIcorrelation: pearson, spearman, kendall, rank, covariance, covariance_matrix, correlation_matrix

Overview

The covariance is positive when the two variables tend to be above their means together. Dividing by the standard deviations makes it scale-free: Pearson’s correlation , between and , measures the strength of linear association. Rank correlations replace the values by their ranks and measure any monotone association, at the same time becoming immune to outliers. Each coefficient comes with a p-value for the null hypothesis of no association.

Where it is used

Correlation measures whether two things vary together.

  • Experimental science. Is a sensor’s reading related to temperature? Is there an association between two gene expressions?
  • Finance. Correlations between asset returns drive portfolio diversification.
  • Signal processing. Cross-correlation finds delays between signals, as in sonar and GPS.
  • A warning. Correlation does not imply causation, and Pearson’s coefficient only detects linear relationships; rank correlations (Spearman, Kendall) detect monotone ones and are robust to outliers.

History

Francis Galton, studying the heights of parents and children, introduced “co-relation” and regression towards the mean (1886–1888). Karl Pearson (1896) gave the product-moment formula and its theory, and R. A. Fisher (1915) derived the exact distribution of for normal data, together with the transformation that bears his name. Charles Spearman (1904), a psychologist studying intelligence, proposed correlating ranks; Maurice Kendall (1938) defined a coefficient from concordant and discordant pairs, with a tie-corrected version (1945). Francis Anscombe’s quartet (1973) became the standard warning that a correlation coefficient is no substitute for a plot.

The idea

Pearson’s correlation

The numerator is positive when and tend to be above their means together and below their means together, and negative when one tends to be high where the other is low. Dividing by the two spreads removes the units and the scales of the variables, so is a pure number that does not change if either variable is shifted or rescaled.

  • By the Cauchy-Schwarz inequality , with equality exactly when the points lie on a straight line. So measures the strength of a linear relation; a perfect but curved relation can have a small .
  • is the fraction of the variance of explained by the least-squares line through the data.
  • Significance. Even unrelated variables give a nonzero in a finite sample, so one asks how large a value chance alone would produce. For independent normal variables the statistic has Student’s distribution with degrees of freedom, which gives the p-value.

The library computes by two passes (means first, then deviations, as for the variance) and clamps it to , which rounding could otherwise slightly exceed.

Spearman’s rank correlation

Pearson’s has two limitations: it detects only linear relations, and a single extreme value can dominate it. Both are removed by discarding the values and keeping only their order. Replace each value by its rank among the values (1 for the smallest; tied values share the average of their ranks), do the same for the values, and compute Pearson’s of the ranks.

The result equals 1 for any increasing relation, linear or not, because the ranks of and then coincide. It is also robust: however extreme an outlier is, its rank is at most , so it can only have a limited effect. The library uses the same approximation for the p-value, as SciPy does.

Kendall’s tau

A pair of observations is concordant if and order it the same way and discordant otherwise. With concordant and discordant pairs among the pairs, is the probability of concordance minus that of discordance, a directly interpretable quantity. With ties, , where and count the pairs tied in and in . Under independence is approximately normal with a known, tie-corrected variance, which gives the p-value. The direct count is ; Knight’s (1966) merge-sort algorithm achieves .

Anscombe’s quartet

Table 10.4. Anscombe's quartet.

setmean of variance of Pearson Spearman Kendall
I7.504.130.816 (p = 0.0022)0.818 (p = 0.0021)0.636 (p = 0.0064)
II7.504.130.816 (p = 0.0022)0.691 (p = 0.0186)0.564 (p = 0.0158)
III7.504.120.816 (p = 0.0022)0.991 (p = 0.0000)0.964 (p = 0.0000)
IV7.504.120.817 (p = 0.0022)0.500 (p = 0.1173)0.426 (p = 0.1138)

Anscombe’s four data sets share their means, variances, regression line (dashed) and Pearson correlation of 0.816, yet look nothing alike: a noisy line, a smooth curve, a perfect line with one outlier, and a single influential point. The rank correlations tell them apart: on set III they see the near-perfect monotone relation through the outlier, and on set IV the association rests on one point and is not significant.

Algorithm

Pearson’s .

  1. Compute the means and .
  2. In a second pass, accumulate , and .
  3. Return , clamped to .
  4. For the p-value, compute and the two-sided tail of Student’s distribution with degrees of freedom.

Spearman’s .

  1. Rank each variable: sort its values, and give each value its position in the sorted order, counted from 1. A group of tied values all receive the average of the positions they occupy.
  2. Compute Pearson’s of the two lists of ranks.

Kendall’s .

  1. For every pair of observations , compare the signs of and : equal signs make the pair concordant, opposite signs discordant, and a zero difference makes it a tie in that variable.
  2. Count , and the pairs tied in () and in ().
  3. Return with .
  4. For the p-value, divide by the square root of its variance under independence, corrected for the sizes of the tie groups, and use the normal distribution.

Pearson’s costs , Spearman’s for the sorts, and Kendall’s for the direct count.

Implementation

/// Kendall's τ_b, `(C − D) / √((n₀ − n₁)(n₀ − n₂))` over concordant and discordant pairs with
/// tie corrections, and a two-sided p-value from the normal approximation to `S = C − D` with
/// the tie-corrected variance. `O(n²)`.
pub fn kendall(x: &[f64], y: &[f64]) -> Result<Correlation, ErrorsJSL> {
    paired(x, y, 2)?;
    let n = x.len();
    let mut s: i64 = 0;
    for i in 0..n {
        for j in i + 1..n {
            let product = (x[i] - x[j]).signum() * (y[i] - y[j]).signum();
            if x[i] != x[j] && y[i] != y[j] {
                s += product as i64;
            }
        }
    }
    // Tie groups of each variable.
    let groups = |v: &[f64]| -> Vec<f64> {
        let mut sorted = v.to_vec();
        sorted.sort_by(f64::total_cmp);
        let mut out = Vec::new();
        let mut i = 0;
        while i < sorted.len() {
            let mut j = i;
            while j + 1 < sorted.len() && sorted[j + 1] == sorted[i] {
                j += 1;
            }
            if j > i {
                out.push((j - i + 1) as f64);
            }
            i = j + 1;
        }
        out
    };
    let (tx, ty) = (groups(x), groups(y));
    let nf = n as f64;
    let n0 = nf * (nf - 1.0) / 2.0;
    let n1: f64 = tx.iter().map(|t| t * (t - 1.0) / 2.0).sum();
    let n2: f64 = ty.iter().map(|t| t * (t - 1.0) / 2.0).sum();
    let denominator = ((n0 - n1) * (n0 - n2)).sqrt();
    if denominator == 0.0 {
        return Err(ErrorsJSL::InvalidInputRange("Correlation is undefined for a constant sample."));
    }
    let tau = s as f64 / denominator;
    let sum = |g: &[f64], f: &dyn Fn(f64) -> f64| g.iter().map(|&t| f(t)).sum::<f64>();
    let v0 = nf * (nf - 1.0) * (2.0 * nf + 5.0);
    let vt = sum(&tx, &|t| t * (t - 1.0) * (2.0 * t + 5.0));
    let vu = sum(&ty, &|t| t * (t - 1.0) * (2.0 * t + 5.0));
    let v1 = sum(&tx, &|t| t * (t - 1.0)) * sum(&ty, &|t| t * (t - 1.0)) / (2.0 * nf * (nf - 1.0));
    let v2 = if n > 2 { sum(&tx, &|t| t * (t - 1.0) * (t - 2.0)) * sum(&ty, &|t| t * (t - 1.0) * (t - 2.0)) / (9.0 * nf * (nf - 1.0) * (nf - 2.0)) } else { 0.0 };
    let variance = (v0 - vt - vu) / 18.0 + v1 + v2;
    let z = s as f64 / variance.sqrt();
    Ok(Correlation { coefficient: tau, p_value: 2.0 * normal_cdf(-z.abs(), 0.0, 1.0) })
}
  • covariance_matrix and correlation_matrix take a slice of variables (each a sample), and return symmetric matrices.
  • A constant variable has no correlation; the functions return an error.

In practice

//! Three correlation coefficients on a monotone but nonlinear relation with an outlier.

use lib_jsl_statistics::correlation::{correlation_matrix, kendall, pearson, spearman};

fn main() {
    // Dose and response: saturating growth, with the last response misrecorded.
    let dose: Vec<f64> = (1..=15).map(|d| d as f64).collect();
    let mut response: Vec<f64> = dose.iter().map(|d| 10.0 * (1.0 - (-d / 4.0f64).exp()) + 0.3 * (d * 1.7).sin()).collect();
    response[14] = 0.5;
    for (name, r) in [("Pearson", pearson(&dose, &response)), ("Spearman", spearman(&dose, &response)), ("Kendall", kendall(&dose, &response))] {
        let r = r.unwrap();
        println!("{name:<9} {:+.3}  (p = {:.2e})", r.coefficient, r.p_value);
    }
    let m = correlation_matrix(&[dose.clone(), response.clone(), dose.iter().map(|d| d * d).collect()]).unwrap();
    for row in m {
        println!("{}", row.iter().map(|v| format!("{v:+.3}")).collect::<Vec<_>>().join("  "));
    }
}
Pearson   +0.362  (p = 1.85e-1)
Spearman  +0.600  (p = 1.81e-2)
Kendall   +0.638  (p = 9.14e-4)
+1.000  +0.362  +0.972
+0.362  +1.000  +0.182
+0.972  +0.182  +1.000

One misrecorded response hides a strong monotone relation from Pearson’s ; the rank correlations still find it.

Strengths

  • Three coefficients with p-values matching SciPy, including ties.
  • Rank correlations capture monotone, nonlinear association and resist outliers.

Weaknesses

  • Correlation measures association, not causation, and only linear (Pearson) or monotone (rank) association: on a symmetric range has correlation zero.
  • Kendall’s is ; the p-values are asymptotic.

Exercises

  1. Prove from the Cauchy-Schwarz inequality, with equality only for collinear points.
  2. Show that without ties Spearman’s , where are the rank differences.
  3. Show that for continuous bivariate normal data , and check it by simulation.
  4. Construct a data set with but a perfect functional relation.
  5. Implement Knight’s algorithm for by counting inversions during a merge sort.
Hints and answers
  1. for the centred data ; Cauchy-Schwarz gives with equality iff , i.e. the points are collinear.
  2. Ranks of both samples are permutations of , with fixed. Expanding and substituting in the Pearson formula for ranks (variance ) gives the stated expression.
  3. For a bivariate normal with correlation , the probability that a pair is concordant is ; then .
  4. Take symmetric about 0, for example , and : the relation is perfect but because .
  5. Sort by , then count the inversions in while merge sorting: and follow from the number of inversions, in .

Further reading

  • F. J. Anscombe, “Graphs in statistical analysis”, The American Statistician 27 (1973) 17–21.
  • M. G. Kendall and J. D. Gibbons, Rank Correlation Methods, 5th ed., Edward Arnold, 1990.
  • W. R. Knight, “A computer method for calculating Kendall’s tau with ungrouped data”, Journal of the American Statistical Association 61 (1966) 436–439.
  • J. L. Rodgers and W. A. Nicewander, “Thirteen ways to look at the correlation coefficient”, The American Statistician 42 (1988) 59–66.