Algorithm Search⌘K

Algorithmcore

Iteratively reweighted least squares

Also called IRLS, IWLS.

Solves a sequence of weighted least squares problems whose weights come from the current fit. It fits generalized linear models and robust M-estimators.

Time
Θ(k n p^2) worstΘ(n p^2) best
Space
Θ(n p) extra
Where
k = the number of iterations; n = the number of observations; p = the number of columns of X
Properties
deterministicnot exactofflineiterative
Origin
John A. Nelder, Robert W. M. Wedderburn, Paul W. Holland, Roy E. Welsch, Peter J. Green, 1972

Iteratively reweighted least squares turns a hard fitting problem into a sequence of weighted least squares problems. Each pass computes a weight wiw_i and a working response ziz_i for every observation from the current coefficients bb, then fits zz on XX with those weights to get the next bb. With the weights and responses of a generalized linear model the pass is a Fisher scoring step, and for a canonical link such as the logit it is exactly a Newton step. With the weights of a robust loss, such as Huber's or Tukey's biweight, each pass cannot increase the loss. One routine, a weighted QR solve in a loop, fits logistic, Poisson and probit regression, robust M-estimators and least absolute deviations.

In plain words

Many fitting problems would be easy if each point came with the right weight. For a yes or no outcome, points whose predicted chance is near one half carry the most information, but you only know the chances after you have a fit. For a robust line, a point far from the line should count less, but you only know which points are far after you have a line. The method breaks the circle by guessing. Start from some line, compute the weights it implies, fit again with those weights, and repeat. For the models in this page each round moves toward the answer, and a handful of rounds is usually enough.

The problem

Input. A fixed real n×pn \times p design XX with rows xi⊤x_i^\top (the intercept is one of the pp columns), a response yy, and a working rule that maps the response and the current linear predictor η=Xb\eta = Xb to weights wi≥0w_i \ge 0 and working responses ziz_i.

Output. A coefficient vector b^\hat b at which the weighted fit reproduces itself: fitting z(b^)z(\hat b) on XX with weights w(b^)w(\hat b) gives b^\hat b back.

Two families of rules cover most uses:

problem objective working response ziz_i weight wiw_i
GLM with mean μi=g−1(ηi)\mu_i = g^{-1}(\eta_i), variance function VV maximize the likelihood ηi+(yi−μi)g′(μi)\eta_i + (y_i - \mu_i)g'(\mu_i) 1/(V(μi)g′(μi)2)1/(V(\mu_i)g'(\mu_i)^2)
logistic regression (logit link) maximize the likelihood ηi+(yi−μi)/(μi(1−μi))\eta_i + (y_i - \mu_i)/(\mu_i(1 - \mu_i)) μi(1−μi)\mu_i(1 - \mu_i)
Poisson regression (log link) maximize the likelihood ηi+(yi−μi)/μi\eta_i + (y_i - \mu_i)/\mu_i μi\mu_i
M-estimation, ρ(r)=f(r2)\rho(r) = f(r^2) with ff concave minimize ∑ρ(yi−ηi)\sum\rho(y_i - \eta_i) yiy_i f′(ri2)f'(r_i^2), proportional to ψ(ri)/ri\psi(r_i)/r_i
Huber loss, threshold cc, scale ss as above yiy_i min⁡(1,cs/∣ri∣)\min(1, cs/\lvert r_i\rvert)
Tukey biweight, threshold cc, scale ss as above yiy_i (1−(ri/cs)2)2(1 - (r_i/cs)^2)^2 inside, 00 outside
least absolute deviations, floor δ\delta minimize ∑∣yi−ηi∣\sum\lvert y_i - \eta_i\rvert yiy_i 1/max⁡(∣ri∣,δ)1/\max(\lvert r_i\rvert, \delta)

Here ri=yi−ηir_i = y_i - \eta_i and ψ=ρ′\psi = \rho'.

The algorithm

  1. ITERATIVELY-REWEIGHTED-LEAST-SQUARES(X, y, RULE, b⁽⁰⁾, tol, maxit)
  2. 1b ← b⁽⁰⁾ ▷ often 0, or a least squares fit
  3. 2for k ← 1 to maxit do
  4. 3η ← X b
  5. 4(w, z) ← RULE(y, η) ▷ weights and working response from the current fit
  6. 5b⁺ ← argmin_β Σᵢ wᵢ (zᵢ - xᵢᵀβ)² ▷ weighted least squares by QR of √w-scaled rows
  7. 6if ‖b⁺ - b‖ ≤ tol · (‖b⁺‖ + tol) then return (b⁺, converged)
  8. 7b ← b⁺
  9. 8return (b, not converged)

Line L5 is the only heavy step. It solves a weighted least squares problem by a QR factorization of the rows scaled by wi\sqrt{w_i}, as on the weighted least squares page; rows with wi=0w_i = 0 (the biweight beyond cc) drop out. For a GLM, line L4 needs μi=g−1(ηi)\mu_i = g^{-1}(\eta_i), and the implementation keeps μi\mu_i a small distance away from the boundary of its range so that wiw_i and ziz_i stay finite. The dispersion ϕ\phi of the GLM cancels and is not needed. For M-estimation the scale ss is fixed during the loop; in practice it is a robust scale of a starting fit, such as the median absolute deviation of its residuals.

Example

Logistic regression. Take x=(1,2,3,4,5,6)x = (1, 2, 3, 4, 5, 6), y=(0,0,1,0,1,1)y = (0, 0, 1, 0, 1, 1), and the model logit⁡μi=b0+b1xi\operatorname{logit}\mu_i = b_0 + b_1x_i. Start at b=0b = 0. Then every μi=1/2\mu_i = 1/2, every weight is 1/41/4, and zi=4yi−2=(−2,−2,2,−2,2,2)z_i = 4y_i - 2 = (-2, -2, 2, -2, 2, 2). With equal weights, line L5 is ordinary least squares of zz on xx: the slope is 14/17.5=0.814/17.5 = 0.8 and the intercept 0−0.8⋅3.5=−2.80 - 0.8 \cdot 3.5 = -2.8. This is exactly the Newton step from b=0b = 0. The passes go on:

kk b0b_0 b1b_1 deviance −2ℓ-2\ell
0 0 0 8.3178
1 -2.8000 0.8000 5.2129
2 -3.8842 1.1098 4.9697
3 -4.2214 1.2061 4.9560
4 -4.2489 1.2140 4.95597
5 -4.2491 1.2140 4.95597

The number of correct digits roughly doubles per pass near the end, as for Newton's method; the step test with tolerance 10−1010^{-10} stops after 7 passes. At the limit the score X⊤(y−μ)X^\top(y - \mu) is zero.

A robust line. For x=1,…,10x = 1, \dots, 10 and y=(1.1,2.0,2.9,4.2,5.0,5.9,7.1,8.0,30.0,10.1)y = (1.1, 2.0, 2.9, 4.2, 5.0, 5.9, 7.1, 8.0, 30.0, 10.1), where the ninth point is a gross error, ordinary least squares gives the slope 1.892. Starting from b=0b = 0 with the scale fixed at s=0.5s = 0.5, the Huber rule (c=1.345c = 1.345) gives slope 1.040 after 8 passes, the biweight (c=4.685c = 4.685) gives 1.002 after 7 passes with weight 0 on the bad point, and the L1 rule (δ=10−6\delta = 10^{-6}) gives 1.0125 after 12 passes. In each run the loss decreased at every pass, as the proof says it must.

Correctness

Line L5 returns b+=(X⊤WX)−1X⊤Wzb^+ = (X^\top WX)^{-1}X^\top Wz. For a GLM, the score is U=ϕ−1X⊤W((yi−μi)g′(μi))iU = \phi^{-1}X^\top W\bigl((y_i - \mu_i)g'(\mu_i)\bigr)_i and the expected information is I=ϕ−1X⊤WX\mathcal I = \phi^{-1}X^\top WX; substituting z=η+(y−μ)g′(μ)z = \eta + (y - \mu)g'(\mu) gives b+=b+I−1Ub^+ = b + \mathcal I^{-1}U, a Fisher scoring step. For the logit link W=diag⁡(μi(1−μi))W = \operatorname{diag}(\mu_i(1 - \mu_i)) is also minus the Hessian of the log-likelihood, so the step is Newton's step; the same holds for every canonical link. For a loss ρ(r)=f(r2)\rho(r) = f(r^2) with ff concave, the tangent line of ff gives a weighted sum of squares that lies above the loss and touches it at the current bb; line L5 minimizes that upper bound, so the loss cannot increase. The L1 weights with a floor δ\delta do this exactly for a smoothed absolute loss, and a fixed point is within nδ/2n\delta/2 of the least absolute deviations minimum. The proof gives the details and says what is not proved.

Proof: Iteratively reweighted least squares is Fisher scoring for a GLM, Newton's method for a canonical link, and a descent method for M-estimationfull

The arithmetic is exact. XX is a fixed real n×pn \times p matrix with rows xi⊤x_i^\top, and line L5 is always applied to a weighted design of rank pp (the code raises an error otherwise). By the proof on the weighted least squares page, line L5 then returns the unique minimizer

b+=(X⊤WX)−1X⊤Wz,W=diag⁡(w1,…,wn),b^+ = (X^\top WX)^{-1}X^\top Wz, \qquad W = \operatorname{diag}(w_1, \dots, w_n),

of ∑iwi(zi−xi⊤β)2\sum_i w_i(z_i - x_i^\top\beta)^2. The three lemmas below say what this step is for each kind of working rule.

Lemma 1 (a GLM step is a Fisher scoring step). Let yiy_i have an exponential family law with mean μi\mu_i, variance ϕV(μi)\phi V(\mu_i) and link g(μi)=ηi=xi⊤βg(\mu_i) = \eta_i = x_i^\top\beta, with gg smooth and strictly monotone. With zi=ηi+(yi−μi)g′(μi)z_i = \eta_i + (y_i - \mu_i)g'(\mu_i) and wi=1/(V(μi)g′(μi)2)w_i = 1/(V(\mu_i)g'(\mu_i)^2), all at the current bb, the step of line L5 is

b+=b+I(b)−1U(b),b^+ = b + \mathcal I(b)^{-1}U(b),

where UU is the score and I\mathcal I the expected information.

Proof. The log-likelihood of observation ii is (yiθi−κ(θi))/ϕ(y_i\theta_i - \kappa(\theta_i))/\phi plus a term free of β\beta, with κ′(θ)=μ\kappa'(\theta) = \mu and κ′′(θ)=V(μ)\kappa''(\theta) = V(\mu). By the chain rule, ∂θi/∂ηi=(dμi/dηi)/V(μi)=1/(V(μi)g′(μi))\partial\theta_i/\partial\eta_i = (d\mu_i/d\eta_i)/V(\mu_i) = 1/(V(\mu_i)g'(\mu_i)), so

U(β)=1ϕ∑iyi−μiV(μi)g′(μi)xi=1ϕX⊤W ((yi−μi)g′(μi))i.U(\beta) = \frac1\phi\sum_i \frac{y_i - \mu_i}{V(\mu_i)g'(\mu_i)}x_i = \frac1\phi X^\top W\,\bigl((y_i - \mu_i)g'(\mu_i)\bigr)_i.

The expected information is I=Cov⁡U=1ϕ2∑iϕV(μi)V(μi)2g′(μi)2xixi⊤=1ϕX⊤WX\mathcal I = \operatorname{Cov}U = \frac1{\phi^2}\sum_i \frac{\phi V(\mu_i)}{V(\mu_i)^2g'(\mu_i)^2}x_ix_i^\top = \frac1\phi X^\top WX. So b+I−1U=(X⊤WX)−1(X⊤WXb+X⊤W((yi−μi)g′(μi))i)=(X⊤WX)−1X⊤Wzb + \mathcal I^{-1}U = (X^\top WX)^{-1}\bigl(X^\top WXb + X^\top W((y_i - \mu_i)g'(\mu_i))_i\bigr) = (X^\top WX)^{-1}X^\top Wz, since Xb=ηXb = \eta. □\square

The dispersion ϕ\phi cancels, so the iteration does not need it.

Lemma 2 (for the logistic model the step is the Newton step). For yi∈{0,1}y_i \in \{0, 1\}, μi=1/(1+e−ηi)\mu_i = 1/(1 + e^{-\eta_i}) and the log-likelihood ℓ(β)=∑i(yiηi−log⁡(1+eηi))\ell(\beta) = \sum_i (y_i\eta_i - \log(1 + e^{\eta_i})), the Newton step b−(∇2ℓ)−1∇ℓb - (\nabla^2\ell)^{-1}\nabla\ell equals the step of line L5 with wi=μi(1−μi)w_i = \mu_i(1 - \mu_i) and zi=ηi+(yi−μi)/wiz_i = \eta_i + (y_i - \mu_i)/w_i.

Proof. dμ/dη=μ(1−μ)d\mu/d\eta = \mu(1 - \mu), so ∇ℓ=∑i(yi−μi)xi=X⊤(y−μ)\nabla\ell = \sum_i(y_i - \mu_i)x_i = X^\top(y - \mu) and ∇2ℓ=−∑iμi(1−μi)xixi⊤=−X⊤WX\nabla^2\ell = -\sum_i\mu_i(1 - \mu_i)x_ix_i^\top = -X^\top WX, which does not depend on yy. The Newton step is

b+(X⊤WX)−1X⊤(y−μ)=(X⊤WX)−1X⊤W(Xb+W−1(y−μ))=(X⊤WX)−1X⊤Wz.□b + (X^\top WX)^{-1}X^\top(y - \mu) = (X^\top WX)^{-1}X^\top W\bigl(Xb + W^{-1}(y - \mu)\bigr) = (X^\top WX)^{-1}X^\top Wz. \qquad\square

The same argument works for every canonical link, where g′(μ)=1/V(μ)g'(\mu) = 1/V(\mu) and the observed information −∇2ℓ-\nabla^2\ell has no term in y−μy - \mu, so it equals I\mathcal I. For a link that is not canonical, such as the probit link, the observed information has an extra term with factor yi−μiy_i - \mu_i, and the step is Fisher scoring, not Newton. At b=0b = 0 in the logistic model every μi=1/2\mu_i = 1/2, so wi=1/4w_i = 1/4 and zi=4yi−2z_i = 4y_i - 2 are rational, and the first step can be checked in exact arithmetic.

Lemma 3 (M-estimation: the loss never increases). Let ρ(r)=f(r2)\rho(r) = f(r^2) with ff differentiable, nondecreasing and concave on [0,∞)[0, \infty), and F(β)=∑iρ(yi−xi⊤β)F(\beta) = \sum_i\rho(y_i - x_i^\top\beta). With z=yz = y and wi=f′(ri2)w_i = f'(r_i^2) for the current residuals ri=yi−xi⊤br_i = y_i - x_i^\top b, the step satisfies F(b+)≤F(b)F(b^+) \le F(b). Multiplying all wiw_i by one positive constant does not change b+b^+.

Proof. Concavity gives f(t)≤f(t0)+f′(t0)(t−t0)f(t) \le f(t_0) + f'(t_0)(t - t_0) for all t,t0≥0t, t_0 \ge 0. With t=(yi−xi⊤β)2t = (y_i - x_i^\top\beta)^2 and t0=ri2t_0 = r_i^2, summing over ii,

F(β)≤G(β)=F(b)+∑iwi((yi−xi⊤β)2−ri2),F(\beta) \le G(\beta) = F(b) + \sum_i w_i\bigl((y_i - x_i^\top\beta)^2 - r_i^2\bigr),

with equality at β=b\beta = b. Line L5 minimizes ∑iwi(yi−xi⊤β)2\sum_iw_i(y_i - x_i^\top\beta)^2, which is GG up to a constant, so F(b+)≤G(b+)≤G(b)=F(b)F(b^+) \le G(b^+) \le G(b) = F(b). The scale statement holds because a constant factor in all weights does not change the minimizer. □\square

The rules of the implementation fit Lemma 3, with u=r/su = r/s for a fixed scale ss:

  • Huber: f(t)=t/2f(t) = t/2 for t≤c2t \le c^2 and ct−c2/2c\sqrt t - c^2/2 beyond. Then f′(t)=min⁡(1/2,c/(2t))f'(t) = \min(1/2, c/(2\sqrt t)) is continuous and nonincreasing, so ff is concave, and 2f′(u2)=min⁡(1,c/∣u∣)2f'(u^2) = \min(1, c/|u|).
  • Tukey biweight: f(t)=(c2/6)(1−(1−t/c2)3)f(t) = (c^2/6)(1 - (1 - t/c^2)^3) for t≤c2t \le c^2 and c2/6c^2/6 beyond. Then f′(t)=12(1−t/c2)2f'(t) = \frac12(1 - t/c^2)^2 for t≤c2t \le c^2 and 00 beyond, which is nonincreasing, and 2f′(u2)=(1−u2/c2)22f'(u^2) = (1 - u^2/c^2)^2. The loss ρ\rho is not convex in rr, so the iteration can stop at a local minimum.
  • L1 with a floor δ>0\delta > 0: f(t)=t/(2δ)f(t) = t/(2\delta) for t≤δ2t \le \delta^2 and t−δ/2\sqrt t - \delta/2 beyond, so ρδ(r)=r2/(2δ)\rho_\delta(r) = r^2/(2\delta) for ∣r∣≤δ|r| \le \delta and ∣r∣−δ/2|r| - \delta/2 beyond, and 2f′(r2)=1/max⁡(∣r∣,δ)2f'(r^2) = 1/\max(|r|, \delta).

Lemma 4 (the L1 rule is within nδ/2n\delta/2 of least absolute deviations). Let b∗b^* be a fixed point of the L1 rule, that is b+=b∗b^+ = b^* when b=b∗b = b^*, and let m=min⁡β∑i∣yi−xi⊤β∣m = \min_\beta\sum_i|y_i - x_i^\top\beta|. Then m≤∑i∣yi−xi⊤b∗∣≤m+nδ/2m \le \sum_i|y_i - x_i^\top b^*| \le m + n\delta/2.

Proof. The left inequality is the definition of mm. Let Fδ(β)=∑iρδ(yi−xi⊤β)F_\delta(\beta) = \sum_i\rho_\delta(y_i - x_i^\top\beta); FδF_\delta is convex and differentiable, because ρδ\rho_\delta is convex with a continuous derivative. The majorizer GG of Lemma 3 at b∗b^* touches FδF_\delta at b∗b^* and lies above it, so the two have the same gradient there: ∇G(b∗)=−2∑iwirixi=−∑iρδ′(ri)xi=∇Fδ(b∗)\nabla G(b^*) = -2\sum_iw_ir_ix_i = -\sum_i\rho_\delta'(r_i)x_i = \nabla F_\delta(b^*), using 2f′(r2)r=ρδ′(r)2f'(r^2)r = \rho_\delta'(r). Since b∗b^* minimizes GG, ∇Fδ(b∗)=0\nabla F_\delta(b^*) = 0, and b∗b^* minimizes the convex FδF_\delta. From ∣r∣−δ/2≤ρδ(r)≤∣r∣|r| - \delta/2 \le \rho_\delta(r) \le |r|,

∑i∣yi−xi⊤b∗∣≤Fδ(b∗)+nδ2≤Fδ(βLAD)+nδ2≤m+nδ2,\sum_i|y_i - x_i^\top b^*| \le F_\delta(b^*) + \frac{n\delta}2 \le F_\delta(\beta_{\mathrm{LAD}}) + \frac{n\delta}2 \le m + \frac{n\delta}2,

where βLAD\beta_{\mathrm{LAD}} attains mm. □\square

What is not proved. Lemma 3 gives a nonincreasing loss sequence, which therefore converges, but it does not prove that the coefficients converge, and with the biweight they can converge to a local minimum. For a GLM, Lemmas 1 and 2 describe one step only. Newton's method converges quadratically near a maximizer where the information is nonsingular, but from a poor start the full step can increase the deviance, and when the maximum likelihood estimate does not exist (separation in a binary model) the iterates go to infinity. The implementation reports these cases through converged and separation_suspected; it does not halve steps.

Termination. Each pass of lines L3 to L7 is a finite computation: O(np)O(np) for η\eta, O(n)O(n) for the rule and Θ(np2)\Theta(np^2) for the weighted QR. The loop of line L2 runs at most maxit times, so the algorithm stops after O(maxit⋅np2)O(\text{maxit}\cdot np^2) operations, with converged true exactly when line L6 stopped it.

Complexity

One pass costs O(np)O(np) for η\eta, O(n)O(n) for the rule and Θ(np2)\Theta(np^2) for the QR of line L5, so kk passes cost Θ(knp2)\Theta(knp^2) time and Θ(np)\Theta(np) extra space. Forming X⊤WXX^\top WX instead of a QR halves the flops of one pass but squares the condition number. There is no useful bound on kk in terms of nn and pp. For GLMs with an estimate that exists, 5 to 10 passes are typical; for the L1 rule convergence is linear and can be slow when δ\delta is tiny. These counts are observed, not proved.

Properties

  • Fisher scoring in disguise. For any GLM the iteration is Fisher scoring, and the last X⊤WXX^\top WX divided by ϕ\phi is the estimated information. Its inverse gives the usual model-based standard errors.
  • Newton for canonical links. For the logit, log (Poisson) and identity (normal) links the iteration is Newton's method, which converges quadratically near a maximizer with nonsingular information. The log-likelihood is concave in bb, so a maximizer is global.
  • Descent for M-estimation. For Huber, biweight and smoothed L1 the loss sequence is nonincreasing (a majorize-minimize argument). For a convex loss the limit points are minimizers; for the biweight, a redescending loss, they can be local minima, so the start matters.
  • Exact one-step cases. With the identity link and normal responses, wi=1w_i = 1 and z=yz = y, and the first pass is the least squares fit. With the Huber rule and a threshold larger than every residual, the same happens.
  • Invariance. Only the ratios of the weights matter, which is why the constant factors of f′f' and the dispersion ϕ\phi can be dropped.

Variants and improvements

  • Step halving. If a full GLM step lowers the log-likelihood or leaves the valid range of μ\mu, halve it until it does not. The generalized linear model page implements this; the version here does not.
  • Quasi-likelihood and estimating equations. The same loop solves the quasi-likelihood equations, which need only a mean and a variance function, and the generalized estimating equations for clustered data, where line L5 becomes a block-weighted solve.
  • Robust regression with a robust start. For a redescending loss, start from a high-breakdown fit such as least trimmed squares and keep the scale fixed; this is the MM-estimator. The Huber M-estimator and Tukey's biweight pages treat the location case.
  • L1 and quantile regression. The floored weights approximate least absolute deviations; asymmetric weights approximate quantile regression. Linear programming solves both exactly and is usually faster.
  • Sparse recovery. Weights 1/(∣bj∣+ε)1/(|b_j| + \varepsilon) on the coefficients instead of the residuals give reweighted schemes for ℓ1\ell_1 and ℓp\ell_p penalties; the same majorization argument applies.

When to use it

Use the loop to fit any generalized linear model, to compute M-estimates of regression, and as the inner solver when the objective is a sum of terms that each depend on one residual or one linear predictor. It is short to write given a good weighted least squares routine, and each pass has the numerical quality of a QR solve. For least absolute deviations or quantile regression at scale, prefer a linear programming or interior point method; for very large nn or pp in a GLM, prefer a first-order or quasi-Newton method that does not factor XX each pass.

Pitfalls

  • Separation. If a hyperplane separates the 0s from the 1s of a binary response, the logistic likelihood has no maximizer: the deviance goes to 0 as ∥b∥→∞\lVert b\rVert \to \infty, the weights μi(1−μi)\mu_i(1 - \mu_i) go to 0 and the loop never converges. On the data y=(0,0,0,1,1,1)y = (0, 0, 0, 1, 1, 1) with x=1,…,6x = 1, \dots, 6, after 50 passes b=(−219,62.6)b = (-219, 62.6) and every fitted probability is within 10−810^{-8} of 0 or 1. Check for this case instead of reporting the last iterate; logistic regression discusses penalized remedies.
  • Zero counts. A Poisson group whose counts are all 0 sends its coefficient to −∞-\infty in the same way.
  • No step control. Far from the maximizer, a full Fisher scoring or Newton step can lower the likelihood. Use step halving or start from a sensible fit.
  • The scale in M-estimation. Huber and biweight weights depend on r/sr/s. Re-estimating ss inside the loop from the current residuals can break the descent property and, with the biweight, can collapse onto a subset. Fix ss from a robust start or update it by a separate rule.
  • Tiny floors. The L1 rule with a very small δ\delta gives weights near 1/δ1/\delta on the points the fit passes through, which makes line L5 badly conditioned and convergence slow.
  • Standard errors. For robust rules, the final weighted least squares covariance s2(X⊤WX)−1s^2(X^\top WX)^{-1} is not the covariance of the M-estimate. Use the sandwich form of the M-estimator page.

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.

iteratively_reweighted_least_squares.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iteratively-reweighted-least-squares/. The authors are listed in prov/N4YG7R.jsonl.
"""Iteratively reweighted least squares for GLMs and for M-estimation.

Each iteration computes the linear predictor eta = X b, asks a working rule
for weights w_i >= 0 and a working response z_i, and solves the weighted
least squares problem min sum w_i (z_i - x_i^T b)^2 by a Householder QR of
the rows scaled by sqrt(w_i).

Working rules:
  GLM rules (logistic, probit, Poisson): z = eta + (y - mu) g'(mu) and
  w = 1 / (V(mu) g'(mu)^2). This is Fisher scoring, and Newton for a canonical link.
  M rules (Huber, Tukey biweight, L1 with a floor delta): z = y and
  w = f'(r^2) for the loss rho(r) = f(r^2) with f concave, which makes each
  step a majorize-minimize step, so the loss never increases.
"""

import math
from statistics import NormalDist
from typing import NamedTuple

RANK_TOL = 1e-12
_STD = NormalDist()


class IRLSResult(NamedTuple):
    b: list            # the final coefficients
    iterations: int    # weighted least squares solves done
    converged: bool    # True if the step test of line L6 passed
    objective: list    # the objective after each iteration (deviance or M loss)


def weighted_ls(x: list, z: list, w: list) -> list:
    """argmin sum w_i (z_i - x_i^T b)^2 by Householder QR of the scaled rows; rows with w_i = 0 drop out."""
    rows = [[math.sqrt(wi) * v for v in xi] for xi, wi in zip(x, w) if wi > 0.0]
    rhs = [math.sqrt(wi) * zi for zi, wi in zip(z, w) if wi > 0.0]
    n = len(rows)
    p = len(x[0])
    if n < p:
        raise ValueError("fewer rows with positive weight than coefficients")
    col = [math.sqrt(math.fsum(rows[i][j] ** 2 for i in range(n))) for j in range(p)]
    for j in range(p):
        norm = math.sqrt(math.fsum(rows[i][j] ** 2 for i in range(j, n)))
        if norm == 0.0 or norm <= RANK_TOL * col[j]:
            raise ValueError("the weighted design has rank below p")
        alpha = -norm if rows[j][j] >= 0.0 else norm
        v = [rows[j][j] - alpha] + [rows[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] * rows[i][k] for i in range(j, n)) / vv
            for i in range(j, n):
                rows[i][k] -= s * v[i - j]
        s = 2.0 * math.fsum(v[i - j] * rhs[i] for i in range(j, n)) / vv
        for i in range(j, n):
            rhs[i] -= s * v[i - j]
    b = [0.0] * p
    for i in range(p - 1, -1, -1):
        b[i] = (rhs[i] - math.fsum(rows[i][k] * b[k] for k in range(i + 1, p))) / rows[i][i]
    return b


# ---------- GLM working rules: (w, z) from (y, eta), and the deviance ----------

def _xlogy(a: float, b: float) -> float:
    return 0.0 if a == 0.0 else a * math.log(b)


class Logistic:
    """Bernoulli response with the logit link (canonical): w = mu (1 - mu), z = eta + (y - mu) / w."""
    MU_EPS = 1e-12

    def mean(self, eta: float) -> float:
        return 1.0 / (1.0 + math.exp(-eta)) if eta >= 0.0 else math.exp(eta) / (1.0 + math.exp(eta))

    def working(self, y: list, eta: list) -> tuple[list, list]:
        w, z = [], []
        for yi, e in zip(y, eta):
            mu = min(max(self.mean(e), self.MU_EPS), 1.0 - self.MU_EPS)
            v = mu * (1.0 - mu)
            w.append(v)
            z.append(e + (yi - mu) / v)
        return w, z

    def objective(self, y: list, eta: list) -> float:
        """The deviance -2 log-likelihood, computed without overflow."""
        return 2.0 * math.fsum(math.log1p(math.exp(-abs(e))) + max(e, 0.0) - yi * e
                               for yi, e in zip(y, eta))


class Probit:
    """Bernoulli response with the probit link (not canonical): Fisher scoring, not Newton."""
    MU_EPS = 1e-12

    def mean(self, eta: float) -> float:
        return _STD.cdf(eta)

    def working(self, y: list, eta: list) -> tuple[list, list]:
        w, z = [], []
        for yi, e in zip(y, eta):
            mu = min(max(self.mean(e), self.MU_EPS), 1.0 - self.MU_EPS)
            d = max(_STD.pdf(e), 1e-300)  # d mu / d eta = 1 / g'(mu)
            w.append(d * d / (mu * (1.0 - mu)))
            z.append(e + (yi - mu) / d)
        return w, z

    def objective(self, y: list, eta: list) -> float:
        out = []
        for yi, e in zip(y, eta):
            mu = min(max(self.mean(e), self.MU_EPS), 1.0 - self.MU_EPS)
            out.append(-2.0 * (_xlogy(yi, mu) + _xlogy(1.0 - yi, 1.0 - mu)))
        return math.fsum(out)


class Poisson:
    """Poisson response with the log link (canonical): w = mu, z = eta + (y - mu) / mu."""

    def mean(self, eta: float) -> float:
        return math.exp(eta)

    def working(self, y: list, eta: list) -> tuple[list, list]:
        mus = [math.exp(e) for e in eta]
        return mus, [e + (yi - mu) / mu for yi, e, mu in zip(y, eta, mus)]

    def objective(self, y: list, eta: list) -> float:
        """The deviance 2 sum (y log(y / mu) - (y - mu))."""
        return 2.0 * math.fsum(_xlogy(yi, yi) - yi * e - (yi - math.exp(e)) for yi, e in zip(y, eta))


# ---------- M-estimation rules: rho(r / s) = f((r / s)^2) with f concave ----------

class Huber:
    """rho(u) = u^2 / 2 for |u| <= c, c |u| - c^2 / 2 beyond; weight min(1, c / |u|)."""

    def __init__(self, c: float = 1.345, scale: float = 1.0):
        self.c, self.s = c, scale

    def working(self, y: list, eta: list) -> tuple[list, list]:
        w = []
        for yi, e in zip(y, eta):
            u = abs(yi - e) / self.s
            w.append(1.0 if u <= self.c else self.c / u)
        return w, list(y)

    def objective(self, y: list, eta: list) -> float:
        c = self.c
        return math.fsum(u * u / 2.0 if u <= c else c * u - c * c / 2.0
                         for u in (abs(yi - e) / self.s for yi, e in zip(y, eta)))


class Biweight:
    """Tukey's biweight: rho(u) = (c^2 / 6)(1 - (1 - (u / c)^2)^3) for |u| <= c, c^2 / 6 beyond;
    weight (1 - (u / c)^2)^2, zero beyond c. The loss is not convex."""

    def __init__(self, c: float = 4.685, scale: float = 1.0):
        self.c, self.s = c, scale

    def working(self, y: list, eta: list) -> tuple[list, list]:
        w = []
        for yi, e in zip(y, eta):
            t = ((yi - e) / (self.s * self.c)) ** 2
            w.append((1.0 - t) ** 2 if t < 1.0 else 0.0)
        return w, list(y)

    def objective(self, y: list, eta: list) -> float:
        c = self.c
        out = []
        for yi, e in zip(y, eta):
            t = ((yi - e) / (self.s * c)) ** 2
            out.append(c * c / 6.0 * (1.0 - (1.0 - t) ** 3) if t < 1.0 else c * c / 6.0)
        return math.fsum(out)


class L1:
    """Least absolute deviations with a floor delta > 0: weight 1 / max(|r|, delta).
    This is exact majorize-minimize for the smoothed loss r^2 / (2 delta) (|r| <= delta),
    |r| - delta / 2 (beyond), which is within delta / 2 of |r|."""

    def __init__(self, delta: float = 1e-6):
        if not delta > 0.0:
            raise ValueError("delta must be positive")
        self.delta = delta

    def working(self, y: list, eta: list) -> tuple[list, list]:
        return [1.0 / max(abs(yi - e), self.delta) for yi, e in zip(y, eta)], list(y)

    def objective(self, y: list, eta: list) -> float:
        d = self.delta
        return math.fsum(r * r / (2.0 * d) if r <= d else r - d / 2.0
                         for r in (abs(yi - e) for yi, e in zip(y, eta)))


# ---------- the algorithm ----------

def _eta(x: list, b: list) -> list:
    return [math.fsum(a * c for a, c in zip(xi, b)) for xi in x]


def irls(x: list, y: list, rule, b0: list | None = None, tol: float = 1e-10,
         maxit: int = 100) -> IRLSResult:
    """Iteratively reweighted least squares with the given working rule.

    Each iteration costs one weighted least squares solve, Theta(n p^2).
    """
    if len(x) != len(y) or not x:
        raise ValueError("x and y must be nonempty and of the same length")
    p = len(x[0])
    b = list(b0) if b0 is not None else [0.0] * p  # @line L1
    history = []
    for k in range(1, maxit + 1):  # @line L2
        eta = _eta(x, b)  # @line L3
        w, z = rule.working(y, eta)  # @line L4
        b_new = weighted_ls(x, z, w)  # @line L5
        history.append(rule.objective(y, _eta(x, b_new)))
        step = math.sqrt(math.fsum((u - v) ** 2 for u, v in zip(b_new, b)))
        size = math.sqrt(math.fsum(v * v for v in b_new))
        if step <= tol * (size + tol):  # @line L6
            return IRLSResult(b_new, k, True, history)
        b = b_new  # @line L7
    return IRLSResult(b, maxit, False, history)  # @line L8


def separation_suspected(x: list, y: list, b: list, eps: float = 1e-8) -> bool:
    """For a binary GLM: True if some fitted probability is within eps of 0 or 1,
    the symptom of (quasi-)complete separation, where the MLE does not exist."""
    m = Logistic()
    return any(m.mean(e) < eps or m.mean(e) > 1.0 - eps for e in _eta(x, b))
test_iteratively_reweighted_least_squares.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iteratively-reweighted-least-squares/. The authors are listed in prov/N4YG7R.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from iteratively_reweighted_least_squares import (
    L1, Biweight, Huber, Logistic, Poisson, Probit, irls, separation_suspected, weighted_ls,
)

EX_X = [[1.0, float(t)] for t in [1, 2, 3, 4, 5, 6]]
EX_Y = [0, 0, 1, 0, 1, 1]


def solve(a, b):
    """Gauss-Jordan elimination; exact when the entries are Fractions."""
    k = len(a)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(k):
        piv = max(range(c, k), key=lambda r: abs(m[r][c]))
        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 newton_step_logistic(x, y, b, mean):
    """b + (X^T W X)^(-1) X^T (y - mu), W = diag(mu (1 - mu)): Newton on the log-likelihood."""
    p = len(b)
    mu = [mean(sum(a * c for a, c in zip(xi, b))) for xi in x]
    h = [[sum(m * (1 - m) * xi[i] * xi[j] for xi, m in zip(x, mu)) for j in range(p)] for i in range(p)]
    g = [sum((yi - m) * xi[i] for xi, yi, m in zip(x, y, mu)) for i in range(p)]
    d = solve(h, g)
    return [bi + di for bi, di in zip(b, d)]


def test_first_logistic_step_is_the_newton_step_exact():
    """At b = 0 every mu is 1/2, so the working weights 1/4 and responses 4y - 2 are exact floats."""
    rng = random.Random(1)
    for _ in range(10):
        n, p = rng.randint(5, 9), rng.randint(1, 3)
        x = [[1] + [rng.randint(-3, 3) for _ in range(p - 1)] for _ in range(n)]
        y = [rng.randint(0, 1) for _ in range(n)]
        w, z = Logistic().working(y, [0.0] * n)
        assert w == [0.25] * n and z == [4.0 * v - 2.0 for v in y]
        xf = [[Fraction(v) for v in r] for r in x]
        g = [[sum(Fraction(wi) * r[i] * r[j] for r, wi in zip(xf, w)) for j in range(p)] for i in range(p)]
        if any(c == 0 for c in [g[i][i] for i in range(p)]):
            continue
        try:
            irls_step = solve(g, [sum(Fraction(wi) * r[i] * Fraction(zi) for r, wi, zi in zip(xf, w, z)) for i in range(p)])
        except ZeroDivisionError:
            continue  # singular design
        newton = newton_step_logistic(xf, y, [Fraction(0)] * p, lambda e: Fraction(1, 2))
        assert irls_step == newton
    b1 = weighted_ls(EX_X, *reversed(Logistic().working(EX_Y, [0.0] * 6)))
    assert b1 == pytest.approx([-2.8, 0.8], abs=1e-12)
    assert newton_step_logistic([[Fraction(int(v)) for v in r] for r in EX_X], EX_Y, [Fraction(0)] * 2,
                                lambda e: Fraction(1, 2)) == [Fraction(-14, 5), Fraction(4, 5)]


def test_logistic_step_is_the_newton_step_anywhere():
    rng = random.Random(2)
    m = Logistic()
    for _ in range(20):
        n = rng.randint(6, 12)
        x = [[1.0, rng.uniform(-2, 2), rng.uniform(-2, 2)] for _ in range(n)]
        y = [rng.randint(0, 1) for _ in range(n)]
        b = [rng.uniform(-1, 1) for _ in range(3)]
        eta = [sum(a * c for a, c in zip(xi, b)) for xi in x]
        w, z = m.working(y, eta)
        step = weighted_ls(x, z, w)
        assert step == pytest.approx(newton_step_logistic(x, y, b, m.mean), rel=1e-9, abs=1e-9)


def test_page_example_converges_to_the_mle():
    fit = irls(EX_X, EX_Y, Logistic())
    assert fit.converged and fit.iterations <= 8
    assert fit.b == pytest.approx([-4.2490966, 1.2140276], abs=1e-6)
    mu = [Logistic().mean(r[0] * fit.b[0] + r[1] * fit.b[1]) for r in EX_X]
    for j in range(2):  # the score X^T (y - mu) is zero at the MLE
        assert abs(sum((yi - mi) * r[j] for r, yi, mi in zip(EX_X, EX_Y, mu))) < 1e-10
    assert fit.objective[-1] == pytest.approx(4.955973670099, abs=1e-9)
    assert not separation_suspected(EX_X, EX_Y, fit.b)


def test_poisson_and_probit_solve_their_score_equations():
    y = [2, 0, 3, 1, 4, 2, 7]
    fit = irls([[1.0]] * 7, y, Poisson())
    assert math.exp(fit.b[0]) == pytest.approx(sum(y) / 7, rel=1e-12)
    rng = random.Random(3)
    x = [[1.0, rng.uniform(0, 2)] for _ in range(40)]
    yc = [sum(1 for _ in range(10) if rng.random() < 1 - math.exp(-math.exp(0.2 + 0.7 * r[1]) / 10)) for r in x]
    fit = irls(x, yc, Poisson())
    mu = [math.exp(r[0] * fit.b[0] + r[1] * fit.b[1]) for r in x]
    for j in range(2):
        assert abs(sum((a - m) * r[j] for r, a, m in zip(x, yc, mu))) < 1e-8
    yb = [1 if rng.random() < 0.5 + 0.2 * (r[1] - 1) else 0 for r in x]
    fit = irls(x, yb, Probit())
    assert fit.converged
    pr = Probit()
    for j in range(2):
        s = 0.0
        for r, a in zip(x, yb):
            e = r[0] * fit.b[0] + r[1] * fit.b[1]
            mu = pr.mean(e)
            s += (a - mu) * math.exp(-e * e / 2) / math.sqrt(2 * math.pi) / (mu * (1 - mu)) * r[j]
        assert abs(s) < 1e-8


def test_m_estimation_never_increases_the_loss():
    """Majorize-minimize: for rho(r) = f(r^2) with f concave the loss is nonincreasing."""
    rng = random.Random(4)
    for _ in range(15):
        n = 25
        x = [[1.0, rng.uniform(0, 10)] for _ in range(n)]
        y = [1.0 + 0.5 * r[1] + rng.gauss(0, 1) + (rng.choice([0, 0, 0, 15]) if rng.random() < 0.3 else 0) for r in x]
        for rule in [Huber(1.345, 1.0), Biweight(4.685, 1.0), L1(1e-4)]:
            b0 = weighted_ls(x, y, [1.0] * n)
            start = rule.objective(y, [r[0] * b0[0] + r[1] * b0[1] for r in x])
            fit = irls(x, y, rule, b0=b0, maxit=60)
            seq = [start] + fit.objective
            for a, b in zip(seq, seq[1:]):
                assert b <= a * (1 + 1e-12) + 1e-12


def test_l1_is_within_n_delta_over_2_of_least_absolute_deviations():
    """A least absolute deviations line passes through two data points, so the minimum is found by trying all pairs."""
    rng = random.Random(5)
    for _ in range(8):
        n, delta = 12, 1e-3
        xs = [rng.uniform(0, 10) for _ in range(n)]
        y = [2.0 - 0.3 * v + rng.expovariate(1.0) * rng.choice([-1, 1]) for v in xs]
        x = [[1.0, v] for v in xs]
        best = math.inf
        for i, j in itertools.combinations(range(n), 2):
            s = (y[j] - y[i]) / (xs[j] - xs[i])
            a = y[i] - s * xs[i]
            best = min(best, sum(abs(yi - a - s * v) for yi, v in zip(y, xs)))
        fit = irls(x, y, L1(delta), maxit=500, tol=1e-13)
        loss = sum(abs(yi - fit.b[0] - fit.b[1] * v) for yi, v in zip(y, xs))
        assert best - 1e-9 <= loss <= best + n * delta / 2 + 1e-9


def test_huber_with_huge_threshold_is_least_squares():
    x = [[1.0, float(t)] for t in range(8)]
    y = [0.3, 1.1, 1.9, 3.2, 3.8, 5.1, 6.0, 30.0]
    fit = irls(x, y, Huber(c=1e9))
    assert fit.converged and fit.iterations == 2
    assert fit.b == pytest.approx(weighted_ls(x, y, [1.0] * 8), abs=1e-12)


def test_robust_rules_resist_an_outlier():
    x = [[1.0, float(t)] for t in range(1, 11)]
    y = [1.1, 2.0, 2.9, 4.2, 5.0, 5.9, 7.1, 8.0, 30.0, 10.1]
    assert weighted_ls(x, y, [1.0] * 10)[1] > 1.8
    for rule in [Huber(1.345, 0.5), Biweight(4.685, 0.5), L1(1e-6)]:
        fit = irls(x, y, rule, maxit=200)
        assert fit.converged and abs(fit.b[1] - 1.0) < 0.05


def test_separation_is_flagged():
    y = [0, 0, 0, 1, 1, 1]
    fit = irls(EX_X, y, Logistic(), maxit=50)
    assert not fit.converged
    assert separation_suspected(EX_X, y, fit.b)
    assert fit.objective[-1] < 1e-10  # the deviance goes to 0, its infimum, which no finite b attains


def test_bad_inputs():
    with pytest.raises(ValueError):
        L1(0.0)
    with pytest.raises(ValueError):
        irls([[1.0, 1.0], [1.0, 1.0], [1.0, 1.0]], [0, 1, 0], Logistic())
    with pytest.raises(ValueError):
        irls([], [], Logistic())

History

Nelder and Wedderburn (1972) unified regression for normal, binomial, Poisson and gamma responses as generalized linear models and showed that one iterative weighted regression gives the maximum likelihood estimate for all of them; earlier probit analysis already used working responses and weights. Beaton and Tukey (1974) and Holland and Welsch (1977) applied reweighting to robust regression with the biweight and other weight functions. Green (1984) gave the general treatment of the method for maximum likelihood, its Newton and Fisher scoring forms and its robust and resistant variants.

References

  1. J. A. Nelder and R. W. M. Wedderburn, Generalized linear models, Journal of the Royal Statistical Society Series A 135(3), 1972, pp. 370 to 384, The whole paper (maximum likelihood for exponential family responses by iterative weighted linear regression)
  2. Paul W. Holland and Roy E. Welsch, Robust regression using iteratively reweighted least-squares, Communications in Statistics, Theory and Methods 6(9), 1977, pp. 813 to 827, The whole paper (weight functions for robust regression, their tuning constants and the reweighting loop)
  3. P. J. Green, Iteratively reweighted least squares for maximum likelihood estimation, and some robust and resistant alternatives, Journal of the Royal Statistical Society Series B 46(2), 1984, pp. 149 to 192 with the discussion, The whole paper (the general form of the iteration, Fisher scoring and Newton steps, robust and resistant alternatives)
  4. P. McCullagh and J. A. Nelder, Generalized Linear Models, second edition, Chapman and Hall, 1989, Chapter 2 (the fitting algorithm with the working response and the iterative weights)

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
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