Algorithmcore
Weighted least squares
Also called WLS.
Least squares with each squared residual weighted, usually by the inverse of its variance. It is the best linear unbiased estimator when the variances are known.
- Time
- Θ(n p^2) worst · best
- Space
- Θ(n p) extra
- Counts
- flops 2n p^2 - 2p^3/3 + O(n p) 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
Weighted least squares (WLS) fits a linear model by minimizing , a sum of squared residuals in which observation counts with a known weight . When the errors are uncorrelated with variances , so that the weight is the inverse of the variance up to one common factor, WLS is the best linear unbiased estimator, and ordinary least squares is not. The computation is ordinary least squares on rows multiplied by . It is the diagonal case of generalized least squares, and it is the inner step of iteratively reweighted least squares.
In plain words
Some measurements are more precise than others. A cheap sensor and a good sensor measure the same thing; a mean of 50 readings is more reliable than a single reading. If you fit a line and treat every point the same, the noisy points pull the line as hard as the precise ones. Weighted least squares gives each point a weight and makes the fit care more about the points with large weight. The best weight is one over the spread of the point's error. The trick that computes it is short: multiply each row of the data by the square root of its weight. The noise then has the same spread in every row, and the ordinary fit on the changed rows is the weighted fit.
The problem
Model. , where is a fixed real matrix (the intercept column is one of the columns, as on the hat matrix page), is the coefficient vector, and
So the errors are uncorrelated and heteroscedastic with a known pattern: only the ratios of the weights matter, and multiplying all by a constant changes , not the fit.
Input. , and the weights . The rows with must give a matrix of rank .
Output. The estimate, the weighted residual sum of squares, the variance estimate and the estimated covariance:
where are the residuals on the original scale and is the number of positive weights.
The algorithm
WEIGHTED-LEAST-SQUARES(X[1..n, 1..p], y[1..n], w[1..n])- 1
for each i with w[i] > 0 do ▷ m such rows; rows with w[i] = 0 drop out - 2
x̃ᵢ ← √w[i] · xᵢ; ỹᵢ ← √w[i] · y[i] - 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_w ← c[p+1]² + ... + c[m]² ▷ = Σ wᵢ eᵢ² - 6
s² ← RSS_w / (m - p) - 7
V ← s² · R⁻¹ R⁻ᵀ ▷ = s² (Xᵀ W X)⁻¹ - 8
return (b̂, RSS_w, s², V)
Line L2 is the whole idea. If , then has variance , so the scaled rows follow a model with equal variances, and the weighted sum of squares of the original rows is the plain sum of squares of the scaled rows. Lines L3 to L7 are the QR solution of ordinary least squares on the scaled rows. The code does not form : the normal equations square the condition number, and large weight ratios already make the scaled matrix badly conditioned. A interval for is , with the lower quantile of the t law.
Example
Take , , the model with , so .
Line L2 multiplies row by . The scaled rows are and the scaled responses are :
| scaled row | scaled response | ||
|---|---|---|---|
| 1 | 1 | (1, 1) | 2 |
| 2 | 1/2 | (0.5, 1) | 2.5 |
| 3 | 1/3 | (0.333, 1) | 1.667 |
| 4 | 1/4 | (0.25, 1) | 2.25 |
| 5 | 1/5 | (0.2, 1) | 1.8 |
So with these weights the slope becomes the intercept of a regression of on . Exact arithmetic gives
while ordinary least squares gives . The first point, the most precise one, pulls the weighted line down at small . The weighted residual sum of squares is with , so , , and the 95% interval for is .
Measured efficiency. With (), and , samples from random.Random(20261114) gave: the WLS slope had variance (theory ), the OLS slope (theory ), a ratio of . The 95% WLS t interval covered the true slope in 95.2% of the samples, as the exact theory says; the OLS interval with the usual standard error covered it in 93.2%, because that standard error assumes equal variances.
Correctness
Line L2 turns the weighted problem into an unweighted one with the same objective, because , and the QR steps solve that problem exactly. The scaled errors are uncorrelated with common variance , so the Gauss-Markov theorem applies to the scaled model: is unbiased with covariance , and no other linear unbiased estimator has a smaller covariance in the Loewner order. Linear estimators in and in are the same class, so the optimality transfers to the original model. Under normal errors the t intervals are exact. The proof is below.
Proof: Weighted least squares by QR of the scaled rows computes the weighted estimate, which is the best linear unbiased estimator for known weightsfull
The arithmetic is exact. The model is with a fixed real matrix, and , where and every is known. Rows with are treated at the end. Write , and , which is what lines L1 and L2 build. Assume ; since is nonsingular, too.
Lemma 1 (the loop computes the weighted minimizer). Lines L3 and L4 return the unique minimizer of , and line L5 returns .
Proof. , because . Line L3 computes and with orthogonal and upper triangular and nonsingular (the Householder argument is Lemma 1 of the proof on the F-test page; it needs only rank ). Since keeps lengths, . The first term is 0 exactly for , which line L4 computes by back substitution, and is positive for every other . So the minimizer is unique and the minimum is , the value of line L5.
Lemma 2 (the closed form). .
Proof. is a convex quadratic, and its gradient vanishes at the minimizer, so . The matrix is nonsingular.
Lemma 3 (unbiased, and best). and . For every linear unbiased estimator of , is positive semidefinite.
Proof. The scaled vector satisfies with , and . So the scaled model meets the hypotheses of the Gauss-Markov theorem, and by Lemma 1 is its least squares estimate. Gauss-Markov gives unbiasedness, the covariance , and minimality among estimators linear in that are unbiased. A map is linear in exactly when is linear in , and the two give the same random vector, so the classes of linear unbiased estimators in the two models are the same.
Lemma 4 (the variance estimate and exact intervals). With all weights positive, satisfies , and the matrix of line L7 is . If in addition is normal, then has the law for each , so the intervals of confidence_intervals have coverage exactly .
Proof. In the scaled model, are uncorrelated with mean 0 and variance , since and . So . Line L7 forms . Under normality the scaled model is the normal linear model with identity covariance, where is a function of and of ; these are independent normal coordinates, , and the ratio has the law by definition.
Zero weights. A row with adds 0 to for every , so the minimizer and the minimum are those of the fit without the row. Its variance is infinite, so it carries no information and does not count in the residual degrees of freedom; line L1 skips it, and line L6 divides by , where is the number of positive weights. The rank condition then applies to the rows with positive weight.
Termination. Line L1 runs over at most rows. The QR of line L3 has steps, each a finite sum over at most rows and columns, and lines L4 to L7 are finite sums. So the algorithm stops after operations for .
Complexity
For rows with positive weight, line L2 costs , the Householder QR of line L3 costs flops, back substitution flops and the covariance . The total is in the real RAM model, the same as one ordinary least squares fit, and the extra space is for the scaled copy. Forming instead costs about flops, half as much, but squares the condition number.
Properties
- Only the ratios of the weights matter. Replacing by for a constant leaves and unchanged; is multiplied by .
- Best linear unbiased for the right weights. With , the covariance is the smallest among linear unbiased estimators. With wrong weights, is still unbiased, but it is less efficient, and is no longer a correct covariance.
- Exact inference under normal errors. With normal errors and the right weights, independent of , so the t intervals and the F-test on the scaled rows are exact.
- Weighted residuals. The residuals that have equal variance (up to leverage) are the scaled ones . Diagnostics such as leverage and studentized residuals are computed on the scaled rows, where the hat matrix is .
Variants and improvements
- Generalized least squares. Correlated errors with need a full whitening matrix instead of ; see generalized least squares.
- Feasible weighted least squares. When the variances are unknown, model them, for example , estimate from the squared OLS residuals, and refit with . The estimate is no longer linear in and the exact results above do not apply; it is asymptotically as efficient as WLS with the true weights under regularity conditions. A Breusch-Pagan test checks whether a variance model is needed.
- Iterated weights. When the weights depend on the coefficients, as in generalized linear models and M-estimation, alternate between weights and fits: this is iteratively reweighted least squares.
- Sandwich standard errors instead of weights. If the variance pattern is unknown, keep OLS or a rough WLS and use heteroscedasticity-consistent standard errors, which stay valid when the weights are wrong.
- Updating. Adding or removing one weighted row is a rank-one change of ; the Sherman-Morrison formula or a QR update handles it in .
When to use it
Use WLS when the error variances are known up to a common factor: each response is a mean of replicates (), the variance comes from a known measurement process, or a physical model says that the spread grows like a known function of a predictor. If the pattern of the variances must be estimated from the same data, WLS with estimated weights plus a sandwich standard error is safer than trusting .
Pitfalls
- Three meanings of "weight". Precision weights (this page) say that . Frequency weights say that row stands for identical observations: the estimate is the same, but the residual degrees of freedom are , not . Sampling weights are inverse inclusion probabilities in a survey, as in the Horvitz-Thompson estimator: the estimate is the same again, but is wrong and a sandwich or design-based variance is needed. Software that has one
weightsargument cannot know which you mean. - Weights that are variances. The weight is the inverse of the variance. Using the variance itself gives the noisiest points the most influence.
- Estimated weights treated as known. Weights computed from the residuals of the same data make the t and F tests anticonservative in small samples.
- Weights from a single point. A weight that comes from a very small estimated variance (a group with two equal replicates) is huge and lets one observation fix the fit. Bound the weights or pool the variance estimates.
- The normal equations. Forming squares the condition number, and weights that range over many orders of magnitude make that worse. Use QR on the scaled rows.
- Zero and negative weights. A zero weight removes the row and must not count in the degrees of freedom. A negative weight has no meaning as a precision, and the objective is then not convex; the code rejects it.
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
# 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)
weighted_least_squares.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-least-squares/. The authors are listed in prov/3EE4N8.jsonl.
"""Weighted least squares with known weights, by a Householder QR of the scaled rows.
The model is y = X b + e with E[e] = 0 and Var(e_i) = sigma^2 / w_i, the w_i known
and positive (only their ratios matter). The estimate minimizes
sum w_i (y_i - x_i^T b)^2. Each row of X and each y_i is multiplied by sqrt(w_i);
ordinary least squares on the scaled rows, done by QR and not by the normal
equations, gives b-hat, the weighted residual sum of squares, s^2 and the
covariance s^2 (X^T W X)^(-1) = s^2 R^(-1) R^(-T). Rows with w_i = 0 drop out and
do not count in the degrees of freedom.
"""
import math
from typing import NamedTuple
from stdist import t_ppf
RANK_TOL = 1e-12
class WLSFit(NamedTuple):
b: list # the coefficient estimate, length p
rss: float # weighted residual sum of squares, sum w_i e_i^2
df: int # residual degrees of freedom, (number of rows with w_i > 0) - p
s2: float # rss / df, the estimate of sigma^2 (nan if df = 0)
cov: list # s2 (X^T W X)^(-1), p x p
residuals: list # e_i = y_i - x_i^T b, unscaled
def householder_qr(a: list, ys: list) -> tuple[list, list]:
"""Householder QR of the n x p matrix a (list of rows, n >= p), applied to each vector in ys.
Works on copies. Returns (R, cs): R is the p x p upper 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 r_inverse(r: list) -> list:
"""The inverse of an upper triangular nonsingular R, column by column."""
p = len(r)
cols = [back_substitute(r, [1.0 if i == j else 0.0 for i in range(p)]) for j in range(p)]
return [[cols[j][i] for j in range(p)] for i in range(p)]
def weighted_least_squares(x: list, y: list, w: list) -> WLSFit:
"""Fit y = X b + e by weighted least squares with known weights w_i >= 0.
Cost: Theta(n p^2) for the QR and Theta(p^3) for the covariance.
"""
n = len(x)
if len(y) != n or len(w) != n:
raise ValueError("x, y and w must have the same length")
if any(not math.isfinite(wi) or wi < 0.0 for wi in w):
raise ValueError("weights must be finite and nonnegative")
keep = [i for i in range(n) if w[i] > 0.0]
xs, ys = [], []
for i in keep: # @line L1
r = math.sqrt(w[i]) # @line L2
xs.append([r * v for v in x[i]]) # @line L2
ys.append(r * y[i]) # @line L2
rr, (c,) = householder_qr(xs, [ys]) # @line L3
p = len(rr)
b = back_substitute(rr, c[:p]) # @line L4
rss = math.fsum(v * v for v in c[p:]) # @line L5
df = len(keep) - p
s2 = rss / df if df > 0 else math.nan # @line L6
ri = r_inverse(rr)
cov = [[s2 * math.fsum(ri[i][k] * ri[j][k] 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 WLSFit(b, rss, df, s2, cov, res) # @line L8
def confidence_intervals(fit: WLSFit, level: float = 0.95) -> list:
"""t intervals b_j +- t_(df, (1 + level)/2) se_j; exact under normal errors with the right weights."""
q = t_ppf(0.5 + level / 2.0, fit.df)
out = []
for j, bj in enumerate(fit.b):
se = math.sqrt(fit.cov[j][j])
out.append((bj - q * se, bj + q * se))
return out
test_stdist.py 60 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
import math
from stdist import (
beta_inc, chi2_cdf, chi2_ppf, chi2_sf, f_cdf, f_ppf, f_sf, gamma_p, gamma_q,
norm_cdf, norm_ppf, norm_sf, t_cdf, t_ppf, t_sf,
)
XS = [0.001, 0.01, 0.1, 0.3, 0.5, 1.0, 1.7, 2.5, 4.0, 7.0, 12.0, 30.0, 80.0]
def test_chi2_two_degrees_of_freedom() -> None:
for x in XS:
assert abs(chi2_cdf(x, 2) - (1.0 - math.exp(-x / 2.0))) < 1e-13
assert abs(chi2_sf(x, 2) - math.exp(-x / 2.0)) <= 1e-12 * math.exp(-x / 2.0)
def test_t_one_and_two_degrees_of_freedom() -> None:
for x in XS + [-v for v in XS] + [0.0]:
assert abs(t_cdf(x, 1) - (0.5 + math.atan(x) / math.pi)) < 1e-13
assert abs(t_cdf(x, 2) - (0.5 + x / (2.0 * math.sqrt(2.0 + x * x)))) < 1e-13
assert abs(t_cdf(x, 3) + t_sf(x, 3) - 1.0) < 1e-14
def test_f_is_square_of_t() -> None:
for k in [1, 2, 3, 5, 10, 30]:
for x in XS:
two_sided = 2.0 * t_sf(math.sqrt(x), k)
assert abs(f_sf(x, 1, k) - two_sided) < 1e-13
assert abs(f_cdf(x, 1, k) + f_sf(x, 1, k) - 1.0) < 1e-14
def test_gamma_and_beta_identities() -> None:
for a in [0.5, 1.0, 2.5, 10.0, 50.0]:
for x in XS:
assert abs(gamma_p(a, x) + gamma_q(a, x) - 1.0) < 1e-14
# P(1, x) = 1 - e^(-x); I_x(a, 1) = x^a; I_x(1, b) = 1 - (1 - x)^b.
for x in [0.05, 0.3, 0.5, 0.8, 0.99]:
assert abs(gamma_p(1.0, x) - (1.0 - math.exp(-x))) < 1e-14
for a in [0.5, 2.0, 7.0]:
assert abs(beta_inc(a, 1.0, x) - x**a) < 1e-13
assert abs(beta_inc(1.0, a, x) - (1.0 - (1.0 - x) ** a)) < 1e-13
def test_upper_tails_do_not_cancel() -> None:
assert abs(norm_sf(10.0) / 7.619853024160527e-24 - 1.0) < 1e-12
assert abs(chi2_sf(200.0, 2) / math.exp(-100.0) - 1.0) < 1e-12
assert norm_cdf(-30.0) > 0.0
def test_quantiles() -> None:
assert abs(norm_ppf(0.975) - 1.959963985) < 1e-8
assert abs(chi2_ppf(0.95, 1) - 3.841458821) < 1e-8
assert abs(t_ppf(0.975, 10) - 2.228138852) < 1e-8
for p in [1e-6, 0.01, 0.2, 0.5, 0.8, 0.99, 1.0 - 1e-6]:
for k in [1, 4, 25]:
assert abs(chi2_cdf(chi2_ppf(p, k), k) - p) < 1e-12
assert abs(t_cdf(t_ppf(p, k), k) - p) < 1e-12
assert abs(f_cdf(f_ppf(p, k, 7), k, 7) - p) < 1e-12
test_weighted_least_squares.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weighted-least-squares/. The authors are listed in prov/3EE4N8.jsonl.
import math
import random
from fractions import Fraction
import pytest
from weighted_least_squares import confidence_intervals, weighted_least_squares
# The example of the page: x, y and weights 1/x^2.
EX_X = [1, 2, 3, 4, 5]
EX_Y = [2, 5, 5, 9, 9]
EX_W = [Fraction(1, v * v) for v in EX_X]
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 wls_exact(x, y, w):
"""(X^T W X)^(-1) X^T W y by the weighted normal equations, exactly."""
p = len(x[0])
a = [[sum(Fraction(wi) * r[i] * r[j] for r, wi in zip(x, w)) for j in range(p)] for i in range(p)]
rhs = [sum(Fraction(wi) * r[i] * yi for r, yi, wi in zip(x, y, w)) for i in range(p)]
return solve_exact(a, rhs)
def design(xs):
return [[1, v] for v in xs]
def test_page_example_exact():
b = wls_exact(design(EX_X), EX_Y, EX_W)
assert b == [Fraction(281, 1894), Fraction(14967, 7576)]
assert wls_exact(design(EX_X), EX_Y, [1] * 5) == [Fraction(3, 5), Fraction(9, 5)] # OLS
fit = weighted_least_squares(design(EX_X), EX_Y, [float(v) for v in EX_W])
assert fit.b[0] == pytest.approx(float(b[0]), abs=1e-12)
assert fit.b[1] == pytest.approx(float(b[1]), abs=1e-12)
rss = sum(wi * (yi - b[0] - b[1] * xi) ** 2 for xi, yi, wi in zip(EX_X, EX_Y, EX_W))
assert fit.rss == pytest.approx(float(rss), abs=1e-12)
assert fit.df == 3
def test_equals_ols_on_rows_scaled_by_root_weight_exact():
rng = random.Random(11)
for _ in range(20):
n, p = rng.randint(4, 8), rng.randint(1, 3)
x = [[1] + [rng.randint(-5, 5) for _ in range(p - 1)] for _ in range(n)]
y = [rng.randint(-9, 9) for _ in range(n)]
roots = [Fraction(rng.randint(1, 4), rng.randint(1, 3)) for _ in range(n)]
w = [r * r for r in roots]
try:
exact = wls_exact(x, y, w)
except StopIteration:
continue # singular design, skipped
scaled_x = [[r * v for v in row] for row, r in zip(x, roots)]
scaled_y = [r * v for v, r in zip(y, roots)]
assert wls_exact(scaled_x, scaled_y, [1] * n) == exact
fit = weighted_least_squares(x, y, [float(v) for v in w])
for u, v in zip(fit.b, exact):
assert u == pytest.approx(float(v), abs=1e-9)
def test_covariance_matches_inverse_of_weighted_gram_exact():
x, w = design(EX_X), EX_W
fit = weighted_least_squares(x, EX_Y, [float(v) for v in w])
g = [[sum(wi * r[i] * r[j] for r, wi in zip(x, w)) for j in range(2)] for i in range(2)]
det = g[0][0] * g[1][1] - g[0][1] * g[1][0]
inv = [[g[1][1] / det, -g[0][1] / det], [-g[1][0] / det, g[0][0] / det]]
for i in range(2):
for j in range(2):
assert fit.cov[i][j] == pytest.approx(fit.s2 * float(inv[i][j]), rel=1e-10)
def test_zero_weight_equals_deleting_the_row():
x = design([1, 2, 3, 4, 5, 6])
y = [1.0, 3.0, 2.0, 5.0, 4.0, 40.0]
w = [1.0, 2.0, 1.0, 3.0, 1.0, 0.0]
a = weighted_least_squares(x, y, w)
b = weighted_least_squares(x[:5], y[:5], w[:5])
assert a.b == pytest.approx(b.b, abs=1e-12)
assert a.df == b.df == 3
assert a.s2 == pytest.approx(b.s2, rel=1e-12)
def test_scaling_all_weights_changes_nothing():
x = design(EX_X)
w = [float(v) for v in EX_W]
a = weighted_least_squares(x, EX_Y, w)
b = weighted_least_squares(x, EX_Y, [7.5 * v for v in w])
assert a.b == pytest.approx(b.b, abs=1e-12)
assert b.s2 == pytest.approx(7.5 * a.s2, rel=1e-12)
for i in range(2):
assert a.cov[i] == pytest.approx(b.cov[i], rel=1e-10)
def test_bad_inputs():
with pytest.raises(ValueError):
weighted_least_squares(design([1, 2, 3]), [1, 2, 3], [1.0, -1.0, 1.0])
with pytest.raises(ValueError):
weighted_least_squares([[1, 2], [2, 4], [3, 6]], [1, 2, 3], [1.0, 1.0, 1.0])
with pytest.raises(ValueError):
weighted_least_squares(design([1, 2, 3]), [1, 2, 3], [1.0, 0.0, 0.0])
def test_coverage_and_efficiency_measured():
"""Normal errors with sd proportional to x. The t interval with weights 1/x^2 is exact,
so its coverage must be 0.95 up to Monte Carlo error: r = 2000 gives 4 SE of 0.0195."""
rng = random.Random(20261114)
xs = [1 + 0.5 * i for i in range(20)]
x = design(xs)
w = [1.0 / (v * v) for v in xs]
r, hit, slopes_w, slopes_o = 2000, 0, [], []
for _ in range(r):
y = [2.0 + 0.5 * v + rng.gauss(0.0, 0.3 * v) for v in xs]
fit = weighted_least_squares(x, y, w)
lo, hi = confidence_intervals(fit, 0.95)[1]
hit += lo <= 0.5 <= hi
slopes_w.append(fit.b[1])
slopes_o.append(weighted_least_squares(x, y, [1.0] * len(xs)).b[1])
assert abs(hit / r - 0.95) < 0.0195 + 0.002
var_w = sum((s - 0.5) ** 2 for s in slopes_w) / r
var_o = sum((s - 0.5) ** 2 for s in slopes_o) / r
# Var(slope) = sigma^2 [(X^T W X)^(-1)]_22 with sigma = 0.3 and the 2 x 2 inverse by hand.
sw = sum(w)
swx = sum(wi * v for wi, v in zip(w, xs))
swxx = sum(wi * v * v for wi, v in zip(w, xs))
theory_w = 0.09 * sw / (sw * swxx - swx * swx)
assert theory_w > 0.0 and math.isfinite(theory_w)
assert abs(var_w / theory_w - 1.0) < 0.15 # chi-square spread of a variance with r = 2000 is about 0.032
assert var_w < var_o # Gauss-Markov on the scaled model: WLS beats OLS here
History
Aitken (1935) proved that least squares weighted by the inverse of the error covariance matrix gives the linear unbiased estimate of minimum variance, which contains the diagonal case of this page. The computation by scaling the rows and solving with an orthogonal factorization is the standard numerical method of Golub and Van Loan, Section 5.3, applied to the scaled matrix.
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 property)
- George A. F. Seber and Alan J. Lee, Linear Regression Analysis, second edition, Wiley, 2003, Chapter 3 (least squares estimation, with generalized and weighted least squares as a change of variables) and Chapter 10 (unequal variances and weighting)
- Gene H. Golub and Charles F. Van Loan, Matrix Computations, fourth edition, Johns Hopkins University Press, 2013, Section 5.3 (the full-rank least squares problem solved by QR, and why the normal equations square the condition number)
- Nicholas J. Higham, Accuracy and Stability of Numerical Algorithms, second edition, SIAM, 2002, Chapter 20 (the least squares problem, the backward stability of Householder 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 3EE4N8 Edit this page History Report an error Markdown