Algorithm Search⌘K

Algorithmcore

Heteroscedasticity-consistent standard errors

Also called sandwich estimator, Huber-White standard errors, Eicker-Huber-White standard errors, robust standard errors.

Estimate the covariance of least squares as (X^T X)^(-1) X^T diag(e_i^2) X (X^T X)^(-1), which stays consistent when the error variance varies.

Time
Θ(n p^2) worst · best
Space
Θ(n p) extra
Where
n = the number of observations; p = the number of columns of X, with p < n
Properties
deterministicexactofflineiterative
Origin
Friedhelm Eicker, Peter J. Huber, Halbert White, James G. MacKinnon, 1967

Heteroscedasticity-consistent (HC) standard errors keep the ordinary least squares estimate and replace only its variance estimate. When the errors have unequal variances σi2\sigma_i^2, the true covariance of b^\hat b is the sandwich (X⊤X)−1X⊤ΣX(X⊤X)−1(X^\top X)^{-1}X^\top\Sigma X(X^\top X)^{-1} with Σ=diag⁡(σi2)\Sigma = \operatorname{diag}(\sigma_i^2), not σ2(X⊤X)−1\sigma^2(X^\top X)^{-1}. The HC estimators put a squared residual, possibly corrected for leverage, in place of each unknown σi2\sigma_i^2. No model for the variances is needed, and the result is consistent under any pattern of heteroscedasticity. The names Huber-White and Eicker-Huber-White standard errors refer to the same method. The four common versions, HC0 to HC3, differ only in the small sample correction, and with a QR factorization all four cost one least squares fit.

In plain words

The usual standard error of a regression slope assumes that every point is equally noisy. When the noise is larger for some points, that formula can be far too small or too large. This method keeps the fitted line and estimates the uncertainty in a different way: it looks at how far each point is from the line and lets the points with big misses, at places where they move the slope a lot, count for more uncertainty. It does not need to know why the noise varies. Points that pull the line hard toward themselves look better fitted than they are, so the better versions scale up their misses.

The problem

Model. y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix of rank p<np < n (the intercept is one of the pp columns), and independent errors with E[εi]=0\mathrm E[\varepsilon_i] = 0 and Var⁡(εi)=σi2\operatorname{Var}(\varepsilon_i) = \sigma_i^2, unknown and possibly all different. Then

Cov⁡(b^)=(X⊤X)−1X⊤ΣX(X⊤X)−1,Σ=diag⁡(σ12,…,σn2).\operatorname{Cov}(\hat b) = (X^\top X)^{-1}X^\top\Sigma X(X^\top X)^{-1}, \qquad \Sigma = \operatorname{diag}(\sigma_1^2, \dots, \sigma_n^2).

Input. XX, yy and the choice of version.

Output. b^\hat b and the estimate V^=(X⊤X)−1X⊤ΩX(X⊤X)−1\widehat V = (X^\top X)^{-1}X^\top\Omega X(X^\top X)^{-1} with Ω=diag⁡(ωi)\Omega = \operatorname{diag}(\omega_i), where ei=yi−xi⊤b^e_i = y_i - x_i^\top\hat b, hiih_{ii} is the leverage, and

version ωi\omega_i idea
HC0 ei2e_i^2 White's original
HC1 ei2 n/(n−p)e_i^2\,n/(n - p) degrees of freedom correction
HC2 ei2/(1−hii)e_i^2/(1 - h_{ii}) unbiased when the variances are equal
HC3 ei2/(1−hii)2e_i^2/(1 - h_{ii})^2 close to the jackknife

The algorithm

  1. HC-COVARIANCE(X[1..n, 1..p], y[1..n], version)
  2. 1(R, c) ← Householder QR of X, applied to y ▷ X = Q₁R, c = Qᵀy
  3. 2b̂ ← solve R b = c[1..p]
  4. 3eᵢ ← yᵢ - xᵢᵀ b̂ for all i
  5. 4qᵢ ← R⁻ᵀ xᵢ; hᵢᵢ ← ‖qᵢ‖² for all i ▷ qᵢᵀ is row i of Q₁ = X R⁻¹
  6. 5ωᵢ ← eᵢ² · (1, n/(n - p), 1/(1 - hᵢᵢ) or 1/(1 - hᵢᵢ)²) ▷ HC0, HC1, HC2, HC3
  7. 6V ← R⁻¹ (Σᵢ ωᵢ qᵢ qᵢᵀ) R⁻ᵀ
  8. 7seⱼ ← √Vⱼⱼ for j = 1..p
  9. 8return (b̂, V, se)

Line L4 gets each row of Q1Q_1 by one triangular solve, so the leverages come out without the n×nn \times n hat matrix. Line L6 is the sandwich in factored form: ∑iωiqiqi⊤=Q1⊤ΩQ1\sum_i\omega_iq_iq_i^\top = Q_1^\top\Omega Q_1, and R−1Q1⊤ΩQ1R−⊤=(X⊤X)−1X⊤ΩX(X⊤X)−1R^{-1}Q_1^\top\Omega Q_1R^{-\top} = (X^\top X)^{-1}X^\top\Omega X(X^\top X)^{-1}. A 100(1−α)%100(1 - \alpha)\% interval for bjb_j is b^j±q sej\hat b_j \pm q\,\mathrm{se}_j; the implementation takes qq as the upper α/2\alpha/2 quantile of tn−pt_{n-p}, which is a convention, since the theory only gives a normal limit. A Wald test of Cb=dCb = d uses (Cb^−d)⊤(CVC⊤)−1(Cb^−d)(C\hat b - d)^\top(CVC^\top)^{-1}(C\hat b - d), as on the Wald test page.

Example

Take x=(1,2,3,4,10)x = (1, 2, 3, 4, 10) and y=(1,3,2,5,14)y = (1, 3, 2, 5, 14) with an intercept. Exact arithmetic gives b^=(−21/25,73/50)=(−0.84,1.46)\hat b = (-21/25, 73/50) = (-0.84, 1.46) and

ii xix_i eie_i hiih_{ii}
1 1 0.38 0.38
2 2 0.92 0.28
3 3 -1.54 0.22
4 4 0 0.20
5 10 0.24 0.92

The standard error of the slope from each method is:

method se of slope
usual, s2(X⊤X)−1s^2(X^\top X)^{-1} 0.1510
HC0 0.0604
HC1 0.0780
HC2 0.1196
HC3 0.3676

Point 5 has leverage 0.92, so the line passes close to it and its residual 0.24 says little about its error. HC0 takes that residual at face value, and the slope, which depends mostly on point 5, gets a tiny standard error. HC3 multiplies e52e_5^2 by 1/(1−0.92)2=1561/(1 - 0.92)^2 = 156. With five points none of these numbers is reliable; the example shows how strongly the versions can differ when the leverages are uneven.

Measured coverage. With n=25n = 25, xix_i drawn once from a lognormal law, yi=1+xi+εiy_i = 1 + x_i + \varepsilon_i and εi∼N(0,(0.5xi)2)\varepsilon_i \sim N(0, (0.5x_i)^2), r=2000r = 2000 samples from random.Random(20261114) gave these coverages of the nominal 95% t interval for the slope:

method coverage
usual standard error 0.767
HC0 0.858
HC1 0.867
HC2 0.889
HC3 0.912

All HC versions improve on the usual standard error, and none reaches 0.95 at this sample size with a skewed design; HC3 comes closest. These are measurements for one design, not theorems.

Correctness

The proof shows four exact facts. Lines L1 to L6 return exactly (X⊤X)−1X⊤ΩX(X⊤X)−1(X^\top X)^{-1}X^\top\Omega X(X^\top X)^{-1}, with hii=∥qi∥2h_{ii} = \lVert q_i\rVert^2. If the errors have equal variance σ2\sigma^2, then E[ei2]=σ2(1−hii)\mathrm E[e_i^2] = \sigma^2(1 - h_{ii}), so HC2 is exactly unbiased for σ2(X⊤X)−1\sigma^2(X^\top X)^{-1}, HC0 is biased down and HC3 is biased up. By the Sherman-Morrison formula, deleting row ii moves the estimate by −(X⊤X)−1xiei/(1−hii)-(X^\top X)^{-1}x_ie_i/(1 - h_{ii}), so HC3 is exactly the sum of the outer products of the leave-one-out changes, which links it to the jackknife.

The main statistical property is cited, not proved: under independent errors, bounded higher moments and regularity conditions on XX (leverages that go to 0 and a nonsingular limit of X⊤X/nX^\top X/n), nV^n\widehat V is consistent for the limit of nCov⁡(b^)n\operatorname{Cov}(\hat b), for every pattern of variances (Eicker 1967, Huber 1967, White 1980). The resulting t and Wald statistics are asymptotically normal and chi-square.

Proof: The QR form of the heteroscedasticity-consistent covariance equals the sandwich formula, HC2 is unbiased under equal variances, and HC3 is a sum of leave-one-out changesfull

The arithmetic is exact. XX is a fixed real n×pn \times p matrix of rank p<np < n with rows xi⊤x_i^\top, b^=(X⊤X)−1X⊤y\hat b = (X^\top X)^{-1}X^\top y, e=y−Xb^e = y - X\hat b, and H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top with diagonal hiih_{ii}. The target of each estimator is

V^ω=(X⊤X)−1X⊤ΩX(X⊤X)−1,Ω=diag⁡(ω1,…,ωn),\widehat V_\omega = (X^\top X)^{-1}X^\top\Omega X(X^\top X)^{-1}, \qquad \Omega = \operatorname{diag}(\omega_1, \dots, \omega_n),

with ωi=ei2\omega_i = e_i^2 (HC0), ei2n/(n−p)e_i^2n/(n - p) (HC1), ei2/(1−hii)e_i^2/(1 - h_{ii}) (HC2) or ei2/(1−hii)2e_i^2/(1 - h_{ii})^2 (HC3).

Lemma 1 (lines L1 to L4). Line L1 gives an upper triangular nonsingular RR with X⊤X=R⊤RX^\top X = R^\top R, and line L2 gives b^\hat b. The vectors qi=R−⊤xiq_i = R^{-\top}x_i of line L4 are the rows of Q1=XR−1Q_1 = XR^{-1}, which has orthonormal columns, and hii=∥qi∥2h_{ii} = \lVert q_i\rVert^2.

Proof. The Householder argument (Lemma 1 of the proof on the weighted least squares page, with unit weights) gives Q⊤X=(R0)Q^\top X = \binom{R}{0} with QQ orthogonal and b^=R−1c1..p\hat b = R^{-1}c_{1..p}, so X=Q1RX = Q_1R with Q1Q_1 the first pp columns of QQ, and X⊤X=R⊤Q1⊤Q1R=R⊤RX^\top X = R^\top Q_1^\top Q_1R = R^\top R. Row ii of XR−1XR^{-1} is xi⊤R−1=(R−⊤xi)⊤=qi⊤x_i^\top R^{-1} = (R^{-\top}x_i)^\top = q_i^\top. Then H=X(R⊤R)−1X⊤=(XR−1)(XR−1)⊤=Q1Q1⊤H = X(R^\top R)^{-1}X^\top = (XR^{-1})(XR^{-1})^\top = Q_1Q_1^\top, whose (i,i)(i, i) entry is ∥qi∥2\lVert q_i\rVert^2. □\square

Lemma 2 (lines L5 to L7 compute the sandwich). R−1(∑iωiqiqi⊤)R−⊤=V^ωR^{-1}\bigl(\sum_i\omega_iq_iq_i^\top\bigr)R^{-\top} = \widehat V_\omega.

Proof. ∑iωiqiqi⊤=Q1⊤ΩQ1=R−⊤X⊤ΩXR−1\sum_i\omega_iq_iq_i^\top = Q_1^\top\Omega Q_1 = R^{-\top}X^\top\Omega XR^{-1}. So R−1(⋅)R−⊤=(R⊤R)−1X⊤ΩX(R⊤R)−1R^{-1}(\cdot)R^{-\top} = (R^\top R)^{-1}X^\top\Omega X(R^\top R)^{-1}, and R⊤R=X⊤XR^\top R = X^\top X. □\square

So the algorithm returns the HC0 to HC3 matrices exactly, and it never forms an n×nn \times n matrix.

Lemma 3 (HC2 is unbiased when the variances are equal). If E[ε]=0\mathrm E[\varepsilon] = 0 and Cov⁡(ε)=σ2I\operatorname{Cov}(\varepsilon) = \sigma^2I, then E[ei2]=σ2(1−hii)\mathrm E[e_i^2] = \sigma^2(1 - h_{ii}) and E[V^HC2]=σ2(X⊤X)−1=Cov⁡(b^)\mathrm E[\widehat V_{\mathrm{HC2}}] = \sigma^2(X^\top X)^{-1} = \operatorname{Cov}(\hat b).

Proof. e=(I−H)εe = (I - H)\varepsilon, so Cov⁡(e)=σ2(I−H)(I−H)⊤=σ2(I−H)\operatorname{Cov}(e) = \sigma^2(I - H)(I - H)^\top = \sigma^2(I - H), because I−HI - H is symmetric and idempotent. Its diagonal gives E[ei2]=σ2(1−hii)\mathrm E[e_i^2] = \sigma^2(1 - h_{ii}), so E[ei2/(1−hii)]=σ2\mathrm E[e_i^2/(1 - h_{ii})] = \sigma^2 and E[Ω]=σ2I\mathrm E[\Omega] = \sigma^2I. The sandwich is linear in Ω\Omega, so E[V^HC2]=σ2(X⊤X)−1X⊤X(X⊤X)−1=σ2(X⊤X)−1\mathrm E[\widehat V_{\mathrm{HC2}}] = \sigma^2(X^\top X)^{-1}X^\top X(X^\top X)^{-1} = \sigma^2(X^\top X)^{-1}. □\square

Under the same assumption, E[V^HC0]=σ2(X⊤X)−1X⊤(I−diag⁡(hii))X(X⊤X)−1\mathrm E[\widehat V_{\mathrm{HC0}}] = \sigma^2(X^\top X)^{-1}X^\top(I - \operatorname{diag}(h_{ii}))X(X^\top X)^{-1}, which is smaller than σ2(X⊤X)−1\sigma^2(X^\top X)^{-1} by a positive semidefinite matrix; HC0 is biased down, and most where the leverages are large. HC3 is biased up in this case. Under unequal variances none of the four is exactly unbiased.

Lemma 4 (HC3 is a sum of leave-one-out changes). Let b^(i)\hat b_{(i)} be the least squares estimate without row ii, and hii<1h_{ii} < 1 for all ii. Then

b^(i)−b^=−(X⊤X)−1xiei1−hii,V^HC3=∑i=1n(b^(i)−b^)(b^(i)−b^)⊤.\hat b_{(i)} - \hat b = -\frac{(X^\top X)^{-1}x_ie_i}{1 - h_{ii}}, \qquad \widehat V_{\mathrm{HC3}} = \sum_{i=1}^n(\hat b_{(i)} - \hat b)(\hat b_{(i)} - \hat b)^\top.

Proof. Deleting row ii changes X⊤XX^\top X to A=X⊤X−xixi⊤A = X^\top X - x_ix_i^\top and X⊤yX^\top y to X⊤y−xiyiX^\top y - x_iy_i. By the Sherman-Morrison formula, with G=(X⊤X)−1G = (X^\top X)^{-1}, A−1=G+Gxixi⊤G/(1−hii)A^{-1} = G + Gx_ix_i^\top G/(1 - h_{ii}), since xi⊤Gxi=hiix_i^\top Gx_i = h_{ii}. Then

b^(i)=A−1(X⊤y−xiyi)=b^+Gxi xi⊤b^1−hii−Gxiyi−Gxihiiyi1−hii=b^−Gxi(yi−xi⊤b^)1−hii.\hat b_{(i)} = A^{-1}(X^\top y - x_iy_i) = \hat b + \frac{Gx_i\,x_i^\top\hat b}{1 - h_{ii}} - Gx_iy_i - \frac{Gx_ih_{ii}y_i}{1 - h_{ii}} = \hat b - \frac{Gx_i(y_i - x_i^\top\hat b)}{1 - h_{ii}}.

Summing the outer products gives G(∑ixixi⊤ei2/(1−hii)2)G=V^HC3G\bigl(\sum_ix_ix_i^\top e_i^2/(1 - h_{ii})^2\bigr)G = \widehat V_{\mathrm{HC3}}. □\square

The jackknife variance of MacKinnon and White (1985) centers the b^(i)\hat b_{(i)} at their mean bˉ(⋅)\bar b_{(\cdot)} instead of at b^\hat b and multiplies by (n−1)/n(n - 1)/n; with di=b^(i)−b^d_i = \hat b_{(i)} - \hat b and dˉ\bar d their mean, it equals n−1n(V^HC3−ndˉdˉ⊤)\frac{n - 1}{n}\bigl(\widehat V_{\mathrm{HC3}} - n\bar d\bar d^\top\bigr), by expanding the square. The two differ by a term that is small when no row dominates.

What is cited, not proved. Under independent errors with bounded higher moments and regularity conditions on XX (the leverages go to 0 and X⊤X/nX^\top X/n converges to a nonsingular limit), nV^ωn\widehat V_\omega converges in probability to the limit of nCov⁡(b^)n\operatorname{Cov}(\hat b) for each of HC0 to HC3, so the t statistics are asymptotically standard normal. This is the theorem of Eicker (1967), Huber (1967) and White (1980); it is not proved here, and the coverage figures on the page are measured.

Termination. Line L1 is pp Householder steps, lines L2 to L4 are n+1n + 1 triangular solves of size pp, line L5 is nn scalar operations, and lines L6 and L7 are finite sums: Θ(np2)\Theta(np^2) operations in total.

Complexity

The QR costs 2np2−2p3/32np^2 - 2p^3/3 flops, the nn triangular solves of line L4 cost np2np^2, the sum of line L6 costs np2np^2, and the two triangular sandwiches cost O(p3)O(p^3). The total is Θ(np2)\Theta(np^2) time, the order of the fit itself, and Θ(np)\Theta(np) extra space. Forming the n×nn \times n hat matrix would cost Θ(n2p)\Theta(n^2p) time and Θ(n2)\Theta(n^2) space and is never needed.

Properties

  • No variance model. The estimate is consistent whatever the σi2\sigma_i^2 are, as long as the errors are independent and the leverages become small.
  • Order of the versions. HC1 equals HC0 times n/(n−p)n/(n - p), and since 1≤1/(1−hii)≤1/(1−hii)21 \le 1/(1 - h_{ii}) \le 1/(1 - h_{ii})^2, the matrices satisfy HC0 ⪯\preceq HC2 ⪯\preceq HC3 in the Loewner order; the same holds for each standard error.
  • Equivariance. Replacing XX by XAXA for a nonsingular AA maps V^\widehat V to A−1V^A−⊤A^{-1}\widehat VA^{-\top}, as for the usual covariance, and the residuals and leverages do not change.
  • Same as the M-estimation sandwich. For least squares as an M-estimator, the bread is X⊤XX^\top X and the meat is ∑ei2xixi⊤\sum e_i^2x_ix_i^\top, so HC0 is the general sandwich covariance applied to this case.
  • Leverage-one points. If hii=1h_{ii} = 1 then ei=0e_i = 0, HC0 ignores row ii, and HC2 and HC3 are undefined. The implementation raises an error for HC2 and HC3 in that case.

Variants and improvements

  • HC4 and HC5. Cribari-Neto and coauthors raise the leverage exponent with hiih_{ii} to handle very high leverage points. They are rarely needed when the design has no extreme points.
  • Clustered errors. If the errors are correlated within groups, replace ∑iei2xixi⊤\sum_ie_i^2x_ix_i^\top by a sum over groups of (∑i∈geixi)(∑i∈geixi)⊤(\sum_{i \in g}e_ix_i)(\sum_{i \in g}e_ix_i)^\top: cluster-robust standard errors. With one observation per group it reduces to HC0, or HC1 with the matching correction.
  • Serial correlation. For time series, kernel-weighted sums of cross products of nearby etxte_tx_t give heteroscedasticity and autocorrelation consistent estimates, of which Newey and West's is the best known.
  • Bootstrap. The wild bootstrap multiplies each residual by an independent random sign and refits; with HC2 or HC3 studentization it often gives better small sample tests than the normal approximation. The pairs bootstrap resamples whole rows.
  • Other estimators. The same sandwich form gives the covariance of generalized estimating equations, of quasi-likelihood fits with a wrong variance function, and of M-estimators in general.

When to use it

Use HC standard errors for least squares on cross-section data whenever the variance may depend on the regressors, which is most of the time in economics and the social sciences. Long and Ervin (2000) recommend HC3 when n≤250n \le 250, and argue that the choice should not depend on a pretest such as the Breusch-Pagan test. If the variance pattern is known or can be modelled well, weighted least squares gives a more efficient estimate; an HC covariance on top of it protects against a wrong weight model.

Pitfalls

  • Small samples with high leverage. HC0 and HC1 can be far too small when some hiih_{ii} are large, as in the example. Prefer HC3, look at the leverages, and do not trust the nominal level when a few points dominate.
  • It fixes the variance, not the estimate. OLS stays unbiased under heteroscedasticity but is not efficient. HC standard errors make the inference valid; they do not make the fit better.
  • Correlated errors. The method assumes independent errors. Within-group or serial correlation needs the clustered or the autocorrelation consistent versions.
  • F tests. The usual F statistic uses s2s^2 and is wrong under heteroscedasticity. Use the Wald form with V^\widehat V, and treat its F or chi-square reference law as an approximation.
  • Which version. Software defaults differ: some report HC0, some HC1, some HC3. State the version in reports.
  • Misspecified mean. If the mean model is wrong, the HC covariance is still a consistent covariance for the best linear approximation, but the coefficients no longer mean what the model says.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

heteroscedasticity_consistent_standard_errors.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heteroscedasticity-consistent-standard-errors/. The authors are listed in prov/PTWW7S.jsonl.
"""Heteroscedasticity-consistent covariance of the least squares estimate, HC0 to HC3.

With X = Q1 R (thin QR, Q1 = X R^(-1)) the sandwich
(X^T X)^(-1) X^T diag(omega_i) X (X^T X)^(-1) equals R^(-1) (sum omega_i q_i q_i^T) R^(-T),
where q_i^T is row i of Q1 and h_ii = |q_i|^2 is the leverage. The weights are
  HC0: e_i^2                    HC1: e_i^2 n / (n - p)
  HC2: e_i^2 / (1 - h_ii)       HC3: e_i^2 / (1 - h_ii)^2
Nothing of size n x n is formed.
"""

import math
from typing import NamedTuple

from stdist import t_ppf

RANK_TOL = 1e-12
KINDS = ("HC0", "HC1", "HC2", "HC3")


class HCFit(NamedTuple):
    b: list          # least squares coefficients
    cov: list        # the HC covariance estimate, p x p
    se: list         # square roots of its diagonal
    residuals: list  # e_i
    leverage: list   # h_ii
    df: int          # n - p


def householder_r(a: list, y: list) -> tuple[list, list]:
    """R of a Householder QR of the n x p matrix a, and Q^T y. Raises ValueError if rank < p."""
    n = len(a)
    p = len(a[0]) if n else 0
    if p == 0 or n < p:
        raise ValueError("need a design with n >= p >= 1")
    a = [[float(v) for v in row] for row in a]
    c = [float(v) for v in y]
    col = [math.sqrt(math.fsum(a[i][j] ** 2 for i in range(n))) for j in range(p)]
    for j in range(p):
        norm = math.sqrt(math.fsum(a[i][j] ** 2 for i in range(j, n)))
        if norm == 0.0 or norm <= RANK_TOL * col[j]:
            raise ValueError("the design has rank below its number of columns")
        alpha = -norm if a[j][j] >= 0.0 else norm
        v = [a[j][j] - alpha] + [a[i][j] for i in range(j + 1, n)]
        vv = math.fsum(t * t for t in v)
        for k in range(j, p):
            s = 2.0 * math.fsum(v[i - j] * a[i][k] for i in range(j, n)) / vv
            for i in range(j, n):
                a[i][k] -= s * v[i - j]
        s = 2.0 * math.fsum(v[i - j] * c[i] for i in range(j, n)) / vv
        for i in range(j, n):
            c[i] -= s * v[i - j]
    return [[a[i][k] if k >= i else 0.0 for k in range(p)] for i in range(p)], c


def back_substitute(r: list, c: list) -> list:
    p = len(r)
    x = [0.0] * p
    for i in range(p - 1, -1, -1):
        x[i] = (c[i] - math.fsum(r[i][k] * x[k] for k in range(i + 1, p))) / r[i][i]
    return x


def forward_substitute_rt(r: list, c: list) -> list:
    """Solve R^T q = c for upper triangular R (R^T is lower triangular)."""
    p = len(r)
    q = [0.0] * p
    for i in range(p):
        q[i] = (c[i] - math.fsum(r[k][i] * q[k] for k in range(i))) / r[i][i]
    return q


def sandwich(r: list, q: list, omega: list) -> list:
    """R^(-1) (sum_i omega_i q_i q_i^T) R^(-T) for upper triangular R."""
    p = len(r)
    m = [[math.fsum(o * qi[a] * qi[b] for o, qi in zip(omega, q)) for b in range(p)] for a in range(p)]
    t = [back_substitute(r, [m[a][b] for a in range(p)]) for b in range(p)]   # columns of R^(-1) M
    rows = [back_substitute(r, [t[b][a] for b in range(p)]) for a in range(p)]  # rows of (R^(-1) M) R^(-T)
    return [[rows[a][b] for b in range(p)] for a in range(p)]


def hc_covariance(x: list, y: list, kind: str = "HC3") -> HCFit:
    """Least squares fit with the heteroscedasticity-consistent covariance of the given kind.

    Cost: Theta(n p^2) time, Theta(n p) space.
    """
    if kind not in KINDS:
        raise ValueError("kind must be one of " + ", ".join(KINDS))
    n = len(x)
    if len(y) != n:
        raise ValueError("x and y must have the same length")
    r, c = householder_r(x, y)  # @line L1
    p = len(r)
    if n <= p:
        raise ValueError("need n > p")
    b = back_substitute(r, c[:p])  # @line L2
    e = [yi - math.fsum(a * bb for a, bb in zip(xi, b)) for xi, yi in zip(x, y)]  # @line L3
    q = [forward_substitute_rt(r, xi) for xi in x]  # @line L4
    h = [math.fsum(t * t for t in qi) for qi in q]  # @line L4
    if kind == "HC0":  # @line L5
        omega = [ei * ei for ei in e]
    elif kind == "HC1":
        omega = [ei * ei * n / (n - p) for ei in e]
    elif kind == "HC2":
        if max(h) >= 1.0 - 1e-12:
            raise ValueError("a leverage equals 1; HC2 and HC3 are undefined")
        omega = [ei * ei / (1.0 - hi) for ei, hi in zip(e, h)]
    else:
        if max(h) >= 1.0 - 1e-12:
            raise ValueError("a leverage equals 1; HC2 and HC3 are undefined")
        omega = [ei * ei / (1.0 - hi) ** 2 for ei, hi in zip(e, h)]
    cov = sandwich(r, q, omega)  # @line L6
    se = [math.sqrt(max(cov[j][j], 0.0)) for j in range(p)]  # @line L7
    return HCFit(b, cov, se, e, h, n - p)  # @line L8


def confidence_intervals(fit: HCFit, level: float = 0.95) -> list:
    """b_j +- t_(n-p, (1 + level)/2) se_j. The level is only approximate: HC inference is asymptotic."""
    qt = t_ppf(0.5 + level / 2.0, fit.df)
    return [(bj - qt * s, bj + qt * s) for bj, s in zip(fit.b, fit.se)]
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_heteroscedasticity_consistent_standard_errors.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/heteroscedasticity-consistent-standard-errors/. The authors are listed in prov/PTWW7S.jsonl.

import math
import random
from fractions import Fraction

import pytest

from heteroscedasticity_consistent_standard_errors import KINDS, confidence_intervals, hc_covariance

EX_X = [[1, v] for v in [1, 2, 3, 4, 10]]
EX_Y = [1, 3, 2, 5, 14]


def solve(a, b):
    k = len(a)
    m = [[Fraction(v) for v in row] + [Fraction(b[i])] for i, row in enumerate(a)]
    for c in range(k):
        piv = next(r for r in range(c, k) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        for r in range(k):
            if r != c and m[r][c] != 0:
                f = m[r][c] / m[c][c]
                m[r] = [u - f * v for u, v in zip(m[r], m[c])]
    return [m[i][k] / m[i][i] for i in range(k)]


def inverse(a):
    n = len(a)
    cols = [solve(a, [int(i == j) for i in range(n)]) for j in range(n)]
    return [[cols[j][i] for j in range(n)] for i in range(n)]


def gram(x):
    p = len(x[0])
    return [[sum(Fraction(r[i]) * r[j] for r in x) for j in range(p)] for i in range(p)]


def direct(x, y, kind):
    """(X^T X)^(-1) X^T diag(omega) X (X^T X)^(-1) with explicit matrices in exact arithmetic."""
    n, p = len(x), len(x[0])
    gi = inverse(gram(x))
    b = solve(gram(x), [sum(Fraction(r[i]) * v for r, v in zip(x, y)) for i in range(p)])
    e = [v - sum(Fraction(a) * c for a, c in zip(r, b)) for r, v in zip(x, y)]
    h = [sum(Fraction(r[i]) * gi[i][j] * r[j] for i in range(p) for j in range(p)) for r in x]
    factor = {"HC0": lambda hi: 1, "HC1": lambda hi: Fraction(n, n - p),
              "HC2": lambda hi: 1 / (1 - hi), "HC3": lambda hi: 1 / (1 - hi) ** 2}[kind]
    omega = [ei * ei * factor(hi) for ei, hi in zip(e, h)]
    meat = [[sum(o * r[i] * r[j] for o, r in zip(omega, x)) for j in range(p)] for i in range(p)]
    v = [[sum(gi[i][k] * meat[k][l] * gi[l][j] for k in range(p) for l in range(p)) for j in range(p)]
         for i in range(p)]
    return b, e, h, v


def test_page_example_exact():
    b, e, h, _ = direct(EX_X, EX_Y, "HC0")
    assert b == [Fraction(-21, 25), Fraction(73, 50)]
    assert e == [Fraction(19, 50), Fraction(23, 25), Fraction(-77, 50), 0, Fraction(6, 25)]
    assert h == [Fraction(19, 50), Fraction(7, 25), Fraction(11, 50), Fraction(1, 5), Fraction(23, 25)]
    want_se = {"HC0": 0.060433, "HC1": 0.078019, "HC2": 0.119597, "HC3": 0.367592}
    for kind in KINDS:
        v = direct(EX_X, EX_Y, kind)[3]
        fit = hc_covariance(EX_X, EX_Y, kind)
        for i in range(2):
            assert fit.cov[i] == pytest.approx([float(t) for t in v[i]], rel=1e-10, abs=1e-14)
        assert fit.se[1] == pytest.approx(want_se[kind], abs=1e-6)


def test_matches_direct_matrices_on_random_designs_exact():
    rng = random.Random(8)
    done = 0
    while done < 10:
        n, p = rng.randint(6, 10), 3
        x = [[1, rng.randint(-4, 4), rng.randint(0, 6)] for _ in range(n)]
        y = [rng.randint(-9, 9) for _ in range(n)]
        try:
            ref = {k: direct(x, y, k) for k in KINDS}
        except (StopIteration, ZeroDivisionError):
            continue  # singular design or a leverage of 1
        for kind in KINDS:
            fit = hc_covariance(x, y, kind)
            assert fit.leverage == pytest.approx([float(t) for t in ref[kind][2]], abs=1e-12)
            for i in range(p):
                assert fit.cov[i] == pytest.approx([float(t) for t in ref[kind][3][i]], rel=1e-9, abs=1e-12)
        done += 1


def test_hc3_is_the_sum_of_squared_leave_one_out_changes_exact():
    """b_(i) - b = -(X^T X)^(-1) x_i e_i / (1 - h_ii), so HC3 = sum_i (b_(i) - b)(b_(i) - b)^T."""
    rng = random.Random(9)
    for _ in range(5):
        n = 8
        x = [[1, rng.randint(-5, 5), rng.randint(-5, 5)] for _ in range(n)]
        y = [rng.randint(-9, 9) for _ in range(n)]
        try:
            b, _, _, hc3 = direct(x, y, "HC3")
            drops = [solve(gram(x[:i] + x[i + 1:]),
                           [sum(Fraction(r[j]) * v for r, v in zip(x[:i] + x[i + 1:], y[:i] + y[i + 1:])) for j in range(3)])
                     for i in range(n)]
        except (StopIteration, ZeroDivisionError):
            continue
        d = [[bi - bb for bi, bb in zip(di, b)] for di in drops]
        s = [[sum(t[i] * t[j] for t in d) for j in range(3)] for i in range(3)]
        assert s == hc3
        # The jackknife variance centers at the mean of the b_(i): ((n - 1)/n)(HC3 - n dbar dbar^T).
        dbar = [sum(t[i] for t in d) / n for i in range(3)]
        jack = [[Fraction(n - 1, n) * sum((t[i] - dbar[i]) * (t[j] - dbar[j]) for t in d) for j in range(3)]
                for i in range(3)]
        assert jack == [[Fraction(n - 1, n) * (hc3[i][j] - n * dbar[i] * dbar[j]) for j in range(3)] for i in range(3)]


def test_expected_values_under_equal_variances_exact():
    """With Cov(e) = I: E e_i^2 = 1 - h_ii, so E[HC2] = (X^T X)^(-1) exactly and E[HC0] is smaller."""
    x = EX_X
    n, p = len(x), 2
    gi = inverse(gram(x))
    hat = [[sum(Fraction(x[a][i]) * gi[i][j] * x[c][j] for i in range(p) for j in range(p)) for c in range(n)]
           for a in range(n)]
    m = [[int(a == c) - hat[a][c] for c in range(n)] for a in range(n)]
    ee = [sum(m[a][c] ** 2 for c in range(n)) for a in range(n)]  # diag of (I - H) I (I - H)^T
    assert ee == [1 - hat[a][a] for a in range(n)]

    def expected(factor):
        meat = [[sum(ee[a] * factor(hat[a][a]) * x[a][i] * x[a][j] for a in range(n)) for j in range(p)] for i in range(p)]
        return [[sum(gi[i][k] * meat[k][l] * gi[l][j] for k in range(p) for l in range(p)) for j in range(p)] for i in range(p)]

    assert expected(lambda h: 1 / (1 - h)) == gi
    hc0 = expected(lambda h: 1)
    assert all(hc0[j][j] < gi[j][j] for j in range(p))


def test_bad_inputs():
    with pytest.raises(ValueError):
        hc_covariance(EX_X, EX_Y, "HC9")
    x = [[1, 0], [1, 0], [1, 0], [1, 1]]  # the last point has leverage 1
    with pytest.raises(ValueError):
        hc_covariance(x, [1, 2, 3, 4], "HC3")
    # HC0 still works, but the point with leverage 1 has residual 0 and adds nothing:
    # slope = y_4 - mean(y_1..y_3), and only the first three residuals (-1, 0, 1) enter, each with weight 1/9.
    assert hc_covariance(x, [1, 2, 3, 4], "HC0").cov[1][1] == pytest.approx(2.0 / 9.0)


def test_coverage_measured():
    """Errors with sd 0.5 x and lognormal x, n = 25. Measured coverage with r = 2000 was
    HC0 0.858, HC1 0.867, HC2 0.889, HC3 0.912 and 0.767 for the usual standard error.
    Here r = 800 (4 SE about 0.04): HC3 must be at least 0.87 and the usual one at most 0.81."""
    rng = random.Random(20261114)
    n, r = 25, 800
    xs = [math.exp(rng.gauss(0.0, 1.0)) for _ in range(n)]
    x = [[1.0, v] for v in xs]
    xb = sum(xs) / n
    sxx = sum((v - xb) ** 2 for v in xs)
    hit3 = hit0 = hit_naive = 0
    for _ in range(r):
        y = [1.0 + v + rng.gauss(0.0, 0.5 * v) for v in xs]
        f3 = hc_covariance(x, y, "HC3")
        lo, hi = confidence_intervals(f3)[1]
        hit3 += lo <= 1.0 <= hi
        f0 = hc_covariance(x, y, "HC0")
        lo, hi = confidence_intervals(f0)[1]
        hit0 += lo <= 1.0 <= hi
        se = math.sqrt(sum(t * t for t in f3.residuals) / (n - 2) / sxx)
        q = (hi - f0.b[1]) / f0.se[1]  # the same t quantile
        hit_naive += abs(f3.b[1] - 1.0) <= q * se
    assert hit3 >= hit0  # HC3 dominates HC0 entrywise in its weights, so its intervals contain those of HC0
    assert hit3 / r >= 0.87
    assert hit_naive / r <= 0.81

History

Eicker (1963, 1967) proved the consistency of the estimator for least squares with unequal variances, and Huber (1967) gave the general sandwich covariance of an M-estimate under a wrong model in the same Berkeley Symposium volume. White (1980) derived the estimator again for econometric models with random regressors, together with a direct test for heteroscedasticity, and it spread quickly in applied work. MacKinnon and White (1985) studied the small sample behavior and proposed the HC1, HC2 and jackknife versions; the closed form now called HC3 approximates their jackknife. Long and Ervin (2000) made HC3 the usual recommendation for small samples.

References

  1. F. Eicker, Limit theorems for regressions with unequal and dependent errors, Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1, University of California Press, 1967, pp. 59 to 82, The whole paper (consistency of the least squares covariance estimate built from squared residuals under unequal error variances)
  2. P. J. Huber, The behavior of maximum likelihood estimates under nonstandard conditions, Proceedings of the Fifth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1, University of California Press, 1967, pp. 221 to 233, The whole paper (the asymptotic covariance A^(-1) B A^(-T) of an M-estimate when the model is wrong)
  3. Halbert White, A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity, Econometrica 48(4), 1980, pp. 817 to 838, The whole paper (the estimator HC0 for least squares, its consistency, and the direct test)
  4. James G. MacKinnon and Halbert White, Some heteroskedasticity-consistent covariance matrix estimators with improved finite sample properties, Journal of Econometrics 29(3), 1985, pp. 305 to 325, The whole paper (HC1, HC2, the jackknife estimator and their small sample behavior)
  5. J. Scott Long and Laurie H. Ervin, Using heteroscedasticity consistent standard errors in the linear regression model, The American Statistician 54(3), 2000, pp. 217 to 224, The whole paper (a simulation study of HC0 to HC3 with the advice to use HC3 for samples of 250 or fewer)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example