Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 ziz_i. It fits the model by ordinary least squares, regresses the squared residuals on ziz_i, 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 ei2/σ^2e_i^2/\hat\sigma^2; it is the score test under normal errors, and it is too liberal when the errors have heavy tails. Koenker's studentized form, nR2nR^2 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 qq 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. 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 columns), independent errors with mean 0 and Var⁡(εi)=h(α0+zi⊤α)\operatorname{Var}(\varepsilon_i) = h(\alpha_0 + z_i^\top\alpha) for a positive function hh that need not be known, and zi∈Rqz_i \in \mathbb R^q the variance variables. Often ziz_i is the row xix_i without the intercept. With ZZ the n×(q+1)n \times (q + 1) matrix of rows (1,zi⊤)(1, z_i^\top), of rank q+1<nq + 1 < n:

Hypotheses. H0H_0: α=0\alpha = 0, so the variance is constant; H1H_1: α≠0\alpha \ne 0.

Statistics. With the residuals eie_i, σ^2=1n∑iei2\hat\sigma^2 = \frac1n\sum_ie_i^2, gi=ei2/σ^2g_i = e_i^2/\hat\sigma^2, and ESS, TSS and R2R^2 the explained and total sums of squares and the coefficient of determination of the regression of gg on ZZ:

LMBP=12ESS,LMK=nR2=n ESSTSS.\mathrm{LM}_{\mathrm{BP}} = \tfrac12\mathrm{ESS}, \qquad \mathrm{LM}_{\mathrm K} = nR^2 = \frac{n\,\mathrm{ESS}}{\mathrm{TSS}}.

The R2R^2 is the same for ei2e_i^2 and for gig_i, so LMK\mathrm{LM}_{\mathrm K} is also nR2nR^2 of the regression of ei2e_i^2 on ZZ.

Null distribution. Under H0H_0, LMBP→χq2\mathrm{LM}_{\mathrm{BP}} \to \chi^2_q when the errors are normal, and LMK→χq2\mathrm{LM}_{\mathrm K} \to \chi^2_q when they are independent and identically distributed with a finite fourth moment. Neither law is exact for finite nn. Reject at level α\alpha when the statistic is at least the upper α\alpha point χq,1−α2\chi^2_{q, 1-\alpha}; the p-value is P(χq2≥LM)P(\chi^2_q \ge \mathrm{LM}). With normal errors the null law depends only on XX and ZZ, so simulating standard normal errors for the given design gives the exact Monte Carlo p-value (1+#{LM∗≥LM})/(1+B)(1 + \#\{\mathrm{LM}^* \ge \mathrm{LM}\})/(1 + B).

Power. The test has power against variances that change with ziz_i in any smooth way, since hh does not enter the statistic. It has little power against variance patterns that do not follow the chosen ziz_i, and little power in small samples.

The algorithm

  1. BREUSCH-PAGAN(X[1..n, 1..p], y[1..n], z[1..n, 1..q])
  2. 1e ← residuals of y on X by Householder least squares
  3. 2σ̂² ← Σᵢ eᵢ² / n; gᵢ ← eᵢ² / σ̂² for all i ▷ the mean of g is exactly 1
  4. 3(R_Z, d) ← Householder QR of Z = [1, z] applied to g ▷ d = Q_Zᵀ g
  5. 4ESS ← d₁² + … + d_q²; TSS ← Σᵢ (gᵢ - 1)² ▷ d₀ belongs to the constant
  6. 5LM_BP ← ESS / 2
  7. 6LM_K ← n · ESS / TSS
  8. 7p_BP ← P(χ²_q ≥ LM_BP); p_K ← P(χ²_q ≥ LM_K)
  9. 8return (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 ee was scaled, which gives the exact Monte Carlo version: repeat lines L1 to L6 for BB samples of standard normal yy and count how often the simulated statistic is at least the observed one.

Example

Take xi=ix_i = i for i=1,…,10i = 1, \dots, 10, y=(3.2,3.8,5.5,5.5,8,7,11,8,14,9)y = (3.2, 3.8, 5.5, 5.5, 8, 7, 11, 8, 14, 9), an intercept and zi=xiz_i = x_i, so q=1q = 1. The residuals are

e=(−0.165,−0.484,0.297,−0.622,0.959,−0.959,2.122,−1.797,3.284,−2.635),e = (-0.165, -0.484, 0.297, -0.622, 0.959, -0.959, 2.122, -1.797, 3.284, -2.635),

which fan out as xx grows. The results are:

statistic value chi-squared p-value Monte Carlo p-value, B=9999B = 9999
LMBP\mathrm{LM}_{\mathrm{BP}} 5.1931 0.0227 0.0077
LMK\mathrm{LM}_{\mathrm K} 6.8880 0.0087 0.0020

The ratio LMBP/LMK=v^/(2σ^4)=0.754\mathrm{LM}_{\mathrm{BP}}/\mathrm{LM}_{\mathrm K} = \hat v/(2\hat\sigma^4) = 0.754, where v^\hat v is the variance of the ei2e_i^2. Both tests reject at the 5% level. With n=10n = 10 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 n=50n = 50, one regressor drawn once from the uniform law on [0,1][0, 1], zi=xiz_i = x_i, and the 5% level:

errors rr LMBP\mathrm{LM}_{\mathrm{BP}} LMK\mathrm{LM}_{\mathrm K}
N(0,1)N(0, 1), H0H_0 4000 0.048 0.054
t5t_5, H0H_0 4000 0.147 0.046
N(0,1)N(0, 1) times 0.5+2xi0.5 + 2x_i 2000 0.861 0.805
t5t_5 times 0.5+2xi0.5 + 2x_i 2000 0.877 0.658

With heavy-tailed errors the original test rejects three times too often; the higher power of LMBP\mathrm{LM}_{\mathrm{BP}} in the last row is not usable, because its size is wrong. The Monte Carlo standard error of a size near 0.05 with r=4000r = 4000 is 0.0034.

Correctness

The proof shows four exact facts. Lines L2 to L6 compute ESS/2\mathrm{ESS}/2 and n ESS/TSSn\,\mathrm{ESS}/\mathrm{TSS} of the auxiliary regression. Under normal errors with σi2=h(α0+zi⊤α)\sigma_i^2 = h(\alpha_0 + z_i^\top\alpha), the score test of α=0\alpha = 0 is exactly LMBP\mathrm{LM}_{\mathrm{BP}} for every hh, which explains why the test does not need the form of the variance function. The identity

LMBP=v^2σ^4 LMK,v^=1n∑i(ei2−σ^2)2,\mathrm{LM}_{\mathrm{BP}} = \frac{\hat v}{2\hat\sigma^4}\,\mathrm{LM}_{\mathrm K}, \qquad \hat v = \frac1n\sum_i(e_i^2 - \hat\sigma^2)^2,

shows that the two statistics differ by an estimate of (κ−1)/2(\kappa - 1)/2, where κ\kappa is the kurtosis of the errors; it is 1 for normal errors and 4 for t5t_5 errors. Finally, the residuals of ay+Xcay + Xc are aeae and both statistics are unchanged, so under normal errors their null law does not depend on bb or σ\sigma 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. XX is a fixed real n×pn \times p matrix of rank p<np < n, e=(I−H)ye = (I - H)y are the least squares residuals with H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top, σ^2=1n∑iei2>0\hat\sigma^2 = \frac1n\sum_ie_i^2 > 0, gi=ei2/σ^2g_i = e_i^2/\hat\sigma^2, and ZZ is the n×(q+1)n \times (q + 1) matrix with rows (1,zi⊤)(1, z_i^\top) and rank q+1<nq + 1 < n. Let PZP_Z be the projection onto the columns of ZZ,

ESS=∥PZg−gˉ1∥2,TSS=∥g−gˉ1∥2,LMBP=12ESS,LMK=n ESS/TSS=nR2.\mathrm{ESS} = \lVert P_Zg - \bar g\mathbf 1\rVert^2, \quad \mathrm{TSS} = \lVert g - \bar g\mathbf 1\rVert^2, \quad \mathrm{LM}_{\mathrm{BP}} = \tfrac12\mathrm{ESS}, \quad \mathrm{LM}_{\mathrm K} = n\,\mathrm{ESS}/\mathrm{TSS} = nR^2.

Lemma 1 (lines L2 to L6). gˉ=1\bar g = 1 exactly. If QZ⊤Z=(RZ0)Q_Z^\top Z = \binom{R_Z}{0} is the Householder factorization of line L3 and d=QZ⊤gd = Q_Z^\top g, then ESS=d12+⋯+dq2\mathrm{ESS} = d_1^2 + \dots + d_q^2 (counting the entries of dd from 0), and TSS=∑i(gi−1)2\mathrm{TSS} = \sum_i(g_i - 1)^2. So lines L5 and L6 return LMBP\mathrm{LM}_{\mathrm{BP}} and LMK\mathrm{LM}_{\mathrm K}.

Proof. ∑igi=∑iei2/σ^2=n\sum_ig_i = \sum_ie_i^2/\hat\sigma^2 = n. For the second claim, the residual sum of squares of gg on all of ZZ is ∑j>qdj2\sum_{j > q}d_j^2, and on its first column (the constant) it is ∑j≥1dj2\sum_{j \ge 1}d_j^2, because the first jj columns of QZQ_Z span the first jj columns of ZZ; this is the argument of the proof on the F-test for nested linear models page. The difference is d12+⋯+dq2d_1^2 + \dots + d_q^2, and it equals ESS\mathrm{ESS}, since the regression on the constant alone fits gˉ1\bar g\mathbf 1 and PZg−gˉ1P_Zg - \bar g\mathbf 1 is orthogonal to g−PZgg - P_Zg. □\square

Lemma 2 (the score test). Let yi∼N(xi⊤b,σi2)y_i \sim N(x_i^\top b, \sigma_i^2) independently with σi2=h(α0+zi⊤α)\sigma_i^2 = h(\alpha_0 + z_i^\top\alpha), where hh is any positive differentiable function with h′(α0)≠0h'(\alpha_0) \ne 0 at the null value. The score test statistic of H0:α=0H_0: \alpha = 0, with the expected information, is LMBP\mathrm{LM}_{\mathrm{BP}}, for every such hh.

Proof. The log-likelihood is ℓ=−12∑i[log⁡σi2+(yi−xi⊤b)2/σi2]\ell = -\frac12\sum_i\bigl[\log\sigma_i^2 + (y_i - x_i^\top b)^2/\sigma_i^2\bigr] up to a constant. Under H0H_0 the maximum likelihood estimates are b^\hat b of least squares and h(α^0)=σ^2h(\hat\alpha_0) = \hat\sigma^2. Write γ=(α0,α)\gamma = (\alpha_0, \alpha) and c=h′(α0)c = h'(\alpha_0). At the restricted estimates the scores are

∂ℓ∂b=X⊤eσ^2=0,∂ℓ∂γ=c2σ^2∑i(1,zi⊤)⊤(gi−1)=c2σ^2Z⊤(g−1).\frac{\partial\ell}{\partial b} = \frac{X^\top e}{\hat\sigma^2} = 0, \qquad \frac{\partial\ell}{\partial\gamma} = \frac{c}{2\hat\sigma^2}\sum_i(1, z_i^\top)^\top(g_i - 1) = \frac{c}{2\hat\sigma^2}Z^\top(g - \mathbf 1).

Under H0H_0 with normal errors, E[(εi2/σ2−1)2]=2\mathrm E[(\varepsilon_i^2/\sigma^2 - 1)^2] = 2 and the mixed second derivatives in bb and γ\gamma have mean 0, because they contain εi\varepsilon_i or εi3\varepsilon_i^3. So the expected information is block diagonal with γ\gamma block c22σ4Z⊤Z\frac{c^2}{2\sigma^4}Z^\top Z. The score statistic is the quadratic form of the score in the inverse information:

LM=c24σ^4(g−1)⊤Z⋅2σ^4c2(Z⊤Z)−1⋅Z⊤(g−1)=12(g−1)⊤PZ(g−1).\mathrm{LM} = \frac{c^2}{4\hat\sigma^4}(g - \mathbf 1)^\top Z\cdot\frac{2\hat\sigma^4}{c^2}(Z^\top Z)^{-1}\cdot Z^\top(g - \mathbf 1) = \tfrac12(g - \mathbf 1)^\top P_Z(g - \mathbf 1).

The factor cc cancels, so hh does not matter. Since 1\mathbf 1 is a column of ZZ and gˉ=1\bar g = 1, PZ(g−1)=PZg−gˉ1P_Z(g - \mathbf 1) = P_Zg - \bar g\mathbf 1, and the quadratic form is ESS\mathrm{ESS}. □\square

Lemma 3 (Breusch-Pagan versus Koenker). With v^=1n∑i(ei2−σ^2)2\hat v = \frac1n\sum_i(e_i^2 - \hat\sigma^2)^2,

LMBP=v^2σ^4 LMK.\mathrm{LM}_{\mathrm{BP}} = \frac{\hat v}{2\hat\sigma^4}\,\mathrm{LM}_{\mathrm K}.

Proof. TSS=∑i(ei2/σ^2−1)2=nv^/σ^4\mathrm{TSS} = \sum_i(e_i^2/\hat\sigma^2 - 1)^2 = n\hat v/\hat\sigma^4, so ESS=LMK TSS/n=LMK v^/σ^4\mathrm{ESS} = \mathrm{LM}_{\mathrm K}\,\mathrm{TSS}/n = \mathrm{LM}_{\mathrm K}\,\hat v/\hat\sigma^4, and LMBP=ESS/2\mathrm{LM}_{\mathrm{BP}} = \mathrm{ESS}/2. □\square

Under normal errors v^/(2σ^4)→1\hat v/(2\hat\sigma^4) \to 1, and the two statistics agree to first order. For errors with kurtosis κ\kappa, v^/(2σ^4)→(κ−1)/2\hat v/(2\hat\sigma^4) \to (\kappa - 1)/2, so if Koenker's statistic has a χq2\chi^2_q limit, the Breusch-Pagan statistic has the limit κ−12χq2\frac{\kappa - 1}{2}\chi^2_q and its size is wrong unless κ=3\kappa = 3.

Lemma 4 (the null law is free of b and sigma). Under H0H_0 with ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2I), the law of (LMBP,LMK)(\mathrm{LM}_{\mathrm{BP}}, \mathrm{LM}_{\mathrm K}) depends only on XX and ZZ. So the Monte Carlo p-value (1+#{T∗≥T})/(1+B)(1 + \#\{T^* \ge T\})/(1 + B) from BB samples with standard normal errors gives a test of exact size α\alpha when α(B+1)\alpha(B + 1) is an integer.

Proof. For any a≠0a \ne 0 and c∈Rpc \in \mathbb R^p, the residuals of ay+Xcay + Xc are (I−H)(ay+Xc)=ae(I - H)(ay + Xc) = ae. Then σ^2\hat\sigma^2 becomes a2σ^2a^2\hat\sigma^2, and gg, ESS\mathrm{ESS}, TSS\mathrm{TSS} and both statistics do not change. Under H0H_0, y=Xb+σε0y = Xb + \sigma\varepsilon_0 with ε0∼N(0,I)\varepsilon_0 \sim N(0, I), so the statistics are the same functions of ε0\varepsilon_0 for every bb and σ\sigma. The B+1B + 1 values T,T1∗,…,TB∗T, T_1^*, \dots, T_B^* are then exchangeable and have no ties with probability 1, so the rank of TT is uniform on {1,…,B+1}\{1, \dots, B + 1\} and P((1+#{T∗≥T})/(1+B)≤α)=αP\bigl((1 + \#\{T^* \ge T\})/(1 + B) \le \alpha\bigr) = \alpha. □\square

What is cited, not proved. Under H0H_0 with normal errors and conditions on XX and ZZ, LMBP→χq2\mathrm{LM}_{\mathrm{BP}} \to \chi^2_q in law (Breusch and Pagan 1979, the general theory of the score test). Under H0H_0 with independent identically distributed errors with a finite fourth moment, LMK→χq2\mathrm{LM}_{\mathrm K} \to \chi^2_q (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 pp and q+1q + 1 steps, and the other lines are finite sums: Θ(n(p2+q2))\Theta(n(p^2 + q^2)) operations.

Complexity

The two Householder factorizations cost Θ(np2)\Theta(np^2) and Θ(nq2)\Theta(nq^2), and the rest is Θ(n)\Theta(n). The total is Θ(n(p2+q2))\Theta(n(p^2 + q^2)) time and Θ(n(p+q))\Theta(n(p + q)) extra space. The Monte Carlo p-value multiplies this by BB; the QR factors of XX and ZZ could be reused, since only yy changes.

Properties

  • Invariance. Both statistics are unchanged by y→ay+Xcy \to ay + Xc and by any nonsingular linear change of the columns of ZZ that keeps the constant.
  • No variance function needed. The score test is the same for every link hh, so the test detects σi2=σ2exp⁡(γzi)\sigma_i^2 = \sigma^2\exp(\gamma z_i) and σi2=σ2(1+γzi)2\sigma_i^2 = \sigma^2(1 + \gamma z_i)^2 equally.
  • Score test. It needs only the fit under H0H_0. The likelihood ratio and Wald tests for a specified hh need the fit under H1H_1 and agree with it to first order.
  • Non-normal errors. LMK\mathrm{LM}_{\mathrm K} keeps its asymptotic level under any error law with a finite fourth moment; LMBP\mathrm{LM}_{\mathrm{BP}} does not.
  • Uses only e2e^2. 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 ziz_i.

Variants and improvements

  • White's test. Take ziz_i as the predictors, their squares and their cross products, and use nR2nR^2. This detects variance patterns that are quadratic in the predictors, at the cost of q=O(p2)q = O(p^2) degrees of freedom.
  • F form. Some software reports the F test for the auxiliary regression, F=R2/q(1−R2)/(n−q−1)F = \frac{R^2/q}{(1 - R^2)/(n - q - 1)}, which is asymptotically equivalent to nR2/qnR^2/q.
  • Exact Monte Carlo test. If normal errors are a fair assumption, simulate the statistic for the given XX and ZZ as above; this removes the error of the chi-squared approximation, which is large for small nn.
  • Quantile-based tests. Koenker and Bassett (1982) compare slopes of quantile regressions at different quantiles; equal slopes mean the spread does not change with xx. 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 ziz_i 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. LMBP\mathrm{LM}_{\mathrm{BP}} assumes normal errors. With t5t_5 errors its 5% test rejected 15% of the time in the table above. Use LMK\mathrm{LM}_{\mathrm K} unless normality is credible.
  • Not rejecting does not prove constant variance. With small nn the power is low, and the test sees only patterns that follow the chosen ziz_i.
  • Small samples. The chi-squared approximation can be poor for nn 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 ∑ei2\sum e_i^2 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.

breusch_pagan_core.pyI0RawGitHub
# 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 h(zi⊤α)h(z_i^\top\alpha) and noted that it does not depend on hh, 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 nR2nR^2 version, and Koenker and Bassett (1982) developed tests based on regression quantiles.

References

  1. 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)
  2. 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)
  3. 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)
  4. 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.

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