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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , the true covariance of is the sandwich with , not . The HC estimators put a squared residual, possibly corrected for leverage, in place of each unknown . 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. with a fixed real matrix of rank (the intercept is one of the columns), and independent errors with and , unknown and possibly all different. Then
Input. , and the choice of version.
Output. and the estimate with , where , is the leverage, and
| version | idea | |
|---|---|---|
| HC0 | White's original | |
| HC1 | degrees of freedom correction | |
| HC2 | unbiased when the variances are equal | |
| HC3 | close to the jackknife |
The algorithm
HC-COVARIANCE(X[1..n, 1..p], y[1..n], version)- 1
(R, c) ← Householder QR of X, applied to y ▷ X = Q₁R, c = Qᵀy - 2
b̂ ← solve R b = c[1..p] - 3
eᵢ ← yᵢ - xᵢᵀ b̂ for all i - 4
qᵢ ← R⁻ᵀ xᵢ; hᵢᵢ ← ‖qᵢ‖² for all i ▷ qᵢᵀ is row i of Q₁ = X R⁻¹ - 5
ωᵢ ← eᵢ² · (1, n/(n - p), 1/(1 - hᵢᵢ) or 1/(1 - hᵢᵢ)²) ▷ HC0, HC1, HC2, HC3 - 6
V ← R⁻¹ (Σᵢ ωᵢ qᵢ qᵢᵀ) R⁻ᵀ - 7
seⱼ ← √Vⱼⱼ for j = 1..p - 8
return (b̂, V, se)
Line L4 gets each row of by one triangular solve, so the leverages come out without the hat matrix. Line L6 is the sandwich in factored form: , and . A interval for is ; the implementation takes as the upper quantile of , which is a convention, since the theory only gives a normal limit. A Wald test of uses , as on the Wald test page.
Example
Take and with an intercept. Exact arithmetic gives and
| 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, | 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 by . 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 , drawn once from a lognormal law, and , 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 , with . If the errors have equal variance , then , so HC2 is exactly unbiased for , HC0 is biased down and HC3 is biased up. By the Sherman-Morrison formula, deleting row moves the estimate by , 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 (leverages that go to 0 and a nonsingular limit of ), is consistent for the limit of , 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. is a fixed real matrix of rank with rows , , , and with diagonal . The target of each estimator is
with (HC0), (HC1), (HC2) or (HC3).
Lemma 1 (lines L1 to L4). Line L1 gives an upper triangular nonsingular with , and line L2 gives . The vectors of line L4 are the rows of , which has orthonormal columns, and .
Proof. The Householder argument (Lemma 1 of the proof on the weighted least squares page, with unit weights) gives with orthogonal and , so with the first columns of , and . Row of is . Then , whose entry is .
Lemma 2 (lines L5 to L7 compute the sandwich). .
Proof. . So , and .
So the algorithm returns the HC0 to HC3 matrices exactly, and it never forms an matrix.
Lemma 3 (HC2 is unbiased when the variances are equal). If and , then and .
Proof. , so , because is symmetric and idempotent. Its diagonal gives , so and . The sandwich is linear in , so .
Under the same assumption, , which is smaller than 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 be the least squares estimate without row , and for all . Then
Proof. Deleting row changes to and to . By the Sherman-Morrison formula, with , , since . Then
Summing the outer products gives .
The jackknife variance of MacKinnon and White (1985) centers the at their mean instead of at and multiplies by ; with and their mean, it equals , 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 (the leverages go to 0 and converges to a nonsingular limit), converges in probability to the limit of 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 Householder steps, lines L2 to L4 are triangular solves of size , line L5 is scalar operations, and lines L6 and L7 are finite sums: operations in total.
Complexity
The QR costs flops, the triangular solves of line L4 cost , the sum of line L6 costs , and the two triangular sandwiches cost . The total is time, the order of the fit itself, and extra space. Forming the hat matrix would cost time and space and is never needed.
Properties
- No variance model. The estimate is consistent whatever the are, as long as the errors are independent and the leverages become small.
- Order of the versions. HC1 equals HC0 times , and since , the matrices satisfy HC0 HC2 HC3 in the Loewner order; the same holds for each standard error.
- Equivariance. Replacing by for a nonsingular maps to , 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 and the meat is , so HC0 is the general sandwich covariance applied to this case.
- Leverage-one points. If then , HC0 ignores row , 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 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 by a sum over groups of : 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 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 , 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 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 and is wrong under heteroscedasticity. Use the Wald form with , 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PTWW7S Edit this page History Report an error Markdown