Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Alexander C. Aitken, 1935

Generalized least squares (GLS) fits y=Xb+εy = Xb + \varepsilon when the errors are correlated or have unequal variances with a known pattern, Cov⁡(ε)=σ2V\operatorname{Cov}(\varepsilon) = \sigma^2V. It minimizes (y−Xβ)⊤V−1(y−Xβ)(y - X\beta)^\top V^{-1}(y - X\beta), and the solution is b^=(X⊤V−1X)−1X⊤V−1y\hat b = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y, the Aitken estimator. The computation never forms V−1V^{-1}: it factors V=LL⊤V = LL^\top, multiplies the model by L−1L^{-1} so that the new errors are uncorrelated with equal variance, and runs ordinary least squares on the result. For a known VV this is the best linear unbiased estimator. When VV 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. y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix of rank pp (the intercept is one of the pp columns, as on the hat matrix page), E[ε]=0\mathrm E[\varepsilon] = 0 and

Cov⁡(ε)=σ2V,V known, symmetric and positive definite,σ2>0 unknown.\operatorname{Cov}(\varepsilon) = \sigma^2 V, \qquad V \text{ known, symmetric and positive definite}, \quad \sigma^2 > 0 \text{ unknown}.

Here positive definite means z⊤Vz>0z^\top Vz > 0 for every z≠0z \ne 0. A diagonal VV is the case of weighted least squares, with wi=1/Viiw_i = 1/V_{ii}.

Input. XX, yy and VV.

Output. b^=(X⊤V−1X)−1X⊤V−1y\hat b = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y, the whitened residual sum of squares e⊤V−1ee^\top V^{-1}e with e=y−Xb^e = y - X\hat b, the estimate s2=e⊤V−1e/(n−p)s^2 = e^\top V^{-1}e/(n - p) and the covariance estimate s2(X⊤V−1X)−1s^2(X^\top V^{-1}X)^{-1}.

The algorithm

  1. GENERALIZED-LEAST-SQUARES(X[1..n, 1..p], y[1..n], V[1..n, 1..n])
  2. 1L ← Cholesky factor of V ▷ V = L Lᵀ, L lower triangular; fails if V is not positive definite
  3. 2X̃ ← L⁻¹X; ỹ ← L⁻¹y ▷ p + 1 forward substitutions
  4. 3(R, c) ← Householder QR of X̃, applied to ỹ ▷ Qᵀ X̃ = (R; 0), c = Qᵀ ỹ
  5. 4b̂ ← solve R b = c[1..p] by back substitution
  6. 5RSS_V ← c[p+1]² + ... + c[n]² ▷ = eᵀ V⁻¹ e
  7. 6s² ← RSS_V / (n - p)
  8. 7C ← s² · R⁻¹ R⁻ᵀ ▷ = s² (Xᵀ V⁻¹ X)⁻¹
  9. 8return (b̂, RSS_V, s², C)

Line L2 is the whitening. Since Cov⁡(L−1ε)=σ2L−1VL−⊤=σ2I\operatorname{Cov}(L^{-1}\varepsilon) = \sigma^2L^{-1}VL^{-\top} = \sigma^2I, the whitened model y~=X~b+ε~\tilde y = \tilde Xb + \tilde\varepsilon has uncorrelated errors of equal variance, and ∥y~−X~β∥2=(y−Xβ)⊤V−1(y−Xβ)\|\tilde y - \tilde X\beta\|^2 = (y - X\beta)^\top V^{-1}(y - X\beta). Lines L3 to L7 are the QR solution of ordinary least squares on the whitened rows, and inherit its numerical stability. Inverting VV explicitly and then forming X⊤V−1XX^\top V^{-1}X would cost as much and lose accuracy.

Structured VV. For errors from a stationary AR(1) process, Vts=ρ∣t−s∣/(1−ρ2)V_{ts} = \rho^{|t-s|}/(1 - \rho^2), the inverse Cholesky factor is known in closed form: L−1L^{-1} multiplies the first row by 1−ρ2\sqrt{1 - \rho^2} and replaces row t≥2t \ge 2 by row tt minus ρ\rho times row t−1t - 1. This is the Prais-Winsten transformation, and lines L1 and L2 then cost O(np)O(np). For a general stationary autoregressive model the Levinson-Durbin recursion or a Kalman filter gives the whitening in O(n)O(n) per column, and Toeplitz methods (Toeplitz system solving) handle a general stationary covariance.

Example

Take t=1,…,5t = 1, \dots, 5, y=(2,3,5,4,6)y = (2, 3, 5, 4, 6), the model yt=b0+b1t+uty_t = b_0 + b_1 t + u_t, and AR(1) errors with ρ=3/5\rho = 3/5, so 1−ρ2=4/5\sqrt{1 - \rho^2} = 4/5 and the whitening is exact in rationals. Line L2 gives:

tt whitened intercept column whitened tt whitened yy
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

b^=(4037,3637)≈(1.081,0.973),\hat b = \Bigl(\tfrac{40}{37}, \tfrac{36}{37}\Bigr) \approx (1.081, 0.973),

against (1.3,0.9)(1.3, 0.9) from ordinary least squares on the raw data. The whitened residual sum of squares is 3622/925≈3.91573622/925 \approx 3.9157, so s2=1.3052s^2 = 1.3052 with n−p=3n - p = 3, se⁡(b^1)=0.4696\operatorname{se}(\hat b_1) = 0.4696, and the 95% interval for the slope is 0.973±3.1824⋅0.4696=(−0.521,2.467)0.973 \pm 3.1824 \cdot 0.4696 = (-0.521, 2.467). Five correlated points hold little information about a slope.

Measured behavior. With t=1,…,30t = 1, \dots, 30, yt=1+0.2t+uty_t = 1 + 0.2t + u_t and stationary normal AR(1) errors with ρ=0.6\rho = 0.6, r=1000r = 1000 samples from random.Random(20261114) gave these coverages of the nominal 95% t interval for the slope:

method coverage
GLS with the true VV 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 n=30n = 30 because ρ^\hat\rho is biased toward 0 and its sampling error is ignored.

Correctness

Line L1 succeeds because VV is positive definite. By the whitening identity above, lines L3 and L4 minimize (y−Xβ)⊤V−1(y−Xβ)(y - X\beta)^\top V^{-1}(y - X\beta), and the normal equations of the whitened problem are X⊤V−1Xb^=X⊤V−1yX^\top V^{-1}X\hat b = X^\top V^{-1}y, so GLS equals OLS on whitened data. The whitened model satisfies the hypotheses of the Gauss-Markov theorem, and estimators linear in yy and in L−1yL^{-1}y are the same class, so b^\hat b is unbiased with covariance σ2(X⊤V−1X)−1\sigma^2(X^\top V^{-1}X)^{-1} and is best linear unbiased (Aitken's theorem). s2s^2 is unbiased for σ2\sigma^2, 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 L−1L^{-1} 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 y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix of rank pp, E[ε]=0\mathrm E[\varepsilon] = 0 and Cov⁡(ε)=σ2V\operatorname{Cov}(\varepsilon) = \sigma^2 V, where VV is a known symmetric positive definite n×nn \times n matrix and σ2>0\sigma^2 > 0 is unknown.

Lemma 1 (the factor). Line L1 succeeds and returns the unique lower triangular LL with positive diagonal and LL⊤=VLL^\top = V.

Proof. This is the existence and uniqueness of the Cholesky decomposition of a positive definite matrix. In the column loop, the pivot dj=vjj−∑k<jljk2d_j = v_{jj} - \sum_{k<j} l_{jk}^2 is the ratio of the leading principal minors of orders jj and j−1j - 1 of VV, which are positive, so the square root exists and every division is by a positive number. Each entry of LL is forced by the equation (LL⊤)ij=vij(LL^\top)_{ij} = v_{ij} once the earlier columns are known, which gives uniqueness. If some dj≤0d_j \le 0, VV is not positive definite and the code raises an error. □\square

Lemma 2 (the whitened model). Let X~=L−1X\tilde X = L^{-1}X, y~=L−1y\tilde y = L^{-1}y and ε~=L−1ε\tilde\varepsilon = L^{-1}\varepsilon, as line L2 computes by forward substitution. Then y~=X~b+ε~\tilde y = \tilde Xb + \tilde\varepsilon with E[ε~]=0\mathrm E[\tilde\varepsilon] = 0, Cov⁡(ε~)=σ2I\operatorname{Cov}(\tilde\varepsilon) = \sigma^2 I and rank⁡X~=p\operatorname{rank}\tilde X = p.

Proof. Multiply the model by L−1L^{-1}. Then Cov⁡(ε~)=L−1σ2VL−⊤=σ2L−1LL⊤L−⊤=σ2I\operatorname{Cov}(\tilde\varepsilon) = L^{-1}\sigma^2VL^{-\top} = \sigma^2L^{-1}LL^\top L^{-\top} = \sigma^2 I, and L−1L^{-1} is nonsingular, so it keeps the rank of XX. □\square

Lemma 3 (GLS equals OLS on whitened data). Lines L3 and L4 return the unique minimizer of (y−Xβ)⊤V−1(y−Xβ)(y - X\beta)^\top V^{-1}(y - X\beta), which is

b^=(X⊤V−1X)−1X⊤V−1y,\hat b = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y,

and line L5 returns the minimum value e⊤V−1ee^\top V^{-1}e with e=y−Xb^e = y - X\hat b.

Proof. V−1=L−⊤L−1V^{-1} = L^{-\top}L^{-1}, so (y−Xβ)⊤V−1(y−Xβ)=∥y~−X~β∥2(y - X\beta)^\top V^{-1}(y - X\beta) = \|\tilde y - \tilde X\beta\|^2. Lines L3 and L4 are the QR solution of ordinary least squares for (X~,y~)(\tilde X, \tilde y): with Q⊤X~=(R0)Q^\top\tilde X = \binom{R}{0} and c=Q⊤y~c = Q^\top\tilde y, ∥y~−X~β∥2=∥c1..p−Rβ∥2+∑i>pci2\|\tilde y - \tilde X\beta\|^2 = \|c_{1..p} - R\beta\|^2 + \sum_{i>p}c_i^2, which is smallest exactly at β=R−1c1..p\beta = R^{-1}c_{1..p}, with minimum ∑i>pci2\sum_{i>p}c_i^2 (the same argument as Lemma 1 of the proof on the weighted least squares page). The minimizer solves the normal equations X~⊤X~b^=X~⊤y~\tilde X^\top\tilde X\hat b = \tilde X^\top\tilde y, and X~⊤X~=X⊤L−⊤L−1X=X⊤V−1X\tilde X^\top\tilde X = X^\top L^{-\top}L^{-1}X = X^\top V^{-1}X and X~⊤y~=X⊤V−1y\tilde X^\top\tilde y = X^\top V^{-1}y. □\square

Lemma 4 (Aitken: unbiased and best). E[b^]=b\mathrm E[\hat b] = b, Cov⁡(b^)=σ2(X⊤V−1X)−1\operatorname{Cov}(\hat b) = \sigma^2(X^\top V^{-1}X)^{-1}, and for every linear unbiased estimator bˇ=Cy\check b = Cy the difference Cov⁡(bˇ)−Cov⁡(b^)\operatorname{Cov}(\check b) - \operatorname{Cov}(\hat b) is positive semidefinite.

Proof. By Lemma 2 the whitened model satisfies the hypotheses of the Gauss-Markov theorem, and by Lemma 3 b^\hat b is its least squares estimate. So b^\hat b is unbiased with covariance σ2(X~⊤X~)−1=σ2(X⊤V−1X)−1\sigma^2(\tilde X^\top\tilde X)^{-1} = \sigma^2(X^\top V^{-1}X)^{-1}, and it has the smallest covariance among estimators that are linear in y~\tilde y and unbiased. An estimator CyCy equals (CL)y~(CL)\tilde y, and Dy~D\tilde y equals (DL−1)y(DL^{-1})y, so the estimators linear in yy and linear in y~\tilde y are the same random vectors, and so are the unbiased ones. □\square

Lemma 5 (variance estimate and exact intervals). s2=e⊤V−1e/(n−p)s^2 = e^\top V^{-1}e/(n - p) from line L6 satisfies E[s2]=σ2\mathrm E[s^2] = \sigma^2, and line L7 returns s2(X⊤V−1X)−1s^2(X^\top V^{-1}X)^{-1}. If ε\varepsilon is normal, (b^j−bj)/s2[(X⊤V−1X)−1]jj(\hat b_j - b_j)/\sqrt{s^2[(X^\top V^{-1}X)^{-1}]_{jj}} has the tn−pt_{n-p} law.

Proof. In the whitened model c=Q⊤y~c = Q^\top\tilde y has mean (Rb0)\binom{Rb}{0} and covariance σ2I\sigma^2 I, so E∑i>pci2=(n−p)σ2\mathrm E\sum_{i>p}c_i^2 = (n - p)\sigma^2. R−1R−⊤=(R⊤R)−1=(X~⊤X~)−1R^{-1}R^{-\top} = (R^\top R)^{-1} = (\tilde X^\top\tilde X)^{-1}. Under normality b^−b=R−1(c1..p−Rb)\hat b - b = R^{-1}(c_{1..p} - Rb) depends on c1,…,cpc_1, \dots, c_p only and s2s^2 on cp+1,…,cnc_{p+1}, \dots, c_n only; these are independent normal coordinates, (n−p)s2/σ2∼χn−p2(n - p)s^2/\sigma^2 \sim \chi^2_{n-p}, and the ratio is tn−pt_{n-p} by definition. □\square

Lemma 6 (the Prais-Winsten matrix is the inverse Cholesky factor of the AR(1) covariance). Let ∣ρ∣<1|\rho| < 1 and Vts=ρ∣t−s∣/(1−ρ2)V_{ts} = \rho^{|t-s|}/(1 - \rho^2). Let PP be the n×nn \times n matrix with P11=1−ρ2P_{11} = \sqrt{1 - \rho^2}, Ptt=1P_{tt} = 1 and Pt,t−1=−ρP_{t,t-1} = -\rho for t≥2t \ge 2, and zeros elsewhere. Then PVP⊤=IPVP^\top = I and P=L−1P = L^{-1}, where LL is the Cholesky factor of VV.

Proof. VV is the covariance of a stationary AR(1) process ut=ρut−1+atu_t = \rho u_{t-1} + a_t with uncorrelated innovations ata_t of variance 1: then Var⁡ut=1/(1−ρ2)\operatorname{Var}u_t = 1/(1 - \rho^2) and Cov⁡(ut,ut−h)=ρh/(1−ρ2)\operatorname{Cov}(u_t, u_{t-h}) = \rho^h/(1 - \rho^2). The vector PuPu has entries 1−ρ2 u1\sqrt{1 - \rho^2}\,u_1 and ut−ρut−1=atu_t - \rho u_{t-1} = a_t for t≥2t \ge 2. The first has variance 1, the ata_t have variance 1, and ata_t for t≥2t \ge 2 is uncorrelated with u1u_1 and with the other innovations, so Cov⁡(Pu)=PVP⊤=I\operatorname{Cov}(Pu) = PVP^\top = I. Hence V=P−1P−⊤V = P^{-1}P^{-\top}. The matrix PP is lower triangular with positive diagonal, so P−1P^{-1} is too, and by the uniqueness in Lemma 1, P−1=LP^{-1} = L. □\square

So for AR(1) errors line L2 is the Prais-Winsten transformation, and it costs O(np)O(np) instead of O(n3)O(n^3).

Lemma 7 (Kruskal: when OLS and GLS agree). The ordinary least squares estimate (X⊤X)−1X⊤y(X^\top X)^{-1}X^\top y equals b^\hat b for every yy if and only if the column space of VXVX equals the column space of XX.

Proof. Let H=X(X⊤X)−1X⊤H = X(X^\top X)^{-1}X^\top and e0=(I−H)ye_0 = (I - H)y, the OLS residual. Since b^\hat b is the unique solution of X⊤V−1(y−Xβ)=0X^\top V^{-1}(y - X\beta) = 0, OLS equals GLS at yy exactly when X⊤V−1e0=0X^\top V^{-1}e_0 = 0. If col⁡(VX)=col⁡(X)\operatorname{col}(VX) = \operatorname{col}(X), then V−1V^{-1} maps col⁡(X)\operatorname{col}(X) onto itself, so V−1X=XAV^{-1}X = XA for some p×pp \times p matrix AA, and X⊤V−1e0=A⊤X⊤e0=0X^\top V^{-1}e_0 = A^\top X^\top e_0 = 0 because e0⊥col⁡(X)e_0 \perp \operatorname{col}(X). Conversely, if X⊤V−1(I−H)y=0X^\top V^{-1}(I - H)y = 0 for every yy, the columns of V−1XV^{-1}X are orthogonal to col⁡(I−H)=col⁡(X)⊥\operatorname{col}(I - H) = \operatorname{col}(X)^\perp, so col⁡(V−1X)⊆col⁡(X)\operatorname{col}(V^{-1}X) \subseteq \operatorname{col}(X); both have dimension pp, so they are equal, and applying VV gives col⁡(X)=col⁡(VX)\operatorname{col}(X) = \operatorname{col}(VX). □\square

For example, the equicorrelated V=(1−c)I+c11⊤V = (1 - c)I + c\mathbf 1\mathbf 1^\top satisfies the condition whenever 1∈col⁡(X)\mathbf 1 \in \operatorname{col}(X), since Vx=(1−c)x+c(1⊤x)1Vx = (1 - c)x + c(\mathbf 1^\top x)\mathbf 1.

Termination. Line L1 is nn column steps of finite sums (n3/3n^3/3 flops), line L2 is p+1p + 1 forward substitutions (n2n^2 flops each), the QR of line L3 is pp Householder steps, and lines L4 to L7 are finite sums. So the algorithm stops after Θ(n3+n2p)\Theta(n^3 + n^2p) operations for a dense VV.

Complexity

For a dense VV, the Cholesky factor costs n3/3n^3/3 flops, the p+1p + 1 forward substitutions (p+1)n2(p + 1)n^2, the QR 2np2−2p3/32np^2 - 2p^3/3 and the covariance O(p3)O(p^3): Θ(n3)\Theta(n^3) time and Θ(n2)\Theta(n^2) space for VV and LL. Structure changes this. A diagonal VV is weighted least squares at Θ(np2)\Theta(np^2). AR(1) and banded VV with bandwidth qq cost Θ(nq2+nqp+np2)\Theta(nq^2 + nqp + np^2). A block diagonal VV with blocks of size mm, as in repeated measures, costs Θ(nm2+np2)\Theta(nm^2 + np^2).

Properties

  • Best linear unbiased. For known VV, Cov⁡(b^)=σ2(X⊤V−1X)−1\operatorname{Cov}(\hat b) = \sigma^2(X^\top V^{-1}X)^{-1} is the smallest covariance, in the Loewner order, among linear unbiased estimators. OLS is still unbiased under correlation, but its covariance is σ2(X⊤X)−1X⊤VX(X⊤X)−1\sigma^2(X^\top X)^{-1}X^\top VX(X^\top X)^{-1}, not σ2(X⊤X)−1\sigma^2(X^\top X)^{-1}.
  • Scale of VV does not matter. VV and cVcV give the same b^\hat b and the same covariance estimate.
  • When OLS is already GLS. Kruskal (1968): OLS equals GLS for every yy exactly when the column space of VXVX equals that of XX. An equicorrelated V=(1−c)I+c11⊤V = (1 - c)I + c\mathbf 1\mathbf 1^\top with an intercept in XX 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 e=y−Xb^e = y - X\hat b are correlated even under the model. Diagnostics such as leverage and studentized residuals belong on the whitened scale L−1eL^{-1}e.

Variants and improvements

  • Feasible GLS. V=V(θ)V = V(\theta) depends on a few unknown parameters. Estimate θ\theta from OLS residuals, then run GLS with V(θ^)V(\hat\theta). For AR(1) errors, ρ^=∑etet−1/∑et2\hat\rho = \sum e_te_{t-1}/\sum e_t^2 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 VV; 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 yt−ρyt−1y_t - \rho y_{t-1}; in practice it is iterated between ρ\rho and bb, 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 bb and θ\theta 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 VV but give up efficiency. Generalized estimating equations combine both: a working VV for efficiency and a sandwich variance that stays valid when the working VV 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 VV is in doubt, prefer OLS or feasible GLS with a robust sandwich variance.

Pitfalls

  • Inverting VV. Forming V−1V^{-1} 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 VV is known. With an estimated VV they are too small in short series.
  • A wrong VV. GLS with a wrong VV stays unbiased if the regressors are fixed, but it is no longer best, and s2(X⊤V−1X)−1s^2(X^\top V^{-1}X)^{-1} is the wrong covariance. Use a sandwich variance unless the model for VV is well checked.
  • Lagged dependent variables. If XX contains yt−1y_{t-1} and the errors are autocorrelated, OLS and feasible GLS are both inconsistent; the regressors are correlated with the errors. The fixed-XX theory of this page does not apply.
  • Strict exogeneity. With correlated errors, GLS uses future and past regressors to predict each error. It needs E[εt∣X]=0\mathrm E[\varepsilon_t \mid X] = 0 for all regressor values, not only those at time tt; OLS needs less.
  • Nearly singular VV. If VV is close to singular, the whitening amplifies rounding error, and the Cholesky factor may fail. Check the condition number of VV, 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.

generalized_least_squares.pyI0RawGitHub
# 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 1−ρ2\sqrt{1 - \rho^2}, 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

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

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
  • a full proof of flops.worst
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