Algorithmcore
Breusch-Pagan test
Also called Koenker-Bassett test.
Tests for heteroscedasticity by regressing the squared residuals on the predictors; n times the R-squared of that regression is chi-squared under the null.
- Time
- Θ(n (p^2 + q^2)) worst · best
- Space
- Θ(n (p + q)) extra
- Where
- n = the number of observations; p = the number of columns of X, with p < n; q = the number of variance variables
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Trevor S. Breusch, Adrian R. Pagan, Roger Koenker, 1979
The Breusch-Pagan test checks whether the error variance of a linear regression depends on chosen variables . It fits the model by ordinary least squares, regresses the squared residuals on , and rejects constant variance when that auxiliary regression explains much. The original statistic of Breusch and Pagan (1979) is half the explained sum of squares of ; it is the score test under normal errors, and it is too liberal when the errors have heavy tails. Koenker's studentized form, of the same regression, keeps its level without normality and is the one most software uses by default; some programs call this form the Koenker-Bassett test. Both are referred to a chi-squared law with degrees of freedom, and with normal errors a Monte Carlo p-value for the given design is exact.
In plain words
After fitting a line, look at how big the misses are. If the misses tend to be larger where some variable is large, the noise is not constant, and the usual standard errors are wrong. The test makes this precise: it fits a second line that tries to predict the squared misses from the chosen variables. If that second line predicts them clearly better than a flat line would, the test reports that the noise level changes. The original version assumes bell-shaped noise and raises false alarms when the noise has heavy tails. Koenker's version fixes this and is the safer default.
The problem
Model. with a fixed real matrix of rank (the intercept is one of the columns), independent errors with mean 0 and for a positive function that need not be known, and the variance variables. Often is the row without the intercept. With the matrix of rows , of rank :
Hypotheses. : , so the variance is constant; : .
Statistics. With the residuals , , , and ESS, TSS and the explained and total sums of squares and the coefficient of determination of the regression of on :
The is the same for and for , so is also of the regression of on .
Null distribution. Under , when the errors are normal, and when they are independent and identically distributed with a finite fourth moment. Neither law is exact for finite . Reject at level when the statistic is at least the upper point ; the p-value is . With normal errors the null law depends only on and , so simulating standard normal errors for the given design gives the exact Monte Carlo p-value .
Power. The test has power against variances that change with in any smooth way, since does not enter the statistic. It has little power against variance patterns that do not follow the chosen , and little power in small samples.
The algorithm
BREUSCH-PAGAN(X[1..n, 1..p], y[1..n], z[1..n, 1..q])- 1
e ← residuals of y on X by Householder least squares - 2
σ̂² ← Σᵢ eᵢ² / n; gᵢ ← eᵢ² / σ̂² for all i ▷ the mean of g is exactly 1 - 3
(R_Z, d) ← Householder QR of Z = [1, z] applied to g ▷ d = Q_Zᵀ g - 4
ESS ← d₁² + … + d_q²; TSS ← Σᵢ (gᵢ - 1)² ▷ d₀ belongs to the constant - 5
LM_BP ← ESS / 2 - 6
LM_K ← n · ESS / TSS - 7
p_BP ← P(χ²_q ≥ LM_BP); p_K ← P(χ²_q ≥ LM_K) - 8
return (LM_BP, LM_K, p_BP, p_K)
Line L4 reads the explained sum of squares off the transformed response, as on the F-test for nested linear models page, so the auxiliary fit needs no normal equations and no second pass. Lines L1 to L6 do not depend on how was scaled, which gives the exact Monte Carlo version: repeat lines L1 to L6 for samples of standard normal and count how often the simulated statistic is at least the observed one.
Example
Take for , , an intercept and , so . The residuals are
which fan out as grows. The results are:
| statistic | value | chi-squared p-value | Monte Carlo p-value, |
|---|---|---|---|
| 5.1931 | 0.0227 | 0.0077 | |
| 6.8880 | 0.0087 | 0.0020 |
The ratio , where is the variance of the . Both tests reject at the 5% level. With the chi-squared p-values are far from the exact Monte Carlo ones for normal errors (seed 7 for random.Random), which shows how rough the asymptotic law is in small samples.
Measured size and power. With , one regressor drawn once from the uniform law on , , and the 5% level:
| errors | |||
|---|---|---|---|
| , | 4000 | 0.048 | 0.054 |
| , | 4000 | 0.147 | 0.046 |
| times | 2000 | 0.861 | 0.805 |
| times | 2000 | 0.877 | 0.658 |
With heavy-tailed errors the original test rejects three times too often; the higher power of in the last row is not usable, because its size is wrong. The Monte Carlo standard error of a size near 0.05 with is 0.0034.
Correctness
The proof shows four exact facts. Lines L2 to L6 compute and of the auxiliary regression. Under normal errors with , the score test of is exactly for every , which explains why the test does not need the form of the variance function. The identity
shows that the two statistics differ by an estimate of , where is the kurtosis of the errors; it is 1 for normal errors and 4 for errors. Finally, the residuals of are and both statistics are unchanged, so under normal errors their null law does not depend on or and the Monte Carlo test has exact size.
The chi-squared limits are cited, not proved: Breusch and Pagan (1979) for the normal case, from the general theory of the score test, and Koenker (1981) for the studentized form.
Proof: The Breusch-Pagan statistic is half the explained sum of squares of the auxiliary regression, equals the score test, is a rescaled Koenker statistic, and has a null law free of b and sigma under normal errorsfull
The arithmetic is exact. is a fixed real matrix of rank , are the least squares residuals with , , , and is the matrix with rows and rank . Let be the projection onto the columns of ,
Lemma 1 (lines L2 to L6). exactly. If is the Householder factorization of line L3 and , then (counting the entries of from 0), and . So lines L5 and L6 return and .
Proof. . For the second claim, the residual sum of squares of on all of is , and on its first column (the constant) it is , because the first columns of span the first columns of ; this is the argument of the proof on the F-test for nested linear models page. The difference is , and it equals , since the regression on the constant alone fits and is orthogonal to .
Lemma 2 (the score test). Let independently with , where is any positive differentiable function with at the null value. The score test statistic of , with the expected information, is , for every such .
Proof. The log-likelihood is up to a constant. Under the maximum likelihood estimates are of least squares and . Write and . At the restricted estimates the scores are
Under with normal errors, and the mixed second derivatives in and have mean 0, because they contain or . So the expected information is block diagonal with block . The score statistic is the quadratic form of the score in the inverse information:
The factor cancels, so does not matter. Since is a column of and , , and the quadratic form is .
Lemma 3 (Breusch-Pagan versus Koenker). With ,
Proof. , so , and .
Under normal errors , and the two statistics agree to first order. For errors with kurtosis , , so if Koenker's statistic has a limit, the Breusch-Pagan statistic has the limit and its size is wrong unless .
Lemma 4 (the null law is free of b and sigma). Under with , the law of depends only on and . So the Monte Carlo p-value from samples with standard normal errors gives a test of exact size when is an integer.
Proof. For any and , the residuals of are . Then becomes , and , , and both statistics do not change. Under , with , so the statistics are the same functions of for every and . The values are then exchangeable and have no ties with probability 1, so the rank of is uniform on and .
What is cited, not proved. Under with normal errors and conditions on and , in law (Breusch and Pagan 1979, the general theory of the score test). Under with independent identically distributed errors with a finite fourth moment, (Koenker 1981). Neither limit is proved here, and the size and power figures on the page are measured.
Termination. Lines L1 and L3 are Householder factorizations with and steps, and the other lines are finite sums: operations.
Complexity
The two Householder factorizations cost and , and the rest is . The total is time and extra space. The Monte Carlo p-value multiplies this by ; the QR factors of and could be reused, since only changes.
Properties
- Invariance. Both statistics are unchanged by and by any nonsingular linear change of the columns of that keeps the constant.
- No variance function needed. The score test is the same for every link , so the test detects and equally.
- Score test. It needs only the fit under . The likelihood ratio and Wald tests for a specified need the fit under and agree with it to first order.
- Non-normal errors. keeps its asymptotic level under any error law with a finite fourth moment; does not.
- Uses only . The test does not look at the sign of the residuals, so it is not built to detect a wrong mean model. A wrong mean model can still make it reject, since a missing term enters the squared residuals in a way that may follow .
Variants and improvements
- White's test. Take as the predictors, their squares and their cross products, and use . This detects variance patterns that are quadratic in the predictors, at the cost of degrees of freedom.
- F form. Some software reports the F test for the auxiliary regression, , which is asymptotically equivalent to .
- Exact Monte Carlo test. If normal errors are a fair assumption, simulate the statistic for the given and as above; this removes the error of the chi-squared approximation, which is large for small .
- Quantile-based tests. Koenker and Bassett (1982) compare slopes of quantile regressions at different quantiles; equal slopes mean the spread does not change with . These tests do not need a finite fourth moment.
- Goldfeld and Quandt. Splitting the data by the size of one variable and comparing the residual variances of the two halves by an F ratio gives an exact test under normal errors, but only for a variance that is monotone in that variable.
When to use it
Use the Koenker form as a diagnostic when unequal variances would change the analysis: to decide whether to model the variance with weighted least squares, or to show that a variance model is needed. Choose from knowledge of the problem, usually the predictors or the fitted values. Do not use it as a gate for the choice of standard errors: heteroscedasticity-consistent standard errors cost little and are valid whether or not the test rejects, and a pretest changes the level of the later tests.
Pitfalls
- The original statistic with heavy tails. assumes normal errors. With errors its 5% test rejected 15% of the time in the table above. Use unless normality is credible.
- Not rejecting does not prove constant variance. With small the power is low, and the test sees only patterns that follow the chosen .
- Small samples. The chi-squared approximation can be poor for below about 30, as the example shows; the Monte Carlo version helps when the errors are normal.
- Misspecified mean. A missing nonlinear term or interaction shows up as large residuals in some region and can make the test reject although the variance is constant. Check the mean model first.
- Outliers. One large residual can dominate and the auxiliary regression; inspect studentized residuals.
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/breusch-pagan-test/. The authors are listed in prov/R9XRKX.jsonl.
"""The Breusch-Pagan test and Koenker's studentized form, by two Householder QR factorizations.
Fit y on X by least squares, set g_i = e_i^2 / sigma2 with sigma2 = sum e_i^2 / n, and regress g on
Z = [1, z_i] (q variables after the intercept). With d = Q_Z^T g, the explained sum of squares is
ESS = d[1]^2 + ... + d[q]^2 (0-based), and the total sum of squares about the mean 1 is
TSS = sum (g_i - 1)^2. Then
Breusch-Pagan: LM = ESS / 2
Koenker: LM = n ESS / TSS = n R^2
and both are referred to chi-square with q degrees of freedom. The code is in this file and not in
breusch_pagan_test.py, because tools treat a file whose name ends in _test.py as a test file.
"""
import math
import random
from typing import NamedTuple
from stdist import chi2_sf
RANK_TOL = 1e-12
class BPResult(NamedTuple):
lm_bp: float # ESS / 2, the original Breusch-Pagan statistic
lm_koenker: float # n R^2 of the auxiliary regression
q: int # degrees of freedom
p_bp: float # chi-square upper tail of lm_bp
p_koenker: float # chi-square upper tail of lm_koenker
def householder_qr(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 residuals(x: list, y: list) -> list:
"""Least squares residuals of y on the columns of x."""
r, c = householder_qr(x, y)
p = len(r)
b = [0.0] * p
for i in range(p - 1, -1, -1):
b[i] = (c[i] - math.fsum(r[i][k] * b[k] for k in range(i + 1, p))) / r[i][i]
return [yi - math.fsum(a * bb for a, bb in zip(xi, b)) for xi, yi in zip(x, y)]
def statistics_from_residuals(e: list, z: list) -> tuple[float, float]:
"""(LM_BP, LM_Koenker) from the residuals e and the variables z (rows without the intercept)."""
n = len(e)
q = len(z[0])
sigma2 = math.fsum(t * t for t in e) / n # @line L2
if sigma2 == 0.0:
raise ValueError("all residuals are 0")
g = [t * t / sigma2 for t in e] # @line L2
_, d = householder_qr([[1.0] + list(zi) for zi in z], g) # @line L3
ess = math.fsum(d[j] ** 2 for j in range(1, q + 1)) # @line L4
tss = math.fsum((gi - 1.0) ** 2 for gi in g) # @line L4
if tss == 0.0:
raise ValueError("all squared residuals are equal")
return ess / 2.0, n * ess / tss # @line L5 @line L6
def breusch_pagan(x: list, y: list, z: list | None = None) -> BPResult:
"""Breusch-Pagan and Koenker tests of constant variance against variance depending on z.
x: rows of the design (with an intercept column); z: rows of the variance variables, without
an intercept. If z is None, the columns of x other than a constant column are used.
Cost: Theta(n (p^2 + q^2)) time, Theta(n (p + q)) space.
"""
n = len(x)
if len(y) != n:
raise ValueError("x and y must have the same length")
if z is None:
keep = [j for j in range(len(x[0])) if len({row[j] for row in x}) > 1]
z = [[row[j] for j in keep] for row in x]
if len(z) != n or not z or len(z[0]) == 0:
raise ValueError("z must have n rows and at least one column")
q = len(z[0])
if n <= q + 1 or n <= len(x[0]):
raise ValueError("too few observations")
e = residuals(x, y) # @line L1
lm_bp, lm_k = statistics_from_residuals(e, z)
return BPResult(lm_bp, lm_k, q, chi2_sf(lm_bp, q), chi2_sf(lm_k, q)) # @line L7 @line L8
def monte_carlo_p_values(x: list, y: list, z: list, reps: int = 999, seed: int = 1) -> tuple[float, float]:
"""Monte Carlo p-values (1 + #{T* >= T}) / (1 + reps) for both statistics under normal errors.
Under H0 with normal errors the residuals are (I - H) eps and both statistics are unchanged by
scaling, so their law depends only on X and Z: the Monte Carlo test has exact size.
"""
obs = statistics_from_residuals(residuals(x, y), z)
rng = random.Random(seed)
n = len(x)
count = [0, 0]
for _ in range(reps):
sim = statistics_from_residuals(residuals(x, [rng.gauss(0.0, 1.0) for _ in range(n)]), z)
for k in range(2):
count[k] += sim[k] >= obs[k] - 1e-12 * abs(obs[k])
return (1 + count[0]) / (1 + reps), (1 + count[1]) / (1 + reps)
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)
breusch_pagan_test.py 11 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/breusch-pagan-test/. The authors are listed in prov/R9XRKX.jsonl.
"""Entry point named after the slug. The code lives in breusch_pagan_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from breusch_pagan_core import (
BPResult, breusch_pagan, householder_qr, monte_carlo_p_values, residuals, statistics_from_residuals,
)
__all__ = ["BPResult", "breusch_pagan", "householder_qr", "monte_carlo_p_values", "residuals",
"statistics_from_residuals"]
test_breusch_pagan_test.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/breusch-pagan-test/. The authors are listed in prov/R9XRKX.jsonl.
import math
import random
from fractions import Fraction
import pytest
from breusch_pagan_test import breusch_pagan, monte_carlo_p_values
from stdist import chi2_ppf
EX_XS = list(range(1, 11))
EX_X = [[1, v] for v in EX_XS]
EX_Y = [Fraction(v) for v in ["3.2", "3.8", "5.5", "5.5", "8", "7", "11", "8", "14", "9"]]
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 ls_fit(x, y):
"""Exact least squares by the normal equations: coefficients and residuals."""
p = len(x[0])
gram = [[sum(Fraction(r[i]) * r[j] for r in x) for j in range(p)] for i in range(p)]
b = solve(gram, [sum(Fraction(r[i]) * v for r, v in zip(x, y)) for i in range(p)])
return b, [Fraction(v) - sum(Fraction(a) * c for a, c in zip(r, b)) for r, v in zip(x, y)]
def exact_statistics(x, y, z):
"""The auxiliary regression done directly: returns (LM_BP, LM_K, sigma2, v) as Fractions."""
n = len(x)
_, e = ls_fit(x, y)
sigma2 = sum(t * t for t in e) / n
g = [t * t / sigma2 for t in e]
zz = [[1] + list(r) for r in z]
_, u = ls_fit(zz, g)
gbar = sum(g) / n
tss = sum((t - gbar) ** 2 for t in g)
ess = tss - sum(t * t for t in u)
v = sum((t * t - sigma2) ** 2 for t in e) / n
return ess / 2, n * ess / tss, sigma2, v, e, g
def test_page_example_exact():
lm_bp, lm_k, sigma2, v, e, g = exact_statistics(EX_X, EX_Y, [[t] for t in EX_XS])
assert sum(g) == len(g) # the mean of g is exactly 1 because sigma2 is RSS / n
res = breusch_pagan(EX_X, [float(t) for t in EX_Y])
assert res.lm_bp == pytest.approx(float(lm_bp), rel=1e-10)
assert res.lm_koenker == pytest.approx(float(lm_k), rel=1e-10)
assert res.lm_bp == pytest.approx(5.1931, abs=1e-4)
assert res.lm_koenker == pytest.approx(6.8880, abs=1e-4)
assert res.p_bp == pytest.approx(0.02268, abs=1e-5)
assert res.p_koenker == pytest.approx(0.008678, abs=1e-6)
assert float(v / (2 * sigma2 ** 2)) == pytest.approx(0.75394, abs=1e-5)
def test_identities_exact():
"""LM_BP = LM_K v / (2 sigma2^2); LM_K = n R^2 for e^2 itself; LM_BP is the score form."""
rng = random.Random(21)
for _ in range(8):
n = rng.randint(8, 14)
x = [[1, rng.randint(-5, 5), rng.randint(0, 4)] for _ in range(n)]
z = [[r[1], r[1] * r[1]] for r in x]
y = [rng.randint(-9, 9) for _ in range(n)]
try:
lm_bp, lm_k, sigma2, v, e, g = exact_statistics(x, y, z)
except (StopIteration, ZeroDivisionError):
continue
assert lm_bp == lm_k * v / (2 * sigma2 * sigma2)
# R^2 does not change when the response e_i^2 is divided by sigma2.
sq = [t * t for t in e]
_, u = ls_fit([[1] + r for r in z], sq)
mean = sum(sq) / n
assert lm_k == n * (1 - sum(t * t for t in u) / sum((t - mean) ** 2 for t in sq))
# Score form: (1/2) (g - 1)^T Z (Z^T Z)^(-1) Z^T (g - 1), with Z including the intercept.
zz = [[1] + r for r in z]
w = [t - 1 for t in g]
coef = solve([[sum(Fraction(r[i]) * r[j] for r in zz) for j in range(3)] for i in range(3)],
[sum(r[i] * t for r, t in zip(zz, w)) for i in range(3)])
assert lm_bp == sum(c * sum(r[i] * t for r, t in zip(zz, w)) for i, c in enumerate(coef)) / 2
res = breusch_pagan(x, y, z)
assert (res.lm_bp, res.lm_koenker) == pytest.approx((float(lm_bp), float(lm_k)), rel=1e-9)
def test_invariant_to_b_and_sigma_exact():
"""The residuals of a y + X c are a e, and both statistics are unchanged by the scale a."""
z = [[t] for t in EX_XS]
base = exact_statistics(EX_X, EX_Y, z)[:2]
for a, c in ((Fraction(-3), (5, 2)), (Fraction(1, 7), (-1, 4))):
y2 = [a * yi + c[0] + c[1] * xi for yi, xi in zip(EX_Y, EX_XS)]
assert exact_statistics(EX_X, y2, z)[:2] == base
def test_bad_inputs():
with pytest.raises(ValueError):
breusch_pagan(EX_X, [1.0] * 9)
with pytest.raises(ValueError):
breusch_pagan(EX_X, [2.0 * t for t in EX_XS]) # a perfect fit: all residuals are 0
def test_monte_carlo_p_value_of_example_measured():
"""With 9999 normal samples the Monte Carlo p-values were 0.0077 and 0.0020; here B = 1999
(4 SE about 0.008 and 0.004)."""
p_bp, p_k = monte_carlo_p_values(EX_X, [float(t) for t in EX_Y], [[t] for t in EX_XS], reps=1999, seed=7)
assert abs(p_bp - 0.0077) <= 0.008
assert abs(p_k - 0.0020) <= 0.004
def run(rng, r, n, heavy, scale):
xs = [rng.uniform(0.0, 1.0) for _ in range(n)]
x = [[1.0, a] for a in xs]
crit = chi2_ppf(0.95, 1)
rej_bp = rej_k = 0
for _ in range(r):
if heavy:
eps = [rng.gauss(0.0, 1.0) / math.sqrt(sum(rng.gauss(0.0, 1.0) ** 2 for _ in range(5)) / 5)
for _ in range(n)]
else:
eps = [rng.gauss(0.0, 1.0) for _ in range(n)]
y = [1.0 + 2.0 * a + t * scale(a) for a, t in zip(xs, eps)]
res = breusch_pagan(x, y)
rej_bp += res.lm_bp >= crit
rej_k += res.lm_koenker >= crit
return rej_bp / r, rej_k / r
def test_size_and_power_measured():
"""n = 50, one uniform regressor, 5% level. Measured with r = 4000 under H0: normal errors
BP 0.048 and Koenker 0.054; t_5 errors BP 0.147 and Koenker 0.046. Power with sd 0.5 + 2x
(r = 2000): normal 0.861 and 0.805. Here r = 1500 under H0 (4 SE about 0.023) and r = 400 for power."""
flat = lambda a: 1.0
bp, k = run(random.Random(1), 1500, 50, False, flat)
assert abs(bp - 0.05) <= 0.023 and abs(k - 0.05) <= 0.023
bp, k = run(random.Random(2), 1500, 50, True, flat)
assert bp >= 0.10 and abs(k - 0.05) <= 0.023
bp, k = run(random.Random(3), 400, 50, False, lambda a: 0.5 + 2.0 * a)
assert bp >= 0.78 and k >= 0.72
History
Breusch and Pagan (1979) derived the score test for a general variance and noted that it does not depend on , which made it simple to apply. White (1980) gave his direct test with the squares and products of the predictors as part of his paper on the heteroscedasticity-consistent covariance. Koenker (1981) showed that the Breusch-Pagan statistic is sensitive to the kurtosis of the errors and proposed the studentized version, and Koenker and Bassett (1982) developed tests based on regression quantiles.
References
- T. S. Breusch and A. R. Pagan, A simple test for heteroscedasticity and random coefficient variation, Econometrica 47(5), 1979, pp. 1287 to 1294, The whole paper (the score test for a variance h(z_i^T alpha), computed as half the explained sum of squares of the regression of e_i^2 / sigma^2 on z_i)
- Roger Koenker, A note on studentizing a test for heteroscedasticity, Journal of Econometrics 17(1), 1981, pp. 107 to 112, The whole paper (the sensitivity of the Breusch-Pagan test to the kurtosis of the errors and the studentized n R^2 version)
- Roger Koenker and Gilbert Bassett Jr., Robust tests for heteroscedasticity based on regression quantiles, Econometrica 50(1), 1982, pp. 43 to 61, The whole paper (tests of heteroscedasticity from regression quantiles that do not assume normal errors)
- 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 direct test, which is n R^2 of the regression of e_i^2 on the predictors, their squares and their products)
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 R9XRKX Edit this page History Report an error Markdown