Algorithm Search⌘K

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

Weighted least squares (WLS) fits a linear model y=Xb+εy = Xb + \varepsilon by minimizing ∑iwi(yi−xi⊤b)2\sum_i w_i (y_i - x_i^\top b)^2, a sum of squared residuals in which observation ii counts with a known weight wi≥0w_i \ge 0. When the errors are uncorrelated with variances σ2/wi\sigma^2/w_i, 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 wi\sqrt{w_i}. 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. y=Xb+εy = Xb + \varepsilon, where XX is a fixed real n×pn \times p matrix (the intercept column is one of the pp columns, as on the hat matrix page), b∈Rpb \in \mathbb{R}^p is the coefficient vector, E[ε]=0\mathrm E[\varepsilon] = 0 and

Cov⁡(ε)=σ2W−1,W=diag⁡(w1,…,wn),wi>0 known, σ2 unknown.\operatorname{Cov}(\varepsilon) = \sigma^2 W^{-1}, \qquad W = \operatorname{diag}(w_1, \dots, w_n), \quad w_i > 0 \text{ known}, \ \sigma^2 \text{ unknown}.

So the errors are uncorrelated and heteroscedastic with a known pattern: only the ratios of the weights matter, and multiplying all wiw_i by a constant changes σ2\sigma^2, not the fit.

Input. XX, yy and the weights w1,…,wn≥0w_1, \dots, w_n \ge 0. The rows with wi>0w_i > 0 must give a matrix of rank pp.

Output. The estimate, the weighted residual sum of squares, the variance estimate and the estimated covariance:

b^W=arg⁡min⁡β∑i=1nwi(yi−xi⊤β)2=(X⊤WX)−1X⊤Wy,s2=∑iwiei2m−p,Cov⁡^(b^W)=s2(X⊤WX)−1,\hat b_W = \arg\min_\beta \sum_{i=1}^n w_i (y_i - x_i^\top\beta)^2 = (X^\top WX)^{-1}X^\top Wy, \qquad s^2 = \frac{\sum_i w_i e_i^2}{m - p}, \qquad \widehat{\operatorname{Cov}}(\hat b_W) = s^2 (X^\top WX)^{-1},

where ei=yi−xi⊤b^We_i = y_i - x_i^\top\hat b_W are the residuals on the original scale and mm is the number of positive weights.

The algorithm

  1. WEIGHTED-LEAST-SQUARES(X[1..n, 1..p], y[1..n], w[1..n])
  2. 1for each i with w[i] > 0 do ▷ m such rows; rows with w[i] = 0 drop out
  3. 2x̃ᵢ ← √w[i] · xᵢ; ỹᵢ ← √w[i] · y[i]
  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_w ← c[p+1]² + ... + c[m]² ▷ = Σ wᵢ eᵢ²
  7. 6s² ← RSS_w / (m - p)
  8. 7V ← s² · R⁻¹ R⁻ᵀ ▷ = s² (Xᵀ W X)⁻¹
  9. 8return (b̂, RSS_w, s², V)

Line L2 is the whole idea. If Var⁡(εi)=σ2/wi\operatorname{Var}(\varepsilon_i) = \sigma^2/w_i, then wi εi\sqrt{w_i}\,\varepsilon_i has variance σ2\sigma^2, 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 X⊤WXX^\top WX: the normal equations square the condition number, and large weight ratios already make the scaled matrix badly conditioned. A 100α%100\alpha\% interval for bjb_j is b^j±t(m−p,1−α/2)Vjj\hat b_j \pm t_{(m-p, 1-\alpha/2)}\sqrt{V_{jj}}, with t(m−p,1−α/2)t_{(m-p, 1-\alpha/2)} the lower 1−α/21 - \alpha/2 quantile of the t law.

Example

Take x=(1,2,3,4,5)x = (1, 2, 3, 4, 5), y=(2,5,5,9,9)y = (2, 5, 5, 9, 9), the model yi=b0+b1xi+εiy_i = b_0 + b_1 x_i + \varepsilon_i with sd⁡(εi)∝xi\operatorname{sd}(\varepsilon_i) \propto x_i, so wi=1/xi2=(1,1/4,1/9,1/16,1/25)w_i = 1/x_i^2 = (1, 1/4, 1/9, 1/16, 1/25).

Line L2 multiplies row ii by 1/xi1/x_i. The scaled rows are (1/xi,1)(1/x_i, 1) and the scaled responses are yi/xiy_i/x_i:

ii wi\sqrt{w_i} 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 b1b_1 becomes the intercept of a regression of y/xy/x on 1/x1/x. Exact arithmetic gives

b^W=(2811894,149677576)≈(0.1484,1.9756),\hat b_W = \Bigl(\tfrac{281}{1894}, \tfrac{14967}{7576}\Bigr) \approx (0.1484, 1.9756),

while ordinary least squares gives (0.6,1.8)(0.6, 1.8). The first point, the most precise one, pulls the weighted line down at small xx. The weighted residual sum of squares is 0.444960.44496 with m−p=3m - p = 3, so s2=0.14832s^2 = 0.14832, se⁡(b^1)=0.3212\operatorname{se}(\hat b_1) = 0.3212, and the 95% interval for b1b_1 is 1.9756±3.1824⋅0.3212=(0.953,2.998)1.9756 \pm 3.1824 \cdot 0.3212 = (0.953, 2.998).

Measured efficiency. With x=1,1.5,…,10.5x = 1, 1.5, \dots, 10.5 (n=20n = 20), yi=2+0.5xi+εiy_i = 2 + 0.5x_i + \varepsilon_i and εi∼N(0,(0.3xi)2)\varepsilon_i \sim N(0, (0.3x_i)^2), r=2000r = 2000 samples from random.Random(20261114) gave: the WLS slope had variance 0.010740.01074 (theory σ2[(X⊤WX)−1]22=0.01084\sigma^2[(X^\top WX)^{-1}]_{22} = 0.01084), the OLS slope 0.025650.02565 (theory 0.025970.02597), a ratio of 2.392.39. 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 wi(yi−xi⊤β)2=(wiyi−wixi⊤β)2w_i(y_i - x_i^\top\beta)^2 = (\sqrt{w_i}y_i - \sqrt{w_i}x_i^\top\beta)^2, and the QR steps solve that problem exactly. The scaled errors wiεi\sqrt{w_i}\varepsilon_i are uncorrelated with common variance σ2\sigma^2, so the Gauss-Markov theorem applies to the scaled model: b^W\hat b_W is unbiased with covariance σ2(X⊤WX)−1\sigma^2(X^\top WX)^{-1}, and no other linear unbiased estimator has a smaller covariance in the Loewner order. Linear estimators in yy and in W1/2yW^{1/2}y 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 y=Xb+εy = Xb + \varepsilon with XX a fixed real n×pn \times p matrix, E[ε]=0\mathrm E[\varepsilon] = 0 and Cov⁡(ε)=σ2W−1\operatorname{Cov}(\varepsilon) = \sigma^2 W^{-1}, where W=diag⁡(w1,…,wn)W = \operatorname{diag}(w_1, \dots, w_n) and every wi>0w_i > 0 is known. Rows with wi=0w_i = 0 are treated at the end. Write W1/2=diag⁡(wi)W^{1/2} = \operatorname{diag}(\sqrt{w_i}), X~=W1/2X\tilde X = W^{1/2}X and y~=W1/2y\tilde y = W^{1/2}y, which is what lines L1 and L2 build. Assume rank⁡X=p\operatorname{rank} X = p; since W1/2W^{1/2} is nonsingular, rank⁡X~=p\operatorname{rank}\tilde X = p too.

Lemma 1 (the loop computes the weighted minimizer). Lines L3 and L4 return the unique minimizer b^\hat b of S(β)=∑iwi(yi−xi⊤β)2S(\beta) = \sum_i w_i (y_i - x_i^\top\beta)^2, and line L5 returns S(b^)S(\hat b).

Proof. S(β)=∥y~−X~β∥2S(\beta) = \|\tilde y - \tilde X\beta\|^2, because wi(yi−xi⊤β)2=(wi yi−wi xi⊤β)2w_i (y_i - x_i^\top\beta)^2 = (\sqrt{w_i}\,y_i - \sqrt{w_i}\,x_i^\top\beta)^2. Line L3 computes Q⊤X~=(R0)Q^\top\tilde X = \binom{R}{0} and c=Q⊤y~c = Q^\top\tilde y with QQ orthogonal and RR upper triangular and nonsingular (the Householder argument is Lemma 1 of the proof on the F-test page; it needs only rank pp). Since Q⊤Q^\top keeps lengths, S(β)=∥c1..p−Rβ∥2+∑i>pci2S(\beta) = \|c_{1..p} - R\beta\|^2 + \sum_{i > p} c_i^2. The first term is 0 exactly for β=R−1c1..p\beta = R^{-1}c_{1..p}, which line L4 computes by back substitution, and is positive for every other β\beta. So the minimizer is unique and the minimum is ∑i>pci2\sum_{i > p} c_i^2, the value of line L5. □\square

Lemma 2 (the closed form). b^=(X⊤WX)−1X⊤Wy\hat b = (X^\top W X)^{-1}X^\top W y.

Proof. SS is a convex quadratic, and its gradient −2X⊤W(y−Xβ)-2X^\top W(y - X\beta) vanishes at the minimizer, so X⊤WXb^=X⊤WyX^\top W X\hat b = X^\top W y. The matrix X⊤WX=X~⊤X~=R⊤RX^\top W X = \tilde X^\top\tilde X = R^\top R is nonsingular. □\square

Lemma 3 (unbiased, and best). E[b^]=b\mathrm E[\hat b] = b and Cov⁡(b^)=σ2(X⊤WX)−1\operatorname{Cov}(\hat b) = \sigma^2 (X^\top W X)^{-1}. For every linear unbiased estimator b~=Cy\tilde b = Cy of bb, Cov⁡(b~)−Cov⁡(b^)\operatorname{Cov}(\tilde b) - \operatorname{Cov}(\hat b) is positive semidefinite.

Proof. The scaled vector satisfies y~=X~b+ε~\tilde y = \tilde X b + \tilde\varepsilon with ε~=W1/2ε\tilde\varepsilon = W^{1/2}\varepsilon, E[ε~]=0\mathrm E[\tilde\varepsilon] = 0 and Cov⁡(ε~)=W1/2σ2W−1W1/2=σ2I\operatorname{Cov}(\tilde\varepsilon) = W^{1/2}\sigma^2W^{-1}W^{1/2} = \sigma^2 I. So the scaled model meets the hypotheses of the Gauss-Markov theorem, and by Lemma 1 b^\hat b is its least squares estimate. Gauss-Markov gives unbiasedness, the covariance σ2(X~⊤X~)−1=σ2(X⊤WX)−1\sigma^2(\tilde X^\top\tilde X)^{-1} = \sigma^2(X^\top WX)^{-1}, and minimality among estimators linear in y~\tilde y that are unbiased. A map y↦Cyy \mapsto Cy is linear in yy exactly when y~↦CW−1/2y~\tilde y \mapsto CW^{-1/2}\tilde y is linear in y~\tilde y, and the two give the same random vector, so the classes of linear unbiased estimators in the two models are the same. □\square

Lemma 4 (the variance estimate and exact intervals). With all nn weights positive, s2=S(b^)/(n−p)s^2 = S(\hat b)/(n - p) satisfies E[s2]=σ2\mathrm E[s^2] = \sigma^2, and the matrix of line L7 is s2(X⊤WX)−1s^2 (X^\top WX)^{-1}. If in addition ε\varepsilon is normal, then (b^j−bj)/s2[(X⊤WX)−1]jj(\hat b_j - b_j)/\sqrt{s^2[(X^\top WX)^{-1}]_{jj}} has the tn−pt_{n-p} law for each jj, so the intervals of confidence_intervals have coverage exactly 1−α1 - \alpha.

Proof. In the scaled model, cp+1,…,cnc_{p+1}, \dots, c_n are uncorrelated with mean 0 and variance σ2\sigma^2, since Cov⁡(Q⊤ε~)=σ2I\operatorname{Cov}(Q^\top\tilde\varepsilon) = \sigma^2 I and E[Q⊤y~]=(Rb0)\mathrm E[Q^\top\tilde y] = \binom{Rb}{0}. So E[∑i>pci2]=(n−p)σ2\mathrm E[\sum_{i > p}c_i^2] = (n - p)\sigma^2. Line L7 forms s2R−1R−⊤=s2(R⊤R)−1=s2(X⊤WX)−1s^2R^{-1}R^{-\top} = s^2(R^\top R)^{-1} = s^2(X^\top WX)^{-1}. Under normality the scaled model is the normal linear model with identity covariance, where b^−b=R−1(c1..p−Rb)\hat b - b = R^{-1}(c_{1..p} - Rb) is a function of c1,…,cpc_1, \dots, c_p and s2s^2 of cp+1,…,cnc_{p+1}, \dots, c_n; 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 has the tn−pt_{n-p} law by definition. □\square

Zero weights. A row with wi=0w_i = 0 adds 0 to S(β)S(\beta) for every β\beta, so the minimizer and the minimum are those of the fit without the row. Its variance σ2/wi\sigma^2/w_i 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 m−pm - p, where mm is the number of positive weights. The rank condition then applies to the rows with positive weight.

Termination. Line L1 runs over at most nn rows. The QR of line L3 has pp steps, each a finite sum over at most nn rows and pp columns, and lines L4 to L7 are finite sums. So the algorithm stops after Θ(np2)\Theta(np^2) operations for n≥pn \ge p.

Complexity

For m≥pm \ge p rows with positive weight, line L2 costs Θ(mp)\Theta(mp), the Householder QR of line L3 costs 2mp2−2p3/3+O(mp)2mp^2 - 2p^3/3 + O(mp) flops, back substitution p2p^2 flops and the covariance Θ(p3)\Theta(p^3). The total is Θ(np2)\Theta(np^2) in the real RAM model, the same as one ordinary least squares fit, and the extra space is Θ(np)\Theta(np) for the scaled copy. Forming X⊤WXX^\top WX instead costs about mp2mp^2 flops, half as much, but squares the condition number.

Properties

  • Only the ratios of the weights matter. Replacing ww by cwcw for a constant c>0c > 0 leaves b^W\hat b_W and Cov⁡^(b^W)\widehat{\operatorname{Cov}}(\hat b_W) unchanged; s2s^2 is multiplied by cc.
  • Best linear unbiased for the right weights. With wi∝1/Var⁡(εi)w_i \propto 1/\operatorname{Var}(\varepsilon_i), the covariance σ2(X⊤WX)−1\sigma^2(X^\top WX)^{-1} is the smallest among linear unbiased estimators. With wrong weights, b^W\hat b_W is still unbiased, but it is less efficient, and s2(X⊤WX)−1s^2(X^\top WX)^{-1} is no longer a correct covariance.
  • Exact inference under normal errors. With normal errors and the right weights, (m−p)s2/σ2∼χm−p2(m - p)s^2/\sigma^2 \sim \chi^2_{m-p} independent of b^W\hat b_W, 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 wiei\sqrt{w_i}e_i. Diagnostics such as leverage and studentized residuals are computed on the scaled rows, where the hat matrix is W1/2X(X⊤WX)−1X⊤W1/2W^{1/2}X(X^\top WX)^{-1}X^\top W^{1/2}.

Variants and improvements

  • Generalized least squares. Correlated errors with Cov⁡(ε)=σ2V\operatorname{Cov}(\varepsilon) = \sigma^2V need a full whitening matrix instead of W1/2W^{1/2}; see generalized least squares.
  • Feasible weighted least squares. When the variances are unknown, model them, for example Var⁡(εi)=σ2exp⁡(zi⊤γ)\operatorname{Var}(\varepsilon_i) = \sigma^2 \exp(z_i^\top\gamma), estimate γ\gamma from the squared OLS residuals, and refit with w^i=exp⁡(−zi⊤γ^)\hat w_i = \exp(-z_i^\top\hat\gamma). The estimate is no longer linear in yy 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 X⊤WXX^\top WX; the Sherman-Morrison formula or a QR update handles it in O(p2)O(p^2).

When to use it

Use WLS when the error variances are known up to a common factor: each response is a mean of kik_i replicates (wi=kiw_i = k_i), 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 s2(X⊤WX)−1s^2(X^\top WX)^{-1}.

Pitfalls

  • Three meanings of "weight". Precision weights (this page) say that Var⁡(εi)=σ2/wi\operatorname{Var}(\varepsilon_i) = \sigma^2/w_i. Frequency weights say that row ii stands for wiw_i identical observations: the estimate is the same, but the residual degrees of freedom are ∑wi−p\sum w_i - p, not m−pm - p. Sampling weights are inverse inclusion probabilities in a survey, as in the Horvitz-Thompson estimator: the estimate is the same again, but s2(X⊤WX)−1s^2(X^\top WX)^{-1} is wrong and a sandwich or design-based variance is needed. Software that has one weights argument 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 X⊤WXX^\top WX 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.

stdist.pyI0RawGitHub
# 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

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

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