Algorithmcore
Fisher scoring
Also called method of scoring, Fisher's scoring algorithm.
Maximizes a likelihood by Newton steps that use the expected information in place of the observed one. For GLMs it is IRLS, and for canonical links it equals Newton's method.
- Time
- O(t (n p^2 + p^3)) worst
- Space
- O(p^2) extra
- Where
- n = the number of observations; p = the number of parameters; t = the number of iterations
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- R. A. Fisher, C. I. Bliss, 1935
Fisher scoring finds a maximum likelihood estimate by repeated Newton steps on the likelihood equation, with one change: the Hessian of the log-likelihood is replaced by minus its expectation, the Fisher information . The expected information is positive definite under mild conditions, so each step goes uphill, and it is often simpler to compute than the observed Hessian. For a generalized linear model, a scoring step is one weighted least squares fit, which is why the method is also called iteratively reweighted least squares. For a canonical link, such as logistic regression or Poisson regression with a log link, the expected and the observed information are equal, and scoring is exactly Newton's method.
In plain words
You want the top of a hill, the parameter value that makes the data most likely. At your current position you can measure the slope. Newton's method also measures how the slope is bending, and jumps to where the bend says the top is.
Fisher scoring uses the average bend instead: the bend you would expect, on average, over all data sets the model could produce at this parameter value. The average bend always points to a top, never to a valley, so the method moves uphill when the actual bend would send Newton's method the wrong way. Near the top, the actual and the average bend are close, so the method is almost as fast as Newton's.
If a step is too long and the height drops, cut it in half until the height no longer drops.
The problem
The input is a log-likelihood of a sample, , given through its score and the expected information of the sample , which is times the information of one observation for iid data. must be positive definite at every point the method visits. Optionally itself is given, for step control. The input also has a start , a tolerance and a limit on the number of iterations.
The output is a point with , which approximates a root of the likelihood equation , and the matrix , the usual estimate of the covariance of . If the test is not met in iterations, or no step along the scoring direction raises , the output says that the method did not converge.
For a GLM with design rows , mean , , and variance function ,
The algorithm
FISHER-SCORING(U, I, ℓ, θ_0, ε, t_max)- 1
θ ← θ_0 - 2
for t ← 0 to t_max - 1 do - 3
g ← U(θ) ▷ score of the sample at θ - 4
H ← I(θ) ▷ expected information of the sample - 5
δ ← solution of H δ = g ▷ the scoring direction - 6
if gᵀδ ≤ ε then return θ, H⁻¹, converged - 7
s ← 1 - 8
while ℓ(θ + sδ) < ℓ(θ) and s > s_min do s ← s / 2 - 9
if ℓ(θ + sδ) < ℓ(θ) then return θ, H⁻¹, stalled - 10
θ ← θ + sδ - 11
return θ, I(θ)⁻¹, not converged
Line L5 solves a positive definite system; a Cholesky factorization is the usual choice. The quantity in line L6 is the score test statistic for the current point, so the stopping rule does not depend on how the parameters are scaled. Lines L7 to L9 are step halving. Without they are skipped and every step has , which is plain scoring.
For a GLM, put and the working response . Then and , so the full step is the weighted least squares fit of on with weights . That is the IRLS form of the same step.
Example
Logistic and probit regression. The data are the doses , each given to 10 subjects, with and responses; the model has an intercept and a slope in the dose, and the start is . The table gives the scoring iterates without halving, computed in double precision. For the logit link, Newton's method gives the same iterates to all printed digits, as Lemma 5 of the proof says it must.
| logit | logit | probit | probit | |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
The logit errors (the largest coordinate distance to the final estimate) are , , , and below : quadratic convergence, as for Newton's method. The probit errors are , , , and : each step gains a roughly constant number of digits, which is linear convergence with a small rate. Newton's method with the observed information gives the same first probit step, because the two informations agree at , and then differs from the second step on. It reaches the same estimate in 5 steps instead of 6. At the estimate, the inverse information gives the standard errors and (logit) and and (probit).
Cauchy location. For 25 draws from a Cauchy law with location 2 (seed 7 of Python's random.Random), the information of the sample is , a constant, while the observed information with is negative far from the data. From the sample median, Newton's method takes 3 steps and scoring with halving takes 8 to reach the global maximizer . From the smallest observation, Newton's method stops at the stationary point , and from the largest at . Scoring with halving reaches from every start tried, which agrees with a dense grid search over the range of the data.
Correctness
The returned point satisfies , and with it is a root of the likelihood equation, because is positive definite. The direction has positive inner product with the gradient, so it points uphill, and step halving finds a step that does not lower . For a canonical exponential family the Hessian of does not depend on the data, so it equals minus its expectation, and scoring is Newton's method step by step. In general, the Jacobian of the full scoring map at a root is , where is the observed information, so the local rate of convergence is the spectral radius of that matrix. The full proofs are below. They do not show that the limit is the global maximum, which is false in general.
Proof: Fisher scoring stops at an approximate root of the score, never lowers the likelihood, and equals Newton's method for canonical linksfull
The arithmetic is exact. is the log-likelihood of the sample, its score and the expected information of the sample, which is symmetric and positive definite at every where it is used. Line numbers refer to the main pseudocode. Write for one full scoring step.
Lemma 1 (fixed points are roots of the score). if and only if .
Proof. , and is nonsingular.
Lemma 2 (the stopping test). Let and as in lines L3 to L5. Then , with equality if and only if . If line L6 returns, then ; for this means .
Proof. is positive definite because is. So the quadratic form is nonnegative and is zero only for . The return in line L6 happens only when the test holds.
The quantity is the score statistic for the hypothesis that the current is the true value. So the test of line L6 stops when the data give no evidence against the current point; it does not depend on how the parameters are scaled.
Lemma 3 (ascent direction). Let be differentiable at and . Then there is with for all .
Proof. The derivative of at is , which is positive by Lemma 2. A function with positive derivative at 0 is larger than its value at 0 on some interval .
Lemma 4 (the likelihood never falls). With given, every step taken in line L10 satisfies . The loop of line L8 ends after at most halvings.
Proof. Line L9 returns without a step when the halved step still lowers . So a step that reaches line L10 has . The loop of line L8 halves , starting from 1, and stops when at the latest. By Lemma 3, if , the first power of 2 that is at most is larger than and gives an increase, so the loop stops there and line L9 does not return.
Lemma 5 (canonical links: scoring is Newton's method). Let be independent with densities , a canonical exponential family, and (a generalized linear model with canonical link). Then the observed information equals the expected information for every and every data set, so each scoring step equals the Newton step from the same point.
Proof. . Its gradient is and its Hessian is , which does not contain the data . So it equals its own expectation: . Line L5 then solves the same system as Newton's method.
Logistic regression () and Poisson regression with log link () are of this form. For them the local quadratic convergence of Newton's method near a root with nonsingular applies to scoring without change.
Lemma 6 (local rate for other models). Let and be continuously differentiable near a root of , and . The Jacobian of at is
Proof. Differentiate by the product rule. The term that contains the derivative of is multiplied by , and the other term is .
By Ostrowski's theorem on fixed-point iterations, if the spectral radius of is less than 1, then full scoring steps started close enough to converge to , and the error falls asymptotically by about the factor per step. Under a correct model, and both converge to the information of one observation, so as grows; this is a statement about large samples, and for a given data set can be near or above 1.
Theorem. (a) If FISHER-SCORING returns in line L6, the returned satisfies , and with it is a root of the likelihood equation. (b) With given, the sequence of accepted iterates is nondecreasing. (c) For a canonical exponential family or a GLM with canonical link, without step halving, the iterates are exactly those of Newton's method from the same start.
Proof. (a) is Lemma 2, (b) is Lemma 4 and (c) is Lemma 5.
The theorem does not say that the returned root is the global maximizer, or that the iteration converges from every start. Neither is true in general: a likelihood can have several local maxima, and for separated data in logistic regression the maximum is not attained at any finite .
Complexity
For a GLM, one iteration computes the linear predictors in , the score in , the information in , and solves the system in . Each halving costs one more log-likelihood, . Over iterations the time is plus the halvings, and the extra space is for and its factor.
The number of iterations depends on the problem. With a canonical link and a start near the estimate, convergence is quadratic and 5 to 10 iterations are typical. Otherwise it is linear with the rate of Lemma 6 of the proof, which is small when the model fits and is large.
Scoring needs no second derivatives of the data terms, only and , which is part of its appeal. Compared with Newton's method it saves little per step for GLMs but gives a matrix that is positive definite whenever has full column rank and all weights are positive.
Properties
- Ascent with halving. With step halving the log-likelihood never decreases.
- Invariant to reparametrization of the linear kind. If with invertible, the iterates in map to the iterates in , and the stopping test of line L6 is unchanged.
- Covariance for free. at the end is the inverse expected information, the standard covariance estimate of asymptotic normality of the MLE. For a non-canonical link it differs from the inverse observed information at finite .
- One-step efficiency. One full scoring step from a -consistent start gives an estimator with the same limit law as the MLE (van der Vaart, Section 5.7). This is a statement about large samples, not about one data set.
- Exact for linear models. For a normal linear model the information does not depend on , and one step from any start gives the least squares estimate exactly.
Variants and improvements
- Newton-Raphson. Use the observed information . It is faster near the root for non-canonical models, but can be indefinite away from it.
- Mixed strategies. Start with scoring steps for safety and switch to Newton steps near the root, or use when it is positive definite and otherwise.
- Gauss-Newton. For nonlinear least squares with normal errors, scoring is the Gauss-Newton algorithm, and Levenberg-Marquardt damping can replace halving.
- Quasi-likelihood and estimating equations. The same step with and fits generalized estimating equations and quasi-likelihood models.
- Line search and trust regions. Halving is the simplest step control; Armijo line search or a trust region gives the same guarantee with fewer function evaluations.
- Incomplete data. When the expected complete-data information is easy and the observed-data information is not, EM or a scoring step with an estimated information can be used.
When to use it
Use Fisher scoring for generalized linear models, nonlinear regression and other models where the expected information has a closed form and the observed Hessian is messy or indefinite. It is the default fitting method of most GLM software. For models with canonical links it is identical to Newton's method, so nothing is lost. For models with many parameters, where forming and factoring a matrix costs too much, use a quasi-Newton method or a first-order method instead.
Pitfalls
- Separation in logistic regression. If a hyperplane separates the responses and , the likelihood increases toward a supremum that is not attained, and the coefficients grow without bound. Scoring may report convergence at a huge , because the score and the information both go to zero. Check the fitted probabilities: if they are all within rounding of the responses, the estimate does not exist.
- Starting values. For the identity or square-root link with Poisson data, or the identity link with binomial data, a step can leave the parameter space (a negative mean). The log-likelihood is then undefined; halving must treat it as , and the start must be inside the space.
- A root is not the maximum. Like Newton's method, scoring finds a root of the score. With a multimodal likelihood, start from several points or from a consistent estimate.
- Expected versus observed standard errors. For non-canonical links, and give different standard errors. Both are valid asymptotically; say which one is reported.
- Loose tolerance. A test on the change in alone can stop early on a flat ridge. The test uses the scale of the information; with linear convergence, a tolerance of can still leave errors near in .
- Singular information. If does not have full column rank, or a fitted weight is zero, is singular. Remove aliased columns before fitting.
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/fisher-scoring/. The authors are listed in prov/Y142G8.jsonl.
import math
from collections.abc import Callable, Sequence
from typing import NamedTuple
Vector = list
Matrix = list
class ScoringResult(NamedTuple):
theta: list # the last iterate
cov: list # inverse expected information at theta
iterations: int # number of steps taken
converged: bool # True when the decrement g' I^-1 g fell to tol
path: list # all iterates, path[0] = theta0
logliks: list # log-likelihood at each iterate (empty without loglik)
def solve(a: Matrix, b: Vector) -> Vector:
"""Solve a x = b by Gaussian elimination with partial pivoting.
Works for float and Fraction entries. Precondition: a is square and
nonsingular. Cost: O(k^3) for a k x k matrix.
"""
k = len(a)
m = [list(row) + [b[i]] for i, row in enumerate(a)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ZeroDivisionError("singular information matrix")
m[c], m[p] = m[p], m[c]
for r in range(c + 1, k):
f = m[r][c] / m[c][c]
if f != 0:
for j in range(c, k + 1):
m[r][j] = m[r][j] - f * m[c][j]
x = [0] * k
for r in range(k - 1, -1, -1):
s = m[r][k]
for j in range(r + 1, k):
s = s - m[r][j] * x[j]
x[r] = s / m[r][r]
return x
def inverse(a: Matrix) -> Matrix:
"""Return the inverse of a nonsingular square matrix, column by column."""
k = len(a)
cols = [solve(a, [1 if i == j else 0 for i in range(k)]) for j in range(k)]
return [[cols[j][i] for j in range(k)] for i in range(k)]
def fisher_scoring(
score: Callable[[Vector], Vector],
information: Callable[[Vector], Matrix],
theta0: Sequence,
loglik: Callable[[Vector], float] | None = None,
tol: float = 1e-10,
max_iter: int = 100,
min_step: float = 2.0 ** -30,
) -> ScoringResult:
"""Maximize a log-likelihood by Fisher scoring with step halving.
score(theta) is the score of the sample U_n(theta), information(theta) the
expected information I_n(theta), which must be positive definite. With
loglik given, each step is halved until the log-likelihood does not fall.
Stops when g' I^-1 g <= tol. Exact for Fraction inputs when loglik is None.
Cost per step: one score, one information, O(k^3) for the solve.
"""
theta = list(theta0) # @line L1
path = [list(theta)]
lls = [loglik(theta)] if loglik is not None else []
for t in range(max_iter): # @line L2
g = score(theta) # @line L3
h = information(theta) # @line L4
delta = solve(h, g) # @line L5
dec = sum(gi * di for gi, di in zip(g, delta))
if dec <= tol: # @line L6
return ScoringResult(theta, inverse(h), t, True, path, lls)
s = 1 # @line L7
new = [ti + s * di for ti, di in zip(theta, delta)]
if loglik is not None:
l_old = lls[-1]
l_new = loglik(new)
while l_new < l_old and s > min_step: # @line L8
s = s / 2
new = [ti + s * di for ti, di in zip(theta, delta)]
l_new = loglik(new)
if l_new < l_old: # @line L9
return ScoringResult(theta, inverse(h), t, False, path, lls)
lls.append(l_new)
theta = new # @line L10
path.append(list(theta))
return ScoringResult(theta, inverse(information(theta)), max_iter, False, path, lls) # @line L11
# Generalized linear models: mean function, its derivative and the variance.
def _phi(x: float) -> float:
return math.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)
def _sigmoid(x: float) -> float:
if x >= 0:
return 1.0 / (1.0 + math.exp(-x))
e = math.exp(x)
return e / (1.0 + e)
LINKS = {
# name: (mu(eta), dmu/deta(eta))
"logit": (_sigmoid, lambda e: _sigmoid(e) * _sigmoid(-e)),
"probit": (lambda e: 0.5 * math.erfc(-e / math.sqrt(2.0)), _phi),
"log": (math.exp, math.exp),
"identity": (lambda e: e, lambda e: 1.0),
}
def _binomial_ll(y: float, eta: float, link: str) -> float:
if link == "logit":
# log mu = -log(1 + e^-eta), log(1 - mu) = -log(1 + e^eta), computed stably
lp = -(math.log1p(math.exp(-eta)) if eta > -30 else -eta + math.log1p(math.exp(eta)))
lq = -(math.log1p(math.exp(eta)) if eta < 30 else eta + math.log1p(math.exp(-eta)))
else:
p = 0.5 * math.erfc(-eta / math.sqrt(2.0))
q = 0.5 * math.erfc(eta / math.sqrt(2.0))
if (y > 0 and p == 0.0) or (y < 1 and q == 0.0):
return -math.inf
lp = math.log(p) if p > 0 else 0.0
lq = math.log(q) if q > 0 else 0.0
return y * lp + (1 - y) * lq
def _poisson_ll(y: float, eta: float, link: str) -> float:
mu = math.exp(eta) if link == "log" else eta
if mu <= 0:
return -math.inf if (y > 0 or link == "identity") else 0.0
return y * math.log(mu) - mu - math.lgamma(y + 1)
FAMILIES = {
# name: (variance(mu), loglik of one observation)
"binomial": (lambda m: m * (1.0 - m), _binomial_ll),
"poisson": (lambda m: m, _poisson_ll),
}
class GLMFit(NamedTuple):
beta: list
cov: list
iterations: int
converged: bool
separated: bool
loglik: float
path: list
def glm_fisher_scoring(
x: Sequence[Sequence[float]],
y: Sequence[float],
family: str = "binomial",
link: str = "logit",
beta0: Sequence[float] | None = None,
tol: float = 1e-10,
max_iter: int = 100,
halving: bool = True,
) -> GLMFit:
"""Fit a GLM by Fisher scoring. x is n x p with full column rank.
Score U = sum x_i (y_i - mu_i) mu'_i / V(mu_i); information
I = sum x_i x_i' mu'_i^2 / V(mu_i). For the identity link with Poisson
data, beta0 must give positive means. halving=False takes full steps
(plain scoring). separated is True for a binomial
fit whose fitted means all lie within 1e-8 of the responses.
Cost per step: O(n p^2 + p^3).
"""
mean_fn, dmean = LINKS[link]
var_fn, ll_one = FAMILIES[family]
p = len(x[0])
def eta_of(b):
return [sum(xi[j] * b[j] for j in range(p)) for xi in x]
def score(b):
g = [0.0] * p
for xi, yi, e in zip(x, y, eta_of(b)):
m, d = mean_fn(e), dmean(e)
v = var_fn(m)
w = (yi - m) * d / v if v > 0 else 0.0 # a mean at 0 or 1 adds nothing
for j in range(p):
g[j] += xi[j] * w
return g
def information(b):
h = [[0.0] * p for _ in range(p)]
for xi, e in zip(x, eta_of(b)):
m, d = mean_fn(e), dmean(e)
v = var_fn(m)
w = d * d / v if v > 0 else 0.0
for j in range(p):
for k in range(p):
h[j][k] += xi[j] * xi[k] * w
return h
def loglik(b):
return sum(ll_one(yi, e, link) for yi, e in zip(y, eta_of(b)))
start = list(beta0) if beta0 is not None else [0.0] * p
res = fisher_scoring(score, information, start, loglik if halving else None, tol, max_iter)
mus = [mean_fn(e) for e in eta_of(res.theta)]
separated = family == "binomial" and all(abs(m - yi) < 1e-8 for m, yi in zip(mus, y))
return GLMFit(res.theta, res.cov, res.iterations, res.converged, separated, loglik(res.theta), res.path)
test_fisher_scoring.py 233 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fisher-scoring/. The authors are listed in prov/Y142G8.jsonl.
import math
import random
from fractions import Fraction
from statistics import NormalDist
from fisher_scoring import LINKS, FAMILIES, fisher_scoring, glm_fisher_scoring, inverse, solve
ND = NormalDist()
# Reference: Newton-Raphson with the observed information, derived by hand.
# For a GLM, -d2 l / d beta d beta' = sum x x' [mu'^2 / V - (y - mu) c'(eta)], c = mu' / V.
def c_prime(link: str, eta: float) -> float:
if link in ("logit", "log"):
return 0.0 # canonical links: c = 1
if link == "probit":
p = 0.5 * math.erfc(-eta / math.sqrt(2.0))
f = math.exp(-0.5 * eta * eta) / math.sqrt(2.0 * math.pi)
v = p * (1.0 - p)
return (-eta * f * v - f * f * (1.0 - 2.0 * p)) / (v * v)
if link == "identity":
return -1.0 / (eta * eta) # Poisson with identity link: c = 1 / eta
raise ValueError(link)
def newton_glm(x, y, family, link, beta0, tol=1e-10, max_iter=100):
mean_fn, dmean = LINKS[link]
var_fn, _ = FAMILIES[family]
p = len(x[0])
b = list(beta0)
path = [list(b)]
for _ in range(max_iter):
g = [0.0] * p
j = [[0.0] * p for _ in range(p)]
for xi, yi in zip(x, y):
e = sum(xi[k] * b[k] for k in range(p))
m, d = mean_fn(e), dmean(e)
v = var_fn(m)
w = (yi - m) * d / v
h = d * d / v - (yi - m) * c_prime(link, e)
for r in range(p):
g[r] += xi[r] * w
for s in range(p):
j[r][s] += xi[r] * xi[s] * h
delta = solve(j, g)
if sum(a * c for a, c in zip(g, delta)) <= tol:
return b, path
b = [bi + di for bi, di in zip(b, delta)]
path.append(list(b))
return b, path
def make_data(seed, n, beta, family, link):
rng = random.Random(seed)
mean_fn, _ = LINKS[link]
x, y = [], []
for _ in range(n):
xi = [1.0, rng.gauss(0, 1), rng.gauss(0, 1)]
m = mean_fn(sum(a * c for a, c in zip(xi, beta)))
if family == "binomial":
yi = 1.0 if rng.random() < m else 0.0
else:
# Poisson by inversion of the distribution function
u, k, pk = rng.random(), 0, math.exp(-m)
cum = pk
while u > cum:
k += 1
pk *= m / k
cum += pk
yi = float(k)
x.append(xi)
y.append(yi)
return x, y
def test_solve_and_inverse_exact():
a = [[Fraction(4), Fraction(1), Fraction(2)], [Fraction(1), Fraction(3), Fraction(0)], [Fraction(2), Fraction(0), Fraction(5)]]
inv = inverse(a)
for i in range(3):
for j in range(3):
assert sum(a[i][k] * inv[k][j] for k in range(3)) == (1 if i == j else 0)
def test_poisson_mean_one_step_exact():
# l(mu) = sum y log mu - n mu, U = sum y / mu - n, I = n / mu. One step lands on y-bar.
ys = [3, 0, 4, 1, 1, 5, 2]
n, s = len(ys), sum(ys)
for mu0 in (Fraction(1, 3), Fraction(1), Fraction(10)):
res = fisher_scoring(lambda t: [s / t[0] - n], lambda t: [[n / t[0]]], [mu0], tol=0)
assert res.path[1] == [Fraction(s, n)]
assert res.converged and res.iterations == 1
assert res.cov == [[Fraction(s, n) / n]] # inverse information: y-bar / n
def test_normal_linear_model_one_step_equals_least_squares_exact():
x = [[Fraction(1), Fraction(v)] for v in (0, 1, 2, 3, 5)]
y = [Fraction(v) for v in (1, 2, 2, 5, 7)]
xtx = [[sum(r[i] * r[j] for r in x) for j in range(2)] for i in range(2)]
xty = [sum(r[i] * yi for r, yi in zip(x, y)) for i in range(2)]
ols = solve(xtx, xty)
def score(b):
res = [yi - r[0] * b[0] - r[1] * b[1] for r, yi in zip(x, y)]
return [sum(r[i] * e for r, e in zip(x, res)) for i in range(2)]
out = fisher_scoring(score, lambda b: xtx, [Fraction(-4), Fraction(9)], tol=0)
assert out.path[1] == ols and out.theta == ols and out.iterations == 1
def test_canonical_links_scoring_equals_newton_step_by_step():
cases = [
("binomial", "logit", [-0.5, 1.0, -0.7], 11),
("poisson", "log", [0.3, 0.5, -0.4], 12),
]
for family, link, beta, seed in cases:
x, y = make_data(seed, 200, beta, family, link)
fit = glm_fisher_scoring(x, y, family, link, halving=False)
_, npath = newton_glm(x, y, family, link, [0.0, 0.0, 0.0])
assert fit.converged
# with step halving the path may differ, but the limit is the same
safe = glm_fisher_scoring(x, y, family, link)
assert max(abs(u - v) for u, v in zip(safe.beta, fit.beta)) < 1e-8
assert len(fit.path) == len(npath)
for a, b in zip(fit.path, npath):
assert max(abs(u - v) for u, v in zip(a, b)) < 1e-12
def test_non_canonical_links_same_mle_different_path():
cases = [
("binomial", "probit", [-0.3, 0.8, -0.5], 21, [0.0, 0.0, 0.0]),
("poisson", "identity", [3.0, 0.6, -0.5], 22, [3.0, 0.0, 0.0]),
]
for family, link, beta, seed, start in cases:
x, y = make_data(seed, 300, beta, family, link)
fit = glm_fisher_scoring(x, y, family, link, beta0=start, tol=1e-20)
nb, npath = newton_glm(x, y, family, link, start, tol=1e-20)
assert fit.converged
assert max(abs(u - v) for u, v in zip(fit.beta, nb)) < 1e-8
# the plain iterates differ (for probit not at step 1: at eta = 0 the
# observed and expected information agree, so the first steps coincide)
plain = glm_fisher_scoring(x, y, family, link, beta0=start, halving=False)
assert max(abs(u - v) for u, v in zip(plain.path[2], npath[2])) > 1e-6
def test_two_group_closed_forms():
rng = random.Random(5)
g = [0] * 40 + [1] * 60
# Poisson log link: beta0 = log ybar0, beta1 = log(ybar1 / ybar0)
y = []
for gi in g:
m = 2.0 if gi == 0 else 3.5
u, k, pk = rng.random(), 0, math.exp(-m)
cum = pk
while u > cum:
k += 1
pk *= m / k
cum += pk
y.append(float(k))
x = [[1.0, float(gi)] for gi in g]
s0, s1 = sum(y[:40]), sum(y[40:])
fit = glm_fisher_scoring(x, y, "poisson", "log", tol=1e-20)
assert abs(fit.beta[0] - math.log(s0 / 40)) < 1e-10
assert abs(fit.beta[1] - math.log((s1 / 60) / (s0 / 40))) < 1e-10
assert abs(fit.cov[1][1] - (1 / s0 + 1 / s1)) < 1e-10
# Probit: beta0 = Phi^-1(p0), beta1 = Phi^-1(p1) - Phi^-1(p0)
yb = [1.0 if rng.random() < (0.3 if gi == 0 else 0.6) else 0.0 for gi in g]
p0, p1 = sum(yb[:40]) / 40, sum(yb[40:]) / 60
fit = glm_fisher_scoring(x, yb, "binomial", "probit", tol=1e-20)
assert abs(fit.beta[0] - ND.inv_cdf(p0)) < 1e-8
assert abs(fit.beta[1] - (ND.inv_cdf(p1) - ND.inv_cdf(p0))) < 1e-8
def test_cauchy_location_against_grid_search():
rng = random.Random(7)
xs = [2.0 + math.tan(math.pi * (rng.random() - 0.5)) for _ in range(25)]
n = len(xs)
def ll(t):
return -sum(math.log1p((v - t[0]) ** 2) for v in xs)
def score(t):
return [sum(2 * (v - t[0]) / (1 + (v - t[0]) ** 2) for v in xs)]
start = sorted(xs)[n // 2]
res = fisher_scoring(score, lambda t: [[n / 2]], [start], ll, tol=1e-14)
assert res.converged
assert all(b >= a for a, b in zip(res.logliks, res.logliks[1:]))
lo, hi = min(xs), max(xs)
best = max((ll([lo + (hi - lo) * i / 20000]), lo + (hi - lo) * i / 20000) for i in range(20001))
w = 2 * (hi - lo) / 20000
best = max((ll([best[1] - w + 2 * w * i / 20000]), best[1] - w + 2 * w * i / 20000) for i in range(20001))
assert abs(res.theta[0] - best[1]) < 1e-5
assert ll(res.theta) >= best[0] - 1e-12
def test_step_halving_keeps_loglik_from_falling():
x, y = make_data(31, 150, [-0.3, 0.8, -0.5], "binomial", "probit")
fit = glm_fisher_scoring(x, y, "binomial", "probit", beta0=[4.0, -4.0, 4.0], tol=1e-20)
ref = glm_fisher_scoring(x, y, "binomial", "probit", tol=1e-20)
assert fit.converged
assert max(abs(u - v) for u, v in zip(fit.beta, ref.beta)) < 1e-7
# recompute the log-likelihood along the path; it never falls
_, ll_one = FAMILIES["binomial"]
lls = [sum(ll_one(yi, sum(a * c for a, c in zip(xi, b)), "probit") for xi, yi in zip(x, y)) for b in fit.path]
assert all(b >= a for a, b in zip(lls, lls[1:]))
def test_complete_separation_is_flagged():
x = [[1.0, float(t)] for t in (-3, -2, -1, 1, 2, 3)]
y = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]
fit = glm_fisher_scoring(x, y, "binomial", "logit", max_iter=200)
assert fit.separated
assert fit.beta[1] > 5
ok = glm_fisher_scoring(x, [0.0, 1.0, 0.0, 1.0, 0.0, 1.0], "binomial", "logit")
assert ok.converged and not ok.separated
def test_wald_interval_coverage_measured():
# Measured, not proved: coverage of beta1 +- 1.96 se for logistic data, n = 200.
beta = [-0.5, 1.0, -0.7]
z = ND.inv_cdf(0.975)
hits, r = 0, 300
for rep in range(r):
x, y = make_data(1000 + rep, 200, beta, "binomial", "logit")
fit = glm_fisher_scoring(x, y, "binomial", "logit")
se = math.sqrt(fit.cov[1][1])
hits += abs(fit.beta[1] - beta[1]) <= z * se
cover = hits / r
assert abs(cover - 0.95) < 3 * math.sqrt(0.95 * 0.05 / r)
History
R. A. Fisher used the expected information to fit maximum likelihood estimates iteratively. His appendix to C. I. Bliss's 1935 paper on the dosage-mortality curve gives the iterative fit of the probit line with expected weights, and the method spread in bioassay through probit analysis. Nelder and Wedderburn (1972) defined generalized linear models and showed that one fitting algorithm, iterative weighted least squares, is Fisher scoring for all of them. Osborne (1992) analysed the convergence of scoring for likelihoods and quasi-likelihoods and its relation to the Gauss-Newton method.
References
- M. R. Osborne, Fisher's method of scoring, International Statistical Review 60(1), 1992, pages 99 to 117 (convergence of scoring, its relation to Gauss-Newton, and step-length control)
- C. I. Bliss, The calculation of the dosage-mortality curve, Annals of Applied Biology 22(1), 1935, with an appendix by R. A. Fisher, The case of zero survivors, pages 134 to 167; the appendix is on pages 164 to 165 (iterative fit of the probit line with expected weights)
- J. A. Nelder and R. W. M. Wedderburn, Generalized linear models, Journal of the Royal Statistical Society, Series A 135(3), 1972, pages 370 to 384 (the fitting algorithm as iterative weighted least squares, equal to scoring)
- P. McCullagh and J. A. Nelder, Generalized Linear Models, second edition, Chapman and Hall, 1989, Chapter 2 (the iteratively reweighted least squares algorithm for fitting a GLM, and its use of expected information)
- A. W. van der Vaart, Asymptotic Statistics, Cambridge University Press, 1998, Chapter 5, Section 5.7 (one-step estimators)
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 Y142G8 Edit this page History Report an error Markdown