Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 In(θ)I_n(\theta). 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 ℓ(θ)\ell(\theta) of a sample, θ∈Rk\theta \in \mathbb R^k, given through its score U(θ)=∇ℓ(θ)U(\theta) = \nabla\ell(\theta) and the expected information of the sample I(θ)=Var⁡θU(θ)I(\theta) = \operatorname{Var}_\theta U(\theta), which is nn times the information of one observation for iid data. I(θ)I(\theta) must be positive definite at every point the method visits. Optionally ℓ\ell itself is given, for step control. The input also has a start θ0\theta_0, a tolerance ε≥0\varepsilon \ge 0 and a limit tmax⁡t_{\max} on the number of iterations.

The output is a point θ^\hat\theta with U(θ^)TI(θ^)−1U(θ^)≤εU(\hat\theta)^{\mathsf T}I(\hat\theta)^{-1}U(\hat\theta) \le \varepsilon, which approximates a root of the likelihood equation U(θ)=0U(\theta) = 0, and the matrix I(θ^)−1I(\hat\theta)^{-1}, the usual estimate of the covariance of θ^\hat\theta. If the test is not met in tmax⁡t_{\max} iterations, or no step along the scoring direction raises ℓ\ell, the output says that the method did not converge.

For a GLM with design rows xi∈Rpx_i \in \mathbb R^p, mean μi=h(ηi)\mu_i = h(\eta_i), ηi=xiTβ\eta_i = x_i^{\mathsf T}\beta, and variance function V(μ)V(\mu),

U(β)=∑i=1nxi (yi−μi) h′(ηi)V(μi),I(β)=∑i=1nxixiT h′(ηi)2V(μi).U(\beta) = \sum_{i=1}^n x_i\,\frac{(y_i - \mu_i)\,h'(\eta_i)}{V(\mu_i)}, \qquad I(\beta) = \sum_{i=1}^n x_i x_i^{\mathsf T}\,\frac{h'(\eta_i)^2}{V(\mu_i)}.

The algorithm

  1. FISHER-SCORING(U, I, ℓ, θ_0, ε, t_max)
  2. 1θ ← θ_0
  3. 2for t ← 0 to t_max - 1 do
  4. 3g ← U(θ) ▷ score of the sample at θ
  5. 4H ← I(θ) ▷ expected information of the sample
  6. 5δ ← solution of H δ = g ▷ the scoring direction
  7. 6if gᵀδ ≤ ε then return θ, H⁻¹, converged
  8. 7s ← 1
  9. 8while ℓ(θ + sδ) < ℓ(θ) and s > s_min do s ← s / 2
  10. 9if ℓ(θ + sδ) < ℓ(θ) then return θ, H⁻¹, stalled
  11. 10θ ← θ + sδ
  12. 11return θ, I(θ)⁻¹, not converged

Line L5 solves a k×kk \times k positive definite system; a Cholesky factorization is the usual choice. The quantity gTδ=UTI−1Ug^{\mathsf T}\delta = U^{\mathsf T}I^{-1}U 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 ℓ\ell they are skipped and every step has s=1s = 1, which is plain scoring.

For a GLM, put wi=h′(ηi)2/V(μi)w_i = h'(\eta_i)^2/V(\mu_i) and the working response zi=ηi+(yi−μi)/h′(ηi)z_i = \eta_i + (y_i - \mu_i)/h'(\eta_i). Then H=XTWXH = X^{\mathsf T}WX and Hβ+g=XTWzH\beta + g = X^{\mathsf T}Wz, so the full step β+δ\beta + \delta is the weighted least squares fit of zz on XX with weights wiw_i. That is the IRLS form of the same step.

Example

Logistic and probit regression. The data are the doses 1,…,61, \ldots, 6, each given to 10 subjects, with 1,2,4,6,81, 2, 4, 6, 8 and 99 responses; the model has an intercept and a slope in the dose, and the start is β=(0,0)\beta = (0, 0). 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.

tt logit β0\beta_0 logit β1\beta_1 probit β0\beta_0 probit β1\beta_1
0 0 0 0 0
1 −2.4000000000-2.4000000000 0.68571428570.6857142857 −1.5039769648-1.5039769648 0.42970770420.4297077042
2 −3.0276954635-3.0276954635 0.86505584670.8650558467 −1.8156375678-1.8156375678 0.51875359080.5187535908
3 −3.1189201800-3.1189201800 0.89112005140.8911200514 −1.8488825242-1.8488825242 0.52825214980.5282521498
4 −3.1206983729-3.1206983729 0.89162810660.8916281066 −1.8491436546-1.8491436546 0.52832675850.5283267585
5 −3.1206990360-3.1206990360 0.89162829600.8916282960 −1.8491426875-1.8491426875 0.52832648220.5283264822

The logit errors (the largest coordinate distance to the final estimate) are 0.720.72, 0.0930.093, 1.8×10−31.8 \times 10^{-3}, 6.6×10−76.6 \times 10^{-7} and below 10−1510^{-15}: quadratic convergence, as for Newton's method. The probit errors are 0.350.35, 0.0340.034, 2.6×10−42.6 \times 10^{-4}, 9.6×10−79.6 \times 10^{-7} and 3.7×10−93.7 \times 10^{-9}: 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 η=0\eta = 0, 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 0.8530.853 and 0.2260.226 (logit) and 0.4660.466 and 0.1220.122 (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 n/2n/2, a constant, while the observed information ∑2(1−ri2)/(1+ri2)2\sum 2(1 - r_i^2)/(1 + r_i^2)^2 with ri=xi−θr_i = x_i - \theta 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 θ^=1.59503\hat\theta = 1.59503. From the smallest observation, Newton's method stops at the stationary point 9.51569.5156, and from the largest at 13.43813.438. Scoring with halving reaches 1.595031.59503 from every start tried, which agrees with a dense grid search over the range of the data.

Correctness

The returned point satisfies UTI−1U≤εU^{\mathsf T}I^{-1}U \le \varepsilon, and with ε=0\varepsilon = 0 it is a root of the likelihood equation, because I−1I^{-1} is positive definite. The direction δ=I−1U\delta = I^{-1}U has positive inner product UTI−1UU^{\mathsf T}I^{-1}U with the gradient, so it points uphill, and step halving finds a step that does not lower ℓ\ell. For a canonical exponential family the Hessian of ℓ\ell 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 Ik−I−1JI_k - I^{-1}J, where JJ 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. ℓ\ell is the log-likelihood of the sample, U=∇ℓU = \nabla\ell its score and I(θ)I(\theta) the expected information of the sample, which is symmetric and positive definite at every θ\theta where it is used. Line numbers refer to the main pseudocode. Write T(θ)=θ+I(θ)−1U(θ)T(\theta) = \theta + I(\theta)^{-1}U(\theta) for one full scoring step.

Lemma 1 (fixed points are roots of the score). T(θ)=θT(\theta) = \theta if and only if U(θ)=0U(\theta) = 0.

Proof. T(θ)−θ=I(θ)−1U(θ)T(\theta) - \theta = I(\theta)^{-1}U(\theta), and I(θ)−1I(\theta)^{-1} is nonsingular. □\square

Lemma 2 (the stopping test). Let g=U(θ)g = U(\theta) and δ=I(θ)−1g\delta = I(\theta)^{-1}g as in lines L3 to L5. Then gTδ=gTI(θ)−1g≥0g^{\mathsf T}\delta = g^{\mathsf T}I(\theta)^{-1}g \ge 0, with equality if and only if g=0g = 0. If line L6 returns, then gTI(θ)−1g≤εg^{\mathsf T}I(\theta)^{-1}g \le \varepsilon; for ε=0\varepsilon = 0 this means U(θ)=0U(\theta) = 0.

Proof. I(θ)−1I(\theta)^{-1} is positive definite because I(θ)I(\theta) is. So the quadratic form is nonnegative and is zero only for g=0g = 0. The return in line L6 happens only when the test holds. □\square

The quantity gTI−1gg^{\mathsf T}I^{-1}g is the score statistic for the hypothesis that the current θ\theta 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 ℓ\ell be differentiable at θ\theta and U(θ)≠0U(\theta) \ne 0. Then there is s0>0s_0 > 0 with ℓ(θ+sδ)>ℓ(θ)\ell(\theta + s\delta) > \ell(\theta) for all 0<s≤s00 < s \le s_0.

Proof. The derivative of s↦ℓ(θ+sδ)s \mapsto \ell(\theta + s\delta) at s=0s = 0 is U(θ)Tδ=gTI(θ)−1gU(\theta)^{\mathsf T}\delta = g^{\mathsf T}I(\theta)^{-1}g, which is positive by Lemma 2. A function with positive derivative at 0 is larger than its value at 0 on some interval (0,s0](0, s_0]. □\square

Lemma 4 (the likelihood never falls). With ℓ\ell given, every step taken in line L10 satisfies ℓ(θnew)≥ℓ(θold)\ell(\theta_{\text{new}}) \ge \ell(\theta_{\text{old}}). The loop of line L8 ends after at most ⌈log⁡2(1/smin⁡)⌉+1\lceil\log_2(1/s_{\min})\rceil + 1 halvings.

Proof. Line L9 returns without a step when the halved step still lowers ℓ\ell. So a step that reaches line L10 has ℓ(θ+sδ)≥ℓ(θ)\ell(\theta + s\delta) \ge \ell(\theta). The loop of line L8 halves ss, starting from 1, and stops when s≤smin⁡s \le s_{\min} at the latest. By Lemma 3, if smin⁡<s0/2s_{\min} < s_0/2, the first power of 2 that is at most s0s_0 is larger than smin⁡s_{\min} and gives an increase, so the loop stops there and line L9 does not return. □\square

Lemma 5 (canonical links: scoring is Newton's method). Let Y1,…,YnY_1, \ldots, Y_n be independent with densities exp⁡(yηi−b(ηi)+c(y))\exp(y\eta_i - b(\eta_i) + c(y)), a canonical exponential family, and ηi=xiTβ\eta_i = x_i^{\mathsf T}\beta (a generalized linear model with canonical link). Then the observed information J(β)=−∇2ℓ(β)J(\beta) = -\nabla^2\ell(\beta) equals the expected information I(β)I(\beta) for every β\beta and every data set, so each scoring step equals the Newton step from the same point.

Proof. ℓ(β)=∑i(YixiTβ−b(xiTβ)+c(Yi))\ell(\beta) = \sum_i (Y_i x_i^{\mathsf T}\beta - b(x_i^{\mathsf T}\beta) + c(Y_i)). Its gradient is ∑ixi(Yi−b′(ηi))\sum_i x_i(Y_i - b'(\eta_i)) and its Hessian is −∑ixixiTb′′(ηi)-\sum_i x_i x_i^{\mathsf T} b''(\eta_i), which does not contain the data YiY_i. So it equals its own expectation: J(β)=∑ixixiTb′′(ηi)=EβJ(β)=I(β)J(\beta) = \sum_i x_i x_i^{\mathsf T}b''(\eta_i) = \mathrm E_\beta J(\beta) = I(\beta). Line L5 then solves the same system as Newton's method. □\square

Logistic regression (b(η)=log⁡(1+eη)b(\eta) = \log(1 + e^\eta)) and Poisson regression with log link (b(η)=eηb(\eta) = e^\eta) are of this form. For them the local quadratic convergence of Newton's method near a root with nonsingular JJ applies to scoring without change.

Lemma 6 (local rate for other models). Let UU and II be continuously differentiable near a root θ^\hat\theta of UU, and J(θ^)=−∇U(θ^)J(\hat\theta) = -\nabla U(\hat\theta). The Jacobian of TT at θ^\hat\theta is

∇T(θ^)=Ik−I(θ^)−1J(θ^).\nabla T(\hat\theta) = I_k - I(\hat\theta)^{-1}J(\hat\theta).

Proof. Differentiate T(θ)=θ+I(θ)−1U(θ)T(\theta) = \theta + I(\theta)^{-1}U(\theta) by the product rule. The term that contains the derivative of I(θ)−1I(\theta)^{-1} is multiplied by U(θ^)=0U(\hat\theta) = 0, and the other term is I(θ^)−1∇U(θ^)=−I(θ^)−1J(θ^)I(\hat\theta)^{-1}\nabla U(\hat\theta) = -I(\hat\theta)^{-1}J(\hat\theta). □\square

By Ostrowski's theorem on fixed-point iterations, if the spectral radius rr of Ik−I(θ^)−1J(θ^)I_k - I(\hat\theta)^{-1}J(\hat\theta) is less than 1, then full scoring steps started close enough to θ^\hat\theta converge to θ^\hat\theta, and the error falls asymptotically by about the factor rr per step. Under a correct model, J(θ^)/nJ(\hat\theta)/n and I(θ^)/nI(\hat\theta)/n both converge to the information of one observation, so r→0r \to 0 as nn grows; this is a statement about large samples, and for a given data set rr can be near or above 1.

Theorem. (a) If FISHER-SCORING returns in line L6, the returned θ\theta satisfies U(θ)TI(θ)−1U(θ)≤εU(\theta)^{\mathsf T}I(\theta)^{-1}U(\theta) \le \varepsilon, and with ε=0\varepsilon = 0 it is a root of the likelihood equation. (b) With ℓ\ell given, the sequence ℓ(θ0),ℓ(θ1),…\ell(\theta_0), \ell(\theta_1), \ldots 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. ■\blacksquare

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 β\beta.

Complexity

For a GLM, one iteration computes the nn linear predictors in O(np)O(np), the score in O(np)O(np), the information XTWXX^{\mathsf T}WX in O(np2)O(np^2), and solves the p×pp \times p system in O(p3)O(p^3). Each halving costs one more log-likelihood, O(np)O(np). Over tt iterations the time is O(t(np2+p3))O(t(np^2 + p^3)) plus the halvings, and the extra space is O(p2)O(p^2) for HH 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 nn is large.

Scoring needs no second derivatives of the data terms, only h′h' and VV, which is part of its appeal. Compared with Newton's method it saves little per step for GLMs but gives a matrix HH that is positive definite whenever XX 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 θ=Aϕ\theta = A\phi with AA invertible, the iterates in ϕ\phi map to the iterates in θ\theta, and the stopping test of line L6 is unchanged.
  • Covariance for free. I(θ^)−1I(\hat\theta)^{-1} 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 nn.
  • One-step efficiency. One full scoring step from a n\sqrt n-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 β\beta, and one step from any start gives the least squares estimate exactly.

Variants and improvements

  • Newton-Raphson. Use the observed information JJ. It is faster near the root for non-canonical models, but JJ can be indefinite away from it.
  • Mixed strategies. Start with scoring steps for safety and switch to Newton steps near the root, or use JJ when it is positive definite and II 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 U=∑DiTVi−1(yi−μi)U = \sum D_i^{\mathsf T}V_i^{-1}(y_i - \mu_i) and I=∑DiTVi−1DiI = \sum D_i^{\mathsf T}V_i^{-1}D_i 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 p×pp \times p 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 00 and 11, the likelihood increases toward a supremum that is not attained, and the coefficients grow without bound. Scoring may report convergence at a huge β\beta, 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 −∞-\infty, 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, I(β^)−1I(\hat\beta)^{-1} and J(β^)−1J(\hat\beta)^{-1} give different standard errors. Both are valid asymptotically; say which one is reported.
  • Loose tolerance. A test on the change in ℓ\ell alone can stop early on a flat ridge. The test UTI−1U≤εU^{\mathsf T}I^{-1}U \le \varepsilon uses the scale of the information; with linear convergence, a tolerance of 10−1010^{-10} can still leave errors near 10−610^{-6} in β\beta.
  • Singular information. If XX does not have full column rank, or a fitted weight is zero, HH 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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