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 descriptive statistics and robust regression

ProblemFit a straight line by least squares with standard errors, or robustly when some points are outliers; summarise data by trimmed means, standard scores and the mode; average angles; find the Box-Cox power that makes data normal; measure distances between observations
Devised byAdrien-Marie Legendre (1805) and Carl Friedrich Gauss (1809), least squares; Henri Theil (1950) and Pranab Kumar Sen (1968), the median of pairwise slopes; Andrew Siegel (1982), repeated medians; John Tukey (1960s), trimmed means; Ronald Fisher (1953) and Kanti Mardia (1972), directional statistics; George Box and David Cox (1964), the power transform; Prasanta Chandra Mahalanobis (1936) and Paul Jaccard (1901), distances
AccuracyAgrees with SciPy to or better; the Box-Cox reaches a higher likelihood than SciPy’s
Costlinregress: . theilslopes and siegelslopes: . pdist: for points in dimensions
Read firstDescriptive statistics, Correlation and covariance
APIlinregress, theilslopes, siegelslopes, trim_mean, zscore, mode, circmean, circvar, circstd, boxcox, pdist, cdist, squareform

Overview

This entry fills in the everyday tools that sit around the descriptive statistics:

  • Straight-line fits. linregress gives the least-squares line with its correlation, -value and standard errors. theilslopes and siegelslopes give lines that a minority of wild points cannot move.
  • Robust and standardised summaries. trim_mean discards the extremes before averaging, zscore standardises, and mode finds the most frequent value.
  • Circular data. Angles, times of day and wind directions wrap around, so the ordinary mean of 350° and 10° is wrong. circmean, circvar and circstd handle them.
  • The Box-Cox transform. It chooses the power that makes positive data most nearly normal.
  • Distances. pdist, cdist and squareform with 13 metrics, following scipy.spatial.distance. They are the input to clustering and multidimensional scaling.

Where it is used

Outliers can ruin a least-squares line, and robust methods resist them.

  • Calibration and measurement. Fitting a line to sensor data that contain a few bad readings.
  • Theil-Sen and related estimators. Estimating a trend (drift of a clock or a sensor) when some points are contaminated.
  • Uncertainty. Standard errors and confidence intervals of the slope and intercept.
  • Summaries. Further descriptive measures for data that are not well behaved.

History

Least squares was published by Adrien-Marie Legendre (1805) and justified probabilistically by Carl Friedrich Gauss (1809). Its weakness, that one gross error can move the line arbitrarily far, was recognised early. Henri Theil (1950) proposed the median of the slopes through pairs of points, and Pranab Kumar Sen (1968) gave its confidence interval through Kendall’s . The breakdown point, the fraction of points that can be corrupted before an estimator becomes arbitrary, was formalised by Frank Hampel (1971). Theil-Sen breaks down at 29 %. Andrew Siegel’s (1982) repeated medians reached the maximum possible, 50 %.

John Tukey championed trimmed means in the 1960s as a compromise between the mean and the median. Directional statistics goes back to Ronald Fisher (1953), on the dispersion of palaeomagnetic directions, and was systematised by Kanti Mardia (1972). Box and Cox (1964) introduced their transform; P. C. Mahalanobis (1936) and Paul Jaccard (1901) the distances that bear their names.

The idea

Least squares and its standard errors

With the centred sums , and , the least-squares line has slope and intercept , and the correlation is . The residual variance is , so the slope’s standard error is

and has Student’s distribution with degrees of freedom when the true slope is zero.

Robust lines

The Theil-Sen slope is the median of all pairwise slopes . An outlier spoils only the slopes through it, and the median ignores them as long as they are a minority. The intercept is .

Sen’s confidence interval needs no distributional assumption. The number of pairwise slopes below the true slope is related to Kendall’s statistic, whose variance under independence is , less a term for each group of tied values. With slopes sorted, the interval runs from the slope of rank to that of rank , where is the normal quantile.

Siegel’s repeated medians take, for each point, the median of its slopes to all others, and then the median of those medians. Up to half the points can be arbitrary before the estimate breaks down.

Figure 10.5. Forty points on with noise, three of them moved by 18–30 units. Least squares is pulled to slope 1.90. Theil-Sen (2.04) and Siegel (2.03) stay near the true slope 2.

Trimmed means, z-scores and the mode

The -trimmed mean sorts the data, removes values from each end and averages the rest. With it is the mean, and as it approaches the median. Its breakdown point is . At to 0.25 it loses little efficiency for normal data while resisting outliers. The z-score expresses each value in standard deviations from the mean. The mode is the most frequent value; ties go to the smallest, as in SciPy.

Circular statistics

Map each angle to a unit vector and average. The mean resultant vector has length and direction :

circmean returns , so the mean of 350° and 10° is 0°. circvar is : 0 when all angles agree and 1 when they cancel. circstd, , is the standard deviation of the wrapped normal distribution with that , and approaches the ordinary standard deviation for concentrated data. Angles in other units (degrees, hours) are mapped to radians through the period high − low.

The Box-Cox transform

For positive data, (and at ) interpolates between the log, the square root and no transformation. If is normal with variance , the Jacobian gives the profile log-likelihood

with the variance of the transformed data. boxcox maximises it with a golden-section search on , widened if the maximum sits at an end. SciPy uses Brent’s method, which stops at a tolerance of about relative. On the flat maximum of Table 10.11 the two answers differ by in . The library’s has the higher likelihood, by .

Distances

The 13 metrics of distance are the usual norms of (Euclidean, squared Euclidean, city block, Chebyshev, Minkowski ), their scaled forms (standardised Euclidean with given variances, Mahalanobis with an inverse covariance matrix), the angle-based cosine and correlation distances, the weighted Canberra and Bray-Curtis distances, and the set-based Hamming and Jaccard distances. Jaccard treats the vectors as booleans: non-zero or not.

pdist returns the distances between points in condensed form, the upper triangle row by row. squareform expands it to the symmetric matrix and back, and cdist gives the full rectangular matrix between two sets.

Algorithm

theilslopes(y, x, α):

  1. Form the slopes of all pairs with and sort them; the slope is their median.
  2. The intercept is .
  3. Compute over tie groups in and .
  4. With the normal quantile of , return the sorted slopes at ranks and as the interval (rounding halves to even, like NumPy).

Implementation

/// The least-squares line `y ≈ slope · x + intercept` (SciPy's `linregress`), from the centred
/// sums `Sxx`, `Sxy`, `Syy`: `slope = Sxy/Sxx`, `r = Sxy/√(Sxx Syy)`, and the slope's standard
/// error `√((1 − r²) Syy / ((n − 2) Sxx))`.
pub fn linregress(x: &[f64], y: &[f64]) -> Result<LinregressResult, ErrorsJSL> {
    check(x, y, 2)?;
    let n = x.len() as f64;
    let (mx, my) = (x.iter().sum::<f64>() / n, y.iter().sum::<f64>() / n);
    let (mut sxx, mut sxy, mut syy) = (0.0, 0.0, 0.0);
    for (a, b) in x.iter().zip(y) {
        let (dx, dy) = (a - mx, b - my);
        sxx += dx * dx;
        sxy += dx * dy;
        syy += dy * dy;
    }
    if sxx == 0.0 {
        return Err(ErrorsJSL::InvalidInputRange("all x values are identical"));
    }
    let slope = sxy / sxx;
    let intercept = my - slope * mx;
    let r = if syy == 0.0 { 0.0 } else { (sxy / (sxx * syy).sqrt()).clamp(-1.0, 1.0) };
    if x.len() == 2 {
        return Ok(LinregressResult { slope, intercept, rvalue: r, pvalue: 1.0, stderr: 0.0, intercept_stderr: 0.0 });
    }
    let df = n - 2.0;
    let stderr = ((1.0 - r * r) * syy / sxx / df).sqrt();
    let t = r * (df / ((1.0 - r) * (1.0 + r))).sqrt();
    let pvalue = if t.is_infinite() { 0.0 } else { 2.0 * student_t_cdf(-t.abs(), df) };
    let intercept_stderr = stderr * (sxx / n + mx * mx).sqrt();
    Ok(LinregressResult { slope, intercept, rvalue: r, pvalue, stderr, intercept_stderr })
}
/// The Theil-Sen line (SciPy's `theilslopes` with `method='separate'`): the slope is the median
/// of the pairwise slopes `(yⱼ − yᵢ)/(xⱼ − xᵢ)` over pairs with `xⱼ > xᵢ`, the intercept
/// `median(y) − slope · median(x)`. The confidence interval at level `alpha` (SciPy's default
/// 0.95) is Sen's: order statistics of the sorted slopes at ranks `(N ± z σ)/2`, where `σ²` is the
/// variance of Kendall's statistic corrected for ties. Breakdown point 29 %.
pub fn theilslopes(y: &[f64], x: &[f64], alpha: f64) -> Result<RobustLine, ErrorsJSL> {
    check(x, y, 2)?;
    let n = x.len();
    let mut slopes = Vec::with_capacity(n * (n - 1) / 2);
    for i in 0..n {
        for j in 0..n {
            if x[j] > x[i] {
                slopes.push((y[j] - y[i]) / (x[j] - x[i]));
            }
        }
    }
    if slopes.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("all x values are identical"));
    }
    let slope = median_of(&mut slopes);
    let intercept = median_of(&mut y.to_vec()) - slope * median_of(&mut x.to_vec());
    let alpha = if alpha > 0.5 { 1.0 - alpha } else { alpha };
    let z = normal_quantile(alpha / 2.0, 0.0, 1.0);
    let term = |k: usize| (k * (k - 1) * (2 * k + 5)) as f64;
    let sigsq = (term(n) - tie_groups(x).into_iter().map(term).sum::<f64>() - tie_groups(y).into_iter().map(term).sum::<f64>()) / 18.0;
    let sigma = sigsq.sqrt();
    let nt = slopes.len() as f64;
    // NumPy rounds halves to even; so does `round_ties_even`.
    let ru = (((nt - z * sigma) / 2.0).round_ties_even() as i64).min(slopes.len() as i64 - 1).max(0) as usize;
    let rl = ((((nt + z * sigma) / 2.0).round_ties_even() as i64) - 1).max(0) as usize;
    Ok(RobustLine { slope, intercept, low_slope: slopes[rl.min(slopes.len() - 1)], high_slope: slopes[ru] })
}
/// The mean resultant vector of angles in `[low, high)` (one period): its length `R ∈ [0, 1]`
/// and direction, as an angle in radians.
fn resultant(angles: &[f64], low: f64, high: f64) -> Result<(f64, f64), ErrorsJSL> {
    if angles.is_empty() {
        return Err(ErrorsJSL::InvalidInputRange("need at least one angle"));
    }
    if !(high > low) {
        return Err(ErrorsJSL::InvalidInputRange("need high > low"));
    }
    let k = TAU / (high - low);
    let (s, c) = angles.iter().fold((0.0, 0.0), |(s, c), &a| {
        let t = (a - low) * k;
        (s + t.sin(), c + t.cos())
    });
    let n = angles.len() as f64;
    Ok(((s / n).hypot(c / n), s.atan2(c)))
}

/// The circular mean of angles with period `high − low` (SciPy's `circmean`; use `0` and `2π`
/// for radians): the direction of the mean resultant vector, mapped into `[low, high)`.
pub fn circmean(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
    let (_, theta) = resultant(angles, low, high)?;
    Ok(low + theta.rem_euclid(TAU) * (high - low) / TAU)
}

/// The circular variance `1 − R` (SciPy's `circvar`), between 0 (all angles equal) and 1.
pub fn circvar(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
    Ok(1.0 - resultant(angles, low, high)?.0)
}

/// The circular standard deviation `√(−2 ln R)`, in the units of the angles (SciPy's `circstd`).
/// It approaches the ordinary standard deviation for concentrated angles.
pub fn circstd(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
    let (r, _) = resultant(angles, low, high)?;
    Ok((-2.0 * r.ln()).sqrt() * (high - low) / TAU)
}
/// Expands a condensed distance vector into the symmetric square matrix with a zero diagonal
/// (SciPy's `squareform`). Its length must be `m(m − 1)/2` for some `m`.
pub fn squareform(condensed: &[f64]) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
    let len = condensed.len();
    let m = ((1.0 + (1.0 + 8.0 * len as f64).sqrt()) / 2.0).round() as usize;
    if m * (m - 1) / 2 != len {
        return Err(ErrorsJSL::InvalidInputRange("the length is not m(m − 1)/2 for any m"));
    }
    // Entry (i, j), i < j, sits at position i·m − i(i + 1)/2 + (j − i − 1) of the condensed form.
    let index = |i: usize, j: usize| i * m - i * (i + 1) / 2 + (j - i - 1);
    Ok((0..m).map(|i| (0..m).map(|j| match i.cmp(&j) {
        std::cmp::Ordering::Less => condensed[index(i, j)],
        std::cmp::Ordering::Greater => condensed[index(j, i)],
        std::cmp::Ordering::Equal => 0.0,
    }).collect()).collect())
}
  • linregress returns a -value of 1 and zero standard errors for two points, where there are no residual degrees of freedom.
  • zscore takes ddof as SciPy does (default 0). standard_error in descriptive statistics is SciPy’s sem.

In practice

Every function is compared with SciPy 1.17.1 (references from book/generator/data/make_utilities_refs.py). The regression data are the forty points of Figure 10.5. The trimmed means use 101 values from a distribution, the circular statistics 50 von Mises angles, and the distances 7 points in 4 dimensions with some zero components:

Table 10.11. Robust lines, summaries, circular statistics, Box-Cox and distances against SciPy.

computation (SciPy reference)largest difference (relative)
linregress: slope, intercept, r, p-value and both standard errors5e-15
theilslopes with its 95 % interval0
theilslopes with its 90 % interval0
theilslopes, tied x and y values0
siegelslopes0
trim_mean, cutting 0, 10, 25 and 40 %4e-16
zscore, ddof 0 and 10
mode of the rounded values0
circmean, circvar, circstd in radians4e-16
the same in degrees3e-16
boxcox: λ = 0.012088181 against SciPy’s 0.012088107, absolute difference (log-likelihood 5e-14 higher than at SciPy’s λ)7e-8
boxcox: the transformed data9e-8
pdist, all 13 metrics, 7 points in 4 dimensions7e-15
cdist, 3 × 4 points0

Strengths

  • Theil-Sen confidence intervals identical to SciPy’s, including the tie correction and NumPy’s rounding of halves.
  • Circular statistics in any units.
  • All the common distance metrics, with condensed and square forms.

Weaknesses

  • Theil-Sen and Siegel take memory and time; randomised algorithms exist.
  • No weighted or multiple regression here: use linear least squares or the regression models of the machine learning chapter.
  • boxcox finds but no confidence interval for it.

Exercises

  1. Show that the least-squares slope is a weighted average of the pairwise slopes, with weights proportional to , and contrast with Theil-Sen.
  2. What is the breakdown point of Theil-Sen? Find the fraction of bad points for which the bad pairwise slopes form half of all pairs.
  3. Compute circmean of 350° and 10°, and the ordinary mean.
  4. Show that circstd the ordinary standard deviation when the angles are concentrated.
  5. Show that as .
Hints and answers
  1. , so slope with ; one extreme point gets a large weight in many pairs, whereas the median gives every slope one vote.
  2. Pairs with at least one bad point: of all pairs. Setting this to gives .
  3. The unit vectors average to , direction 0°; the ordinary mean is 180°.
  4. For small spread, , so .
  5. .

Further reading

  • P. K. Sen, “Estimates of the regression coefficient based on Kendall’s tau”, Journal of the American Statistical Association 63 (1968) 1379–1389.
  • A. F. Siegel, “Robust regression using repeated medians”, Biometrika 69 (1982) 242–244.
  • P. J. Rousseeuw and A. M. Leroy, Robust Regression and Outlier Detection, Wiley, 1987.
  • K. V. Mardia and P. E. Jupp, Directional Statistics, Wiley, 2000.
  • G. E. P. Box and D. R. Cox, “An analysis of transformations”, Journal of the Royal Statistical Society B 26 (1964) 211–252.
  • M. M. Deza and E. Deza, Encyclopedia of Distances, 4th ed., Springer, 2016.