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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and a working response for every observation from the current coefficients , then fits on with those weights to get the next . 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 design with rows (the intercept is one of the columns), a response , and a working rule that maps the response and the current linear predictor to weights and working responses .
Output. A coefficient vector at which the weighted fit reproduces itself: fitting on with weights gives back.
Two families of rules cover most uses:
| problem | objective | working response | weight |
|---|---|---|---|
| GLM with mean , variance function | maximize the likelihood | ||
| logistic regression (logit link) | maximize the likelihood | ||
| Poisson regression (log link) | maximize the likelihood | ||
| M-estimation, with concave | minimize | , proportional to | |
| Huber loss, threshold , scale | as above | ||
| Tukey biweight, threshold , scale | as above | inside, outside | |
| least absolute deviations, floor | minimize |
Here and .
The algorithm
ITERATIVELY-REWEIGHTED-LEAST-SQUARES(X, y, RULE, b⁽⁰⁾, tol, maxit)- 1
b ← b⁽⁰⁾ ▷ often 0, or a least squares fit - 2
for k ← 1 to maxit do - 3
η ← X b - 4
(w, z) ← RULE(y, η) ▷ weights and working response from the current fit - 5
b⁺ ← argmin_β Σᵢ wᵢ (zᵢ - xᵢᵀβ)² ▷ weighted least squares by QR of √w-scaled rows - 6
if ‖b⁺ - b‖ ≤ tol · (‖b⁺‖ + tol) then return (b⁺, converged) - 7
b ← b⁺ - 8
return (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 , as on the weighted least squares page; rows with (the biweight beyond ) drop out. For a GLM, line L4 needs , and the implementation keeps a small distance away from the boundary of its range so that and stay finite. The dispersion of the GLM cancels and is not needed. For M-estimation the scale 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 , , and the model . Start at . Then every , every weight is , and . With equal weights, line L5 is ordinary least squares of on : the slope is and the intercept . This is exactly the Newton step from . The passes go on:
| deviance | |||
|---|---|---|---|
| 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 stops after 7 passes. At the limit the score is zero.
A robust line. For and , where the ninth point is a gross error, ordinary least squares gives the slope 1.892. Starting from with the scale fixed at , the Huber rule () gives slope 1.040 after 8 passes, the biweight () gives 1.002 after 7 passes with weight 0 on the bad point, and the L1 rule () 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 . For a GLM, the score is and the expected information is ; substituting gives , a Fisher scoring step. For the logit link 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 with concave, the tangent line of gives a weighted sum of squares that lies above the loss and touches it at the current ; line L5 minimizes that upper bound, so the loss cannot increase. The L1 weights with a floor do this exactly for a smoothed absolute loss, and a fixed point is within 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. is a fixed real matrix with rows , and line L5 is always applied to a weighted design of rank (the code raises an error otherwise). By the proof on the weighted least squares page, line L5 then returns the unique minimizer
of . 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 have an exponential family law with mean , variance and link , with smooth and strictly monotone. With and , all at the current , the step of line L5 is
where is the score and the expected information.
Proof. The log-likelihood of observation is plus a term free of , with and . By the chain rule, , so
The expected information is . So , since .
The dispersion cancels, so the iteration does not need it.
Lemma 2 (for the logistic model the step is the Newton step). For , and the log-likelihood , the Newton step equals the step of line L5 with and .
Proof. , so and , which does not depend on . The Newton step is
The same argument works for every canonical link, where and the observed information has no term in , so it equals . For a link that is not canonical, such as the probit link, the observed information has an extra term with factor , and the step is Fisher scoring, not Newton. At in the logistic model every , so and are rational, and the first step can be checked in exact arithmetic.
Lemma 3 (M-estimation: the loss never increases). Let with differentiable, nondecreasing and concave on , and . With and for the current residuals , the step satisfies . Multiplying all by one positive constant does not change .
Proof. Concavity gives for all . With and , summing over ,
with equality at . Line L5 minimizes , which is up to a constant, so . The scale statement holds because a constant factor in all weights does not change the minimizer.
The rules of the implementation fit Lemma 3, with for a fixed scale :
- Huber: for and beyond. Then is continuous and nonincreasing, so is concave, and .
- Tukey biweight: for and beyond. Then for and beyond, which is nonincreasing, and . The loss is not convex in , so the iteration can stop at a local minimum.
- L1 with a floor : for and beyond, so for and beyond, and .
Lemma 4 (the L1 rule is within of least absolute deviations). Let be a fixed point of the L1 rule, that is when , and let . Then .
Proof. The left inequality is the definition of . Let ; is convex and differentiable, because is convex with a continuous derivative. The majorizer of Lemma 3 at touches at and lies above it, so the two have the same gradient there: , using . Since minimizes , , and minimizes the convex . From ,
where attains .
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: for , for the rule and for the weighted QR. The loop of line L2 runs at most maxit times, so the algorithm stops after operations, with converged true exactly when line L6 stopped it.
Complexity
One pass costs for , for the rule and for the QR of line L5, so passes cost time and extra space. Forming instead of a QR halves the flops of one pass but squares the condition number. There is no useful bound on in terms of and . 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 is tiny. These counts are observed, not proved.
Properties
- Fisher scoring in disguise. For any GLM the iteration is Fisher scoring, and the last divided by 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 , 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, and , 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 and the dispersion can be dropped.
Variants and improvements
- Step halving. If a full GLM step lowers the log-likelihood or leaves the valid range of , 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 on the coefficients instead of the residuals give reweighted schemes for and 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 or in a GLM, prefer a first-order or quasi-Newton method that does not factor 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 , the weights go to 0 and the loop never converges. On the data with , after 50 passes and every fitted probability is within 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 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 . Re-estimating inside the loop from the current residuals can break the descent property and, with the biweight, can collapse onto a subset. Fix from a robust start or update it by a separate rule.
- Tiny floors. The L1 rule with a very small gives weights near 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 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.
# 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
- 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)
- 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)
- 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)
- 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.
| 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 N4YG7R Edit this page History Report an error Markdown