Algorithmcore
Generalized least squares
Also called Aitken estimator, feasible generalized least squares.
Least squares after whitening by the error covariance, b = (X^T V^(-1) X)^(-1) X^T V^(-1) y. It is best linear unbiased for known V; with V estimated it is feasible GLS.
- Time
- Θ(n^3) worst · best
- Space
- Θ(n^2) extra
- Counts
- flops n^3/3 + (p + 1) n^2 + 2n p^2 + O(p^3) worst
- 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
- Alexander C. Aitken, 1935
Generalized least squares (GLS) fits when the errors are correlated or have unequal variances with a known pattern, . It minimizes , and the solution is , the Aitken estimator. The computation never forms : it factors , multiplies the model by so that the new errors are uncorrelated with equal variance, and runs ordinary least squares on the result. For a known this is the best linear unbiased estimator. When is estimated from the data, the same steps give feasible GLS.
In plain words
Ordinary least squares treats every observation as a fresh, independent piece of information with the same noise. Often that is false: measurements taken one after the other share part of their noise, and measurements from the same unit are alike. Correlated points carry less information than their number suggests, and noisy points should count less. Generalized least squares fixes both at once. It changes the data with a fixed linear map so that the noise of the changed data is plain, independent and equal in size, then fits the ordinary way. For a series where each error carries part of the previous one, the map is simple: subtract a fraction of the previous point from each point.
The problem
Model. with a fixed real matrix of rank (the intercept is one of the columns, as on the hat matrix page), and
Here positive definite means for every . A diagonal is the case of weighted least squares, with .
Input. , and .
Output. , the whitened residual sum of squares with , the estimate and the covariance estimate .
The algorithm
GENERALIZED-LEAST-SQUARES(X[1..n, 1..p], y[1..n], V[1..n, 1..n])- 1
L ← Cholesky factor of V ▷ V = L Lᵀ, L lower triangular; fails if V is not positive definite - 2
X̃ ← L⁻¹X; ỹ ← L⁻¹y ▷ p + 1 forward substitutions - 3
(R, c) ← Householder QR of X̃, applied to ỹ ▷ Qᵀ X̃ = (R; 0), c = Qᵀ ỹ - 4
b̂ ← solve R b = c[1..p] by back substitution - 5
RSS_V ← c[p+1]² + ... + c[n]² ▷ = eᵀ V⁻¹ e - 6
s² ← RSS_V / (n - p) - 7
C ← s² · R⁻¹ R⁻ᵀ ▷ = s² (Xᵀ V⁻¹ X)⁻¹ - 8
return (b̂, RSS_V, s², C)
Line L2 is the whitening. Since , the whitened model has uncorrelated errors of equal variance, and . Lines L3 to L7 are the QR solution of ordinary least squares on the whitened rows, and inherit its numerical stability. Inverting explicitly and then forming would cost as much and lose accuracy.
Structured . For errors from a stationary AR(1) process, , the inverse Cholesky factor is known in closed form: multiplies the first row by and replaces row by row minus times row . This is the Prais-Winsten transformation, and lines L1 and L2 then cost . For a general stationary autoregressive model the Levinson-Durbin recursion or a Kalman filter gives the whitening in per column, and Toeplitz methods (Toeplitz system solving) handle a general stationary covariance.
Example
Take , , the model , and AR(1) errors with , so and the whitening is exact in rationals. Line L2 gives:
| whitened intercept column | whitened | whitened | |
|---|---|---|---|
| 1 | 4/5 | 4/5 | 8/5 |
| 2 | 2/5 | 7/5 | 9/5 |
| 3 | 2/5 | 9/5 | 16/5 |
| 4 | 2/5 | 11/5 | 1 |
| 5 | 2/5 | 13/5 | 18/5 |
Ordinary least squares on this table gives
against from ordinary least squares on the raw data. The whitened residual sum of squares is , so with , , and the 95% interval for the slope is . Five correlated points hold little information about a slope.
Measured behavior. With , and stationary normal AR(1) errors with , samples from random.Random(20261114) gave these coverages of the nominal 95% t interval for the slope:
| method | coverage |
|---|---|
| GLS with the true | 0.946 |
| OLS with the usual standard error | 0.684 |
| two-step Prais-Winsten feasible GLS | 0.823 |
The GLS interval is exact by the theory below; the measured value is within Monte Carlo error. The variance of the OLS slope was 1.085 times that of the GLS slope (theory 1.084), so for a linear trend OLS loses little efficiency; the damage is in its standard error, which assumes independence and is far too small. Feasible GLS undercovers at because is biased toward 0 and its sampling error is ignored.
Correctness
Line L1 succeeds because is positive definite. By the whitening identity above, lines L3 and L4 minimize , and the normal equations of the whitened problem are , so GLS equals OLS on whitened data. The whitened model satisfies the hypotheses of the Gauss-Markov theorem, and estimators linear in and in are the same class, so is unbiased with covariance and is best linear unbiased (Aitken's theorem). is unbiased for , and under normal errors the t intervals and F tests on the whitened model are exact. The proof also shows that the Prais-Winsten matrix is exactly for the AR(1) covariance, by the uniqueness of the Cholesky factor, and proves Kruskal's condition below.
Proof: Generalized least squares by Cholesky whitening computes the Aitken estimator, which is the best linear unbiased estimator for a known covariancefull
The arithmetic is exact. The model is with a fixed real matrix of rank , and , where is a known symmetric positive definite matrix and is unknown.
Lemma 1 (the factor). Line L1 succeeds and returns the unique lower triangular with positive diagonal and .
Proof. This is the existence and uniqueness of the Cholesky decomposition of a positive definite matrix. In the column loop, the pivot is the ratio of the leading principal minors of orders and of , which are positive, so the square root exists and every division is by a positive number. Each entry of is forced by the equation once the earlier columns are known, which gives uniqueness. If some , is not positive definite and the code raises an error.
Lemma 2 (the whitened model). Let , and , as line L2 computes by forward substitution. Then with , and .
Proof. Multiply the model by . Then , and is nonsingular, so it keeps the rank of .
Lemma 3 (GLS equals OLS on whitened data). Lines L3 and L4 return the unique minimizer of , which is
and line L5 returns the minimum value with .
Proof. , so . Lines L3 and L4 are the QR solution of ordinary least squares for : with and , , which is smallest exactly at , with minimum (the same argument as Lemma 1 of the proof on the weighted least squares page). The minimizer solves the normal equations , and and .
Lemma 4 (Aitken: unbiased and best). , , and for every linear unbiased estimator the difference is positive semidefinite.
Proof. By Lemma 2 the whitened model satisfies the hypotheses of the Gauss-Markov theorem, and by Lemma 3 is its least squares estimate. So is unbiased with covariance , and it has the smallest covariance among estimators that are linear in and unbiased. An estimator equals , and equals , so the estimators linear in and linear in are the same random vectors, and so are the unbiased ones.
Lemma 5 (variance estimate and exact intervals). from line L6 satisfies , and line L7 returns . If is normal, has the law.
Proof. In the whitened model has mean and covariance , so . . Under normality depends on only and on only; these are independent normal coordinates, , and the ratio is by definition.
Lemma 6 (the Prais-Winsten matrix is the inverse Cholesky factor of the AR(1) covariance). Let and . Let be the matrix with , and for , and zeros elsewhere. Then and , where is the Cholesky factor of .
Proof. is the covariance of a stationary AR(1) process with uncorrelated innovations of variance 1: then and . The vector has entries and for . The first has variance 1, the have variance 1, and for is uncorrelated with and with the other innovations, so . Hence . The matrix is lower triangular with positive diagonal, so is too, and by the uniqueness in Lemma 1, .
So for AR(1) errors line L2 is the Prais-Winsten transformation, and it costs instead of .
Lemma 7 (Kruskal: when OLS and GLS agree). The ordinary least squares estimate equals for every if and only if the column space of equals the column space of .
Proof. Let and , the OLS residual. Since is the unique solution of , OLS equals GLS at exactly when . If , then maps onto itself, so for some matrix , and because . Conversely, if for every , the columns of are orthogonal to , so ; both have dimension , so they are equal, and applying gives .
For example, the equicorrelated satisfies the condition whenever , since .
Termination. Line L1 is column steps of finite sums ( flops), line L2 is forward substitutions ( flops each), the QR of line L3 is Householder steps, and lines L4 to L7 are finite sums. So the algorithm stops after operations for a dense .
Complexity
For a dense , the Cholesky factor costs flops, the forward substitutions , the QR and the covariance : time and space for and . Structure changes this. A diagonal is weighted least squares at . AR(1) and banded with bandwidth cost . A block diagonal with blocks of size , as in repeated measures, costs .
Properties
- Best linear unbiased. For known , is the smallest covariance, in the Loewner order, among linear unbiased estimators. OLS is still unbiased under correlation, but its covariance is , not .
- Scale of does not matter. and give the same and the same covariance estimate.
- When OLS is already GLS. Kruskal (1968): OLS equals GLS for every exactly when the column space of equals that of . An equicorrelated with an intercept in is such a case, so a common shock shared by all observations does not change the estimate (but it does change which variances can be estimated).
- Residuals. The residuals are correlated even under the model. Diagnostics such as leverage and studentized residuals belong on the whitened scale .
Variants and improvements
- Feasible GLS. depends on a few unknown parameters. Estimate from OLS residuals, then run GLS with . For AR(1) errors, and the Prais-Winsten whitening give the two-step estimator of the implementation. Under regularity conditions feasible GLS has the same limiting distribution as GLS with the true ; in finite samples its reported standard errors are too small, as the table above shows.
- Cochrane-Orcutt. The older AR(1) method drops the first row and uses only the differences ; in practice it is iterated between and , and the iteration can stop at a local minimum. It loses one observation, which matters for short series and for trending regressors.
- Joint estimation. Maximum likelihood or restricted maximum likelihood estimates and together; for random effects this is the linear mixed model, whose fixed effects are GLS estimates given the variance components.
- Sandwich standard errors instead of GLS. Keep OLS and use heteroscedasticity-consistent or cluster-robust standard errors, which do not need but give up efficiency. Generalized estimating equations combine both: a working for efficiency and a sandwich variance that stays valid when the working is wrong.
When to use it
Use GLS when the error covariance is known up to a scale, or has a small parametric form that can be estimated well: serially correlated errors in a time series regression, a known measurement covariance in calibration, or blocks of correlated observations. Test for serial correlation first with the Durbin-Watson test or the Ljung-Box test on the OLS residuals. If the form of is in doubt, prefer OLS or feasible GLS with a robust sandwich variance.
Pitfalls
- Inverting . Forming explicitly is slower and less accurate than a Cholesky factor and two triangular solves.
- Feasible GLS treated as GLS. The standard errors from line L7 assume that is known. With an estimated they are too small in short series.
- A wrong . GLS with a wrong stays unbiased if the regressors are fixed, but it is no longer best, and is the wrong covariance. Use a sandwich variance unless the model for is well checked.
- Lagged dependent variables. If contains and the errors are autocorrelated, OLS and feasible GLS are both inconsistent; the regressors are correlated with the errors. The fixed- theory of this page does not apply.
- Strict exogeneity. With correlated errors, GLS uses future and past regressors to predict each error. It needs for all regressor values, not only those at time ; OLS needs less.
- Nearly singular . If is close to singular, the whitening amplifies rounding error, and the Cholesky factor may fail. Check the condition number of , or use a model with a nonsingular covariance.
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/generalized-least-squares/. The authors are listed in prov/A3NRM4.jsonl.
"""Generalized least squares with a known error covariance, by Cholesky whitening.
The model is y = X b + e with E[e] = 0 and Cov(e) = sigma^2 V, V known and
positive definite, sigma^2 unknown. With V = L L^T (Cholesky), the whitened
model L^(-1) y = L^(-1) X b + L^(-1) e has uncorrelated errors of variance
sigma^2, and ordinary least squares on it, done by Householder QR, gives
b-hat = (X^T V^(-1) X)^(-1) X^T V^(-1) y without forming V^(-1).
feasible_gls_ar1 is the two-step Prais-Winsten estimator for AR(1) errors:
rho is estimated from the OLS residuals and the exact AR(1) whitening is applied.
"""
import math
from typing import NamedTuple
from stdist import t_ppf
RANK_TOL = 1e-12
class GLSFit(NamedTuple):
b: list # the coefficient estimate, length p
rss: float # whitened residual sum of squares, e^T V^(-1) e
df: int # n - p
s2: float # rss / df, the estimate of sigma^2
cov: list # s2 (X^T V^(-1) X)^(-1), p x p
residuals: list # e = y - X b-hat, on the original scale
def cholesky(v: list) -> list:
"""The lower triangular L with positive diagonal and L L^T = V. Raises ValueError if V is not positive definite."""
n = len(v)
l = [[0.0] * n for _ in range(n)]
for j in range(n):
d = v[j][j] - math.fsum(l[j][k] ** 2 for k in range(j))
if not d > 0.0:
raise ValueError("V is not positive definite")
l[j][j] = math.sqrt(d)
for i in range(j + 1, n):
l[i][j] = (v[i][j] - math.fsum(l[i][k] * l[j][k] for k in range(j))) / l[j][j]
return l
def forward_substitute(l: list, b: list) -> list:
"""Solve L z = b for lower triangular nonsingular L."""
z = []
for i in range(len(l)):
z.append((b[i] - math.fsum(l[i][k] * z[k] for k in range(i))) / l[i][i])
return z
def householder_qr(a: list, ys: list) -> tuple[list, list]:
"""Householder QR of the n x p matrix a (rows), applied to each vector in ys.
Returns (R, cs) with R the p x p triangular factor and cs[k] = Q^T ys[k].
Raises ValueError if a has rank below p (relative tolerance RANK_TOL).
"""
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]
cs = [[float(v) for v in y] for y in ys]
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]
for c in cs:
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]
r = [[a[i][k] if k >= i else 0.0 for k in range(p)] for i in range(p)]
return r, cs
def back_substitute(r: list, c: list) -> list:
"""Solve R x = c for upper triangular nonsingular R."""
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 _ols_whitened(xw: list, yw: list, x: list, y: list) -> GLSFit:
rr, (c,) = householder_qr(xw, [yw])
p = len(rr)
b = back_substitute(rr, c[:p])
rss = math.fsum(v * v for v in c[p:])
df = len(xw) - p
s2 = rss / df if df > 0 else math.nan
cols = [back_substitute(rr, [1.0 if i == j else 0.0 for i in range(p)]) for j in range(p)]
# cols[k] is column k of R^(-1), so (R^(-1) R^(-T))_ij = sum_k cols[k][i] cols[k][j].
cov =[[s2 * math.fsum(cols[k][i] * cols[k][j] for k in range(p)) for j in range(p)]
for i in range(p)]
res = [y[i] - math.fsum(a * bb for a, bb in zip(x[i], b)) for i in range(len(x))]
return GLSFit(b, rss, df, s2, cov, res)
def generalized_least_squares(x: list, y: list, v: list) -> GLSFit:
"""Fit y = X b + e with Cov(e) = sigma^2 V for a known positive definite V.
Cost: n^3/3 flops for the Cholesky factor, n^2 p for the whitening and
2 n p^2 for the QR.
"""
n = len(x)
if len(y) != n or len(v) != n or any(len(row) != n for row in v):
raise ValueError("x, y and V must have matching sizes")
l = cholesky(v) # @line L1
cols = [forward_substitute(l, [row[j] for row in x]) for j in range(len(x[0]))] # @line L2
xw = [[c[i] for c in cols] for i in range(n)] # @line L2
yw = forward_substitute(l, y) # @line L2
rr, (c,) = householder_qr(xw, [yw]) # @line L3
p = len(rr)
b = back_substitute(rr, c[:p]) # @line L4
rss = math.fsum(t * t for t in c[p:]) # @line L5
df = n - p
s2 = rss / df if df > 0 else math.nan # @line L6
rinv_cols = [back_substitute(rr, [1.0 if i == j else 0.0 for i in range(p)]) for j in range(p)]
cov = [[s2 * math.fsum(rinv_cols[k][i] * rinv_cols[k][j] for k in range(p)) for j in range(p)]
for i in range(p)] # @line L7
res = [y[i] - math.fsum(a * bb for a, bb in zip(x[i], b)) for i in range(n)]
return GLSFit(b, rss, df, s2, cov, res) # @line L8
def confidence_intervals(fit: GLSFit, level: float = 0.95) -> list:
"""t intervals b_j +- t_(n-p, (1 + level)/2) se_j; exact under normal errors and the right V."""
q = t_ppf(0.5 + level / 2.0, fit.df)
return [(bj - q * math.sqrt(fit.cov[j][j]), bj + q * math.sqrt(fit.cov[j][j]))
for j, bj in enumerate(fit.b)]
def ar1_covariance(n: int, rho: float) -> list:
"""V with V_ts = rho^|t-s| / (1 - rho^2): the covariance of a stationary AR(1) with unit innovation variance."""
if not -1.0 < rho < 1.0:
raise ValueError("need |rho| < 1")
return [[rho ** abs(t - s) / (1.0 - rho * rho) for s in range(n)] for t in range(n)]
def prais_winsten(rows: list, rho: float) -> list:
"""Apply the AR(1) whitening P to a list of rows (vectors or scalars per time point).
Row 1 is multiplied by sqrt(1 - rho^2); row t >= 2 becomes row_t - rho row_(t-1).
P equals L^(-1) for the Cholesky factor L of ar1_covariance(n, rho).
"""
scalar = not isinstance(rows[0], (list, tuple))
rs = [[r] for r in rows] if scalar else [list(r) for r in rows]
out = [[math.sqrt(1.0 - rho * rho) * v for v in rs[0]]]
for t in range(1, len(rs)):
out.append([a - rho * b for a, b in zip(rs[t], rs[t - 1])])
return [r[0] for r in out] if scalar else out
def feasible_gls_ar1(x: list, y: list) -> tuple[GLSFit, float]:
"""Two-step Prais-Winsten feasible GLS for AR(1) errors.
Step 1: OLS residuals e and rho-hat = sum e_t e_(t-1) / sum e_t^2.
Step 2: OLS on the rows whitened with rho-hat. Returns (fit, rho-hat).
The reported covariance treats rho-hat as known, so it is only asymptotically valid.
"""
n = len(x)
ols = _ols_whitened(x, y, x, y)
e = ols.residuals
rho = math.fsum(e[t] * e[t - 1] for t in range(1, n)) / math.fsum(t * t for t in e)
rho = max(-0.999, min(0.999, rho))
fit = _ols_whitened(prais_winsten(x, rho), prais_winsten(y, rho), x, y)
return fit, rho
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_generalized_least_squares.py 196 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-least-squares/. The authors are listed in prov/A3NRM4.jsonl.
import math
import random
from fractions import Fraction
import pytest
from generalized_least_squares import (
ar1_covariance, cholesky, confidence_intervals, feasible_gls_ar1,
forward_substitute, generalized_least_squares, prais_winsten,
)
def solve_exact(a, b):
"""Gauss-Jordan elimination in exact rational arithmetic."""
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_exact(a):
n = len(a)
cols = [solve_exact(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 matmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))]
for i in range(len(a))]
def transpose(a):
return [list(r) for r in zip(*a)]
def ols_exact(x, y):
p = len(x[0])
g = [[sum(Fraction(r[i]) * r[j] for r in x) for j in range(p)] for i in range(p)]
return solve_exact(g, [sum(Fraction(r[i]) * v for r, v in zip(x, y)) for i in range(p)])
def gls_formula_exact(x, y, v):
"""(X^T V^(-1) X)^(-1) X^T V^(-1) y with V^(-1) formed explicitly, in Fractions."""
vi = inverse_exact(v)
xt = transpose(x)
a = matmul(matmul(xt, vi), x)
rhs = [row[0] for row in matmul(matmul(xt, vi), [[v] for v in y])]
return solve_exact(a, rhs)
def ar1_whitener_exact(n, rho, root):
"""The Prais-Winsten matrix P with sqrt(1 - rho^2) = root given exactly."""
p = [[Fraction(0)] * n for _ in range(n)]
p[0][0] = root
for i in range(1, n):
p[i][i] = Fraction(1)
p[i][i - 1] = -rho
return p
def test_page_example_exact():
t, y = [1, 2, 3, 4, 5], [2, 3, 5, 4, 6]
x = [[1, v] for v in t]
p = ar1_whitener_exact(5, Fraction(3, 5), Fraction(4, 5))
xw, yw = matmul(p, x), [r[0] for r in matmul(p, [[v] for v in y])]
assert [r[1] for r in xw] == [Fraction(4, 5), Fraction(7, 5), Fraction(9, 5), Fraction(11, 5), Fraction(13, 5)]
assert yw == [Fraction(8, 5), Fraction(9, 5), Fraction(16, 5), Fraction(1), Fraction(18, 5)]
b = ols_exact(xw, yw)
assert b == [Fraction(40, 37), Fraction(36, 37)]
assert ols_exact(x, y) == [Fraction(13, 10), Fraction(9, 10)]
rss = sum((v - r[0] * b[0] - r[1] * b[1]) ** 2 for r, v in zip(xw, yw))
assert rss == Fraction(3622, 925)
v = [[Fraction(3, 5) ** abs(i - j) / Fraction(16, 25) for j in range(5)] for i in range(5)]
assert gls_formula_exact(x, y, v) == b
fit = generalized_least_squares(x, y, ar1_covariance(5, 0.6))
assert fit.b == pytest.approx([40 / 37, 36 / 37], abs=1e-12)
assert fit.rss == pytest.approx(3622 / 925, rel=1e-12)
assert fit.df == 3
def test_whitening_equals_the_formula_exact():
"""V = L L^T with a random rational L: OLS on L^(-1) X, L^(-1) y equals the GLS formula exactly."""
rng = random.Random(7)
done = 0
while done < 12:
n, p = rng.randint(4, 7), rng.randint(1, 3)
x = [[1] + [rng.randint(-4, 4) for _ in range(p - 1)] for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
l = [[Fraction(rng.randint(-3, 3), rng.randint(1, 3)) if j < i else
(Fraction(rng.randint(1, 4), rng.randint(1, 2)) if j == i else Fraction(0))
for j in range(n)] for i in range(n)]
v = matmul(l, transpose(l))
li = inverse_exact(l)
xw, yw = matmul(li, x), [r[0] for r in matmul(li, [[t] for t in y])]
try:
exact = ols_exact(xw, yw)
except StopIteration:
continue # singular design
assert exact == gls_formula_exact(x, y, v)
fit = generalized_least_squares(x, y, [[float(t) for t in r] for r in v])
assert fit.b == pytest.approx([float(t) for t in exact], rel=1e-8, abs=1e-8)
done += 1
def test_prais_winsten_is_the_inverse_cholesky_factor():
"""P V P^T = I exactly for rho = 3/5, and numerically P = L^(-1) for L = cholesky(V)."""
n, rho = 6, Fraction(3, 5)
v = [[rho ** abs(i - j) / (1 - rho * rho) for j in range(n)] for i in range(n)]
p = ar1_whitener_exact(n, rho, Fraction(4, 5))
assert matmul(matmul(p, v), transpose(p)) == [[int(i == j) for j in range(n)] for i in range(n)]
l = cholesky(ar1_covariance(n, 0.6))
for j in range(n):
col = forward_substitute(l, [float(i == j) for i in range(n)]) # column j of L^(-1)
assert col == pytest.approx([float(p[i][j]) for i in range(n)], abs=1e-12)
rows = [[1.0, float(t)] for t in range(n)]
got = prais_winsten(rows, 0.6)
for i in range(n):
want = [float(sum(p[i][k] * Fraction(rows[k][j]) for k in range(n))) for j in range(2)]
assert got[i] == pytest.approx(want, abs=1e-12)
def test_diagonal_v_gives_weighted_least_squares():
x = [[1, t] for t in [1, 2, 3, 4, 5]]
y = [2, 5, 5, 9, 9]
v = [[Fraction(t * t) if i == j else Fraction(0) for j, _ in enumerate(x)] for i, t in enumerate([1, 2, 3, 4, 5])]
b = gls_formula_exact(x, y, v)
assert b == [Fraction(281, 1894), Fraction(14967, 7576)] # the example of the WLS page
fit = generalized_least_squares(x, y, [[float(t) for t in r] for r in v])
assert fit.b == pytest.approx([float(t) for t in b], abs=1e-12)
def test_equicorrelation_with_intercept_gives_ols_exact():
"""Kruskal's condition: V = I + c 1 1^T maps col(X) into itself when X has an intercept."""
rng = random.Random(3)
for c in [Fraction(1, 2), Fraction(3), Fraction(-1, 10)]:
n = 6
x = [[1, rng.randint(-5, 5), rng.randint(-5, 5)] for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
v = [[int(i == j) + c for j in range(n)] for i in range(n)]
assert gls_formula_exact(x, y, v) == ols_exact(x, y)
def test_bad_inputs():
with pytest.raises(ValueError):
cholesky([[1.0, 2.0], [2.0, 1.0]])
with pytest.raises(ValueError):
generalized_least_squares([[1, 1], [1, 2]], [1, 2, 3], [[1.0, 0.0], [0.0, 1.0]])
with pytest.raises(ValueError):
ar1_covariance(4, 1.0)
def test_coverage_under_ar1_measured():
"""AR(1) errors with rho = 0.6, n = 30. The GLS t interval with the true V is exact, so its
coverage is 0.95 up to Monte Carlo error: r = 800 gives 4 SE of 0.031. The OLS interval with
the usual standard error is far below 0.95 (about 0.68 measured)."""
rng = random.Random(20261114)
n, rho, r = 30, 0.6, 800
x = [[1.0, float(i + 1)] for i in range(n)]
v = ar1_covariance(n, rho)
eye = [[float(i == j) for j in range(n)] for i in range(n)]
hit_g = hit_o = 0
for _ in range(r):
u = [rng.gauss(0.0, 1.0) / math.sqrt(1.0 - rho * rho)]
for _ in range(n - 1):
u.append(rho * u[-1] + rng.gauss(0.0, 1.0))
y = [1.0 + 0.2 * row[1] + ui for row, ui in zip(x, u)]
lo, hi = confidence_intervals(generalized_least_squares(x, y, v))[1]
hit_g += lo <= 0.2 <= hi
lo, hi = confidence_intervals(generalized_least_squares(x, y, eye))[1]
hit_o += lo <= 0.2 <= hi
assert abs(hit_g / r - 0.95) < 0.031
assert hit_o / r < 0.85
def test_feasible_gls_estimates_rho():
"""A long series: rho-hat has standard error about sqrt((1 - rho^2)/n) = 0.04; the tolerance is 4 SE."""
rng = random.Random(5)
n, rho = 400, 0.6
x = [[1.0, t / n] for t in range(n)]
u = [rng.gauss(0.0, 1.0) / math.sqrt(1.0 - rho * rho)]
for _ in range(n - 1):
u.append(rho * u[-1] + rng.gauss(0.0, 1.0))
y = [2.0 - row[1] + ui for row, ui in zip(x, u)]
fit, rho_hat = feasible_gls_ar1(x, y)
assert abs(rho_hat - rho) < 0.16
exact = prais_winsten(x, rho_hat)
assert len(exact) == n and fit.df == n - 2
History
Aitken (1935) proved that the estimator weighted by the inverse covariance is the minimum variance linear unbiased estimator. Cochrane and Orcutt (1949) applied the idea to time series regressions with autocorrelated errors by differencing with an estimated autocorrelation, and Prais and Winsten (1954) kept the first observation with the factor , which makes the transformation the exact inverse Cholesky factor. Kruskal (1968) gave the coordinate-free condition under which ordinary least squares already equals the Aitken estimator.
References
- A. C. Aitken, On least squares and linear combination of observations, Proceedings of the Royal Society of Edinburgh 55, 1935 (volume dated 1936), pp. 42 to 48, The whole paper (the estimator weighted by the inverse covariance and its minimum variance among linear unbiased estimators)
- William Kruskal, When are Gauss-Markov and least squares estimators identical? A coordinate-free approach, Annals of Mathematical Statistics 39(1), 1968, pp. 70 to 75, The whole paper (ordinary and generalized least squares agree for every response exactly when the covariance maps the column space of X into itself)
- S. J. Prais and C. B. Winsten, Trend estimators and serial correlation, Cowles Commission Discussion Paper Statistics No. 383, Chicago, 1954, The whole paper (the AR(1) transformation that keeps the first observation)
- D. Cochrane and G. H. Orcutt, Application of least squares regression to relationships containing auto-correlated error terms, Journal of the American Statistical Association 44(245), 1949, pp. 32 to 61, The whole paper (least squares on differences with an estimated autocorrelation of the errors)
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 3 (generalized least squares as least squares after a change of variables)
- Gene H. Golub and Charles F. Van Loan, Matrix Computations, fourth edition, Johns Hopkins University Press, 2013, Section 4.2 (the Cholesky factorization of a positive definite matrix) and Section 5.3 (the full-rank least squares problem by QR)
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 A3NRM4 Edit this page History Report an error Markdown