Simple Algorithm
Machine Learning · Convergence · 28 min

Generalized Linear Models

Exponential families and link functions: one idea behind many regressions.

Linear, logistic, Poisson and gamma regression look like four different models. Nelder and Wedderburn showed in 1972 that they are one: a distribution from an exponential dispersion family, a linear predictor, and a link. From that structure come the mean and variance of every family, a concave likelihood under the canonical link, one fitting algorithm for all of them, iteratively reweighted least squares, and one measure of fit, the deviance.

What you’ll learn

  • Write an exponential dispersion family in canonical form, derive Ey=b′(θ)\E y=b'(\theta) and Var⁡y=ϕ b′′(θ)\Var y=\phi\,b''(\theta), and read off the variance functions of the common families.
  • Derive the GLM score and Fisher information, and show that under the canonical link the log-likelihood is concave and the observed and expected information coincide.
  • Derive iteratively reweighted least squares as Fisher scoring, with its working response and weights, and recognize when it fails.
  • Define the deviance as twice a sum of Kullback–Leibler divergences, use it for nested comparisons, and estimate the dispersion.
  • Handle overdispersion with quasi-likelihood and the negative binomial, and describe how classical GLM theory fails when p/np/n is not small.

Exponential dispersion families

DerivationMean and variance from the cumulant function
  1. E[y−b′(θ)ϕ]=0⟹μ=Ey=b′(θ)\E\Big[\frac{y-b'(\theta)}{\phi}\Big]=0\quad\Longrightarrow\quad\mu=\E y=b'(\theta)

    ∫f(y;θ,ϕ) dy=1\int f(y;\theta,\phi)\,dy=1 for every θ\theta. Differentiate under the integral sign; the derivative of the exponent is (y−b′(θ))/ϕ(y-b'(\theta))/\phi, and its expectation must vanish:

  2. E[−b′′(θ)ϕ+(y−b′(θ))2ϕ2]=0⟹Var⁡y=ϕ b′′(θ)\E\Big[-\frac{b''(\theta)}\phi+\frac{(y-b'(\theta))^2}{\phi^2}\Big]=0\quad\Longrightarrow\quad\Var y=\phi\,b''(\theta)

    Differentiate once more. The second derivative of the exponent is −b′′(θ)/ϕ-b''(\theta)/\phi, and the expectation of (second derivative) + (first derivative)2^2 vanishes too:

  3. Var⁡y=ϕ V(μ),V(μ)=b′′((b′)−1(μ))\Var y=\phi\,V(\mu),\qquad V(\mu)=b''\big((b')^{-1}(\mu)\big)

    For a nondegenerate family b′′>0b''>0, so b′b' is strictly increasing and θ↔μ\theta\leftrightarrow\mu is one-to-one. The variance is therefore a function of the mean, the variance function VV:

Familyθ(μ)\theta(\mu)b(θ)b(\theta)ϕ\phiV(μ)V(\mu)
Normal N(μ,σ2)\mathcal N(\mu,\sigma^2)μ\muθ2/2\theta^2/2σ2\sigma^211
Poissonlog⁡μ\log\mueθe^\theta11μ\mu
Bernoullilog⁡μ1−μ\log\frac\mu{1-\mu}log⁡(1+eθ)\log(1+e^\theta)11μ(1−μ)\mu(1-\mu)
Gamma (mean μ\mu, shape ν\nu)−1/μ-1/\mu−log⁡(−θ)-\log(-\theta)1/ν1/\nuμ2\mu^2
Inverse Gaussian (mean μ\mu, shape λ\lambda)−1/(2μ2)-1/(2\mu^2)−−2θ-\sqrt{-2\theta}1/λ1/\lambdaμ3\mu^3
The variance functions say how noise scales with the mean: constant for the normal, proportional for the Poisson, quadratic (a constant coefficient of variation) for the gamma. Power variance functions V(μ)=μpV(\mu)=\mu^p with 1<p<21<p<2 give the Tweedie distributions, compound Poisson–gamma laws with an exact mass at zero, used for insurance claims.
Think first Claim sizes follow a gamma distribution with mean μ=2,000\mu=2{,}000 and shape ν=4\nu=4. What is their standard deviation, and what happens to it for claims with mean 4,0004{,}000?

Var⁡y=ϕV(μ)=μ2/ν=2,0002/4\Var y=\phi V(\mu)=\mu^2/\nu=2{,}000^2/4, so the standard deviation is 1,0001{,}000. Doubling the mean doubles it to 2,0002{,}000: the coefficient of variation stays at 1/ν=0.51/\sqrt\nu=0.5. That constant relative spread is why the gamma (often with a log link) suits costs and durations.

Likelihood, score and the canonical link

A GLM has independent responses yiy_i from one such family with natural parameters θi\theta_i and common dispersion ϕ\phi, means μi=b′(θi)\mu_i=b'(\theta_i), linear predictors ηi=xi⊤w\eta_i=\mathbf x_i^\top\mathbf w, and a monotone link with g(μi)=ηig(\mu_i)=\eta_i. The link is canonical when g=(b′)−1g=(b')^{-1}, that is, when θi=ηi\theta_i=\eta_i: the identity for the normal, the log for the Poisson, the logit for the Bernoulli.

DerivationScore and Fisher information
  1. ∂ℓ∂w=∑i=1nyi−μiϕ⋅1V(μi)⋅1g′(μi)⋅xi\frac{\partial\ell}{\partial\mathbf w}=\sum_{i=1}^n\frac{y_i-\mu_i}{\phi}\cdot\frac{1}{V(\mu_i)}\cdot\frac{1}{g'(\mu_i)}\cdot\mathbf x_i

    The log-likelihood is ℓ(w)=∑i[yiθi−b(θi)]/ϕ\ell(\mathbf w)=\sum_i[y_i\theta_i-b(\theta_i)]/\phi plus terms free of w\mathbf w. Follow the chain w→ηi→μi→θi\mathbf w\to\eta_i\to\mu_i\to\theta_i, using dμ/dθ=b′′(θ)=V(μ)d\mu/d\theta=b''(\theta)=V(\mu) and dη/dμ=g′(μ)d\eta/d\mu=g'(\mu):

  2. I(w)=∑i=1nxixi⊤ϕ V(μi) g′(μi)2=1ϕX⊤WX,Wii=1V(μi) g′(μi)2\mathcal I(\mathbf w)=\sum_{i=1}^n\frac{\mathbf x_i\mathbf x_i^\top}{\phi\,V(\mu_i)\,g'(\mu_i)^2}=\frac1\phi X^\top WX,\qquad W_{ii}=\frac1{V(\mu_i)\,g'(\mu_i)^2}

    The Fisher information is the covariance of the score; with Var⁡yi=ϕV(μi)\Var y_i=\phi V(\mu_i) and independent observations,

Non-canonical links are common and often sensible: the probit for binary data, the log for the gamma (the canonical −1/μ-1/\mu would force a sign constraint on the linear predictor), the identity for counts when effects are additive. They keep the score equations above but lose the simplifications: the observed and expected information differ, and concavity is no longer automatic.

Check your understanding

Which of these holds for every GLM with a canonical link, but not for GLMs in general?

  1. The maximum-likelihood estimate exists for every data set
  2. The Hessian of the log-likelihood does not depend on the observed responses
  3. The variance of yy does not depend on its mean
  4. The mean μ\mu is a linear function of x\mathbf x
Show the answer

B. The Hessian of the log-likelihood does not depend on the observed responses

With θi=ηi\theta_i=\eta_i, the term yiθiy_i\theta_i is linear in w\mathbf w, so the second derivatives come from b(θi)b(\theta_i) alone: −∑ib′′(ηi)xixi⊤/ϕ-\sum_ib''(\eta_i)\mathbf x_i\mathbf x_i^\top/\phi. That is why Newton's method and Fisher scoring coincide for canonical links.

Fitting: Fisher scoring is IRLS

DerivationFrom Fisher scoring to weighted least squares
  1. wnew=w+I(w)−1∇ℓ(w)\mathbf w^{\text{new}}=\mathbf w+\mathcal I(\mathbf w)^{-1}\nabla\ell(\mathbf w)

    Fisher scoring is Newton's method with the Hessian replaced by minus the expected information:

  2. X⊤WX wnew=X⊤WX w+X⊤WG(y−μ)=X⊤WzX^\top WX\,\mathbf w^{\text{new}}=X^\top WX\,\mathbf w+X^\top WG(\mathbf y-\boldsymbol\mu)=X^\top W\mathbf z

    Write the score with the same weights: yi−μiV(μi)g′(μi)=Wii g′(μi)(yi−μi)\frac{y_i-\mu_i}{V(\mu_i)g'(\mu_i)}=W_{ii}\,g'(\mu_i)(y_i-\mu_i), so ∇ℓ=1ϕX⊤WG(y−μ)\nabla\ell=\frac1\phi X^\top WG(\mathbf y-\boldsymbol\mu) with G=diag⁡(g′(μi))G=\diag(g'(\mu_i)). Multiply through by I=1ϕX⊤WX\mathcal I=\frac1\phi X^\top WX:

  3. wnew=(X⊤WX)−1X⊤Wz,zi=ηi+(yi−μi) g′(μi),Wii=1V(μi)g′(μi)2\mathbf w^{\text{new}}=(X^\top WX)^{-1}X^\top W\mathbf z,\qquad z_i=\eta_i+(y_i-\mu_i)\,g'(\mu_i),\qquad W_{ii}=\frac1{V(\mu_i)g'(\mu_i)^2}

    Each step is therefore a weighted least-squares regression of the working response z\mathbf z on XX, a first-order linearization of g(yi)g(y_i) around the current mean. The dispersion ϕ\phi cancels, so it never affects w^\hat{\mathbf w}:

ModelWorking response ziz_iWeight WiiW_{ii}
Normal, identity linkyiy_i11: one step of ordinary least squares
Logistic (Bernoulli, logit)ηi+yi−μiμi(1−μi)\eta_i+\dfrac{y_i-\mu_i}{\mu_i(1-\mu_i)}μi(1−μi)\mu_i(1-\mu_i)
Poisson, log linkηi+yi−μiμi\eta_i+\dfrac{y_i-\mu_i}{\mu_i}μi\mu_i
Gamma, log linkηi+yi−μiμi\eta_i+\dfrac{y_i-\mu_i}{\mu_i}11
For the gamma with a log link the weights are constant, because V(μ)g′(μ)2=μ2⋅μ−2=1V(\mu)g'(\mu)^2=\mu^2\cdot\mu^{-2}=1. For logistic regression the weights μi(1−μi)\mu_i(1-\mu_i) vanish for confidently classified points, which is how the algorithm "stops listening" to them, and why it breaks down under separation.
python
import numpy as np

def irls_poisson(X, y, offset=0.0, tol=1e-10, max_iter=50):
    """Poisson GLM with log link by Fisher scoring (= Newton for this canonical link)."""
    eta = np.log(y + 0.5)                  # start from the data, nudged away from log 0
    w = np.zeros(X.shape[1])
    for _ in range(max_iter):
        mu = np.exp(eta)
        z = eta - offset + (y - mu) / mu   # working response: g'(mu) = 1/mu
        W = mu                             # weights 1 / (V(mu) g'(mu)^2) = mu
        w_new = np.linalg.solve(X.T @ (W[:, None] * X), X.T @ (W * z))
        eta = X @ w_new + offset
        if np.max(np.abs(w_new - w)) < tol:
            break
        w = w_new
    return w_new, np.sqrt(np.diag(np.linalg.inv(X.T @ (W[:, None] * X))))

The second output holds the usual standard errors, from the inverse Fisher information at the final weights (here ϕ=1\phi=1). A production implementation adds step halving when the deviance increases and solves each weighted least-squares problem by QR.

Near the optimum, Fisher scoring converges quadratically for canonical links, where it is Newton's method, and typically needs only a handful of iterations. It can fail when the maximum-likelihood estimate does not exist: under complete or quasi-complete separation in logistic regression, the likelihood keeps increasing as the coefficients go to infinity (Albert & Anderson, 1984), and the weights of the separated points collapse toward zero. Penalization (ridge, or Firth's bias-reducing penalty) restores a finite answer.

Under standard regularity conditions with pp fixed and n→∞n\to\infty, the estimate is consistent and asymptotically normal, w^≈N(w, ϕ (X⊤WX)−1)\hat{\mathbf w}\approx\mathcal N\big(\mathbf w,\ \phi\,(X^\top WX)^{-1}\big), which gives the standard errors and Wald tests printed by GLM software.

The deviance

The saturated model gives every observation its own parameter and fits it perfectly, μ~i=yi\tilde\mu_i=y_i (natural parameter θ~i\tilde\theta_i). The deviance measures how far the fitted model falls short of it:

D=2ϕ[ℓ(saturated)−ℓ(fitted)]=2∑i=1n[yi(θ~i−θ^i)−b(θ~i)+b(θ^i)],D=2\phi\big[\ell(\text{saturated})-\ell(\text{fitted})\big]=2\sum_{i=1}^n\Big[y_i(\tilde\theta_i-\hat\theta_i)-b(\tilde\theta_i)+b(\hat\theta_i)\Big],

which does not depend on ϕ\phi; D/ϕD/\phi is the scaled deviance. Each term is a Bregman divergence of bb, and since the saturated distribution has mean yi=b′(θ~i)y_i=b'(\tilde\theta_i), it equals 2ϕ2\phi times a Kullback–Leibler divergence:

D=2ϕ∑i=1nDKL(f(⋅;θ~i) ∥ f(⋅;θ^i)).D=2\phi\sum_{i=1}^n\KL\big(f(\cdot;\tilde\theta_i)\,\big\|\,f(\cdot;\hat\theta_i)\big).

Fitting a GLM by maximum likelihood is minimizing a sum of KL divergences from the data's own distributions, a direct generalization of least squares, whose deviance is the residual sum of squares.

FamilyDeviance DD
Normal∑i(yi−μ^i)2\sum_i(y_i-\hat\mu_i)^2
Poisson2∑i[yilog⁡(yi/μ^i)−(yi−μ^i)]2\sum_i\big[y_i\log(y_i/\hat\mu_i)-(y_i-\hat\mu_i)\big], with 0log⁡0=00\log0=0
Bernoulli−2∑i[yilog⁡μ^i+(1−yi)log⁡(1−μ^i)]-2\sum_i\big[y_i\log\hat\mu_i+(1-y_i)\log(1-\hat\mu_i)\big]: twice the summed log loss
Gamma2∑i[−log⁡(yi/μ^i)+(yi−μ^i)/μ^i]2\sum_i\big[-\log(y_i/\hat\mu_i)+(y_i-\hat\mu_i)/\hat\mu_i\big]

Comparing nested models. If model M0M_0 with p0p_0 coefficients is nested in M1M_1 with p1p_1, the likelihood-ratio statistic is (D0−D1)/ϕ(D_0-D_1)/\phi, approximately χp1−p02\chi^2_{p_1-p_0} under M0M_0 for large nn. When ϕ\phi must be estimated (normal, gamma, quasi-likelihood), use the FF-like ratio (D0−D1)/(p1−p0)ϕ^\frac{(D_0-D_1)/(p_1-p_0)}{\hat\phi}.

Goodness of fit, carefully. D/ϕ≈χn−p2D/\phi\approx\chi^2_{n-p} only under small-dispersion asymptotics, such as Poisson counts that are all large. For 0/1 data it fails completely: with the canonical link, X⊤y=X⊤μ^X^\top\mathbf y=X^\top\hat{\boldsymbol\mu} gives y⊤η^=μ^⊤η^\mathbf y^\top\hat{\boldsymbol\eta}=\hat{\boldsymbol\mu}^\top\hat{\boldsymbol\eta}, so D=−2∑i[μ^iη^i+log⁡(1−μ^i)]D=-2\sum_i\big[\hat\mu_i\hat\eta_i+\log(1-\hat\mu_i)\big] depends on the data only through the fitted probabilities and cannot detect lack of fit.

Dispersion. It is usually estimated from Pearson's statistic, ϕ^=X2/(n−p)\hat\phi=X^2/(n-p) with X2=∑i(yi−μ^i)2/V(μ^i)X^2=\sum_i(y_i-\hat\mu_i)^2/V(\hat\mu_i). For Poisson and binomial models ϕ=1\phi=1 in theory, so ϕ^\hat\phi well above 1 signals overdispersion.

Predict before you look

A Poisson GLM with p=4p=4 coefficients is fitted to n=120n=120 counts, and Pearson's statistic is X2=290X^2=290. By what factor should the Poisson standard errors be inflated?

Show the answer

1.58

ϕ^=290/(120−4)=2.5\hat\phi=290/(120-4)=2.5, and standard errors scale with ϕ\sqrt\phi: 2.5≈1.58\sqrt{2.5}\approx1.58. Uncorrected, the Poisson analysis would claim intervals about 37% too narrow and declare too many effects significant.

Overdispersion and beyond

The Poisson forces Var⁡y=μ\Var y=\mu. Real counts are often more variable, because of unmeasured differences between units or clustering of events. Two standard repairs:

Quasi-likelihood (Wedderburn, 1974) specifies only the first two moments, Ey=μ\E y=\mu and Var⁡y=ϕV(μ)\Var y=\phi V(\mu), and solves the same estimating equations as the GLM score. The quasi-Poisson model therefore has exactly the Poisson coefficients, with standard errors multiplied by ϕ^\sqrt{\hat\phi} and FF-tests in place of χ2\chi^2-tests.

The negative binomial models the extra variation explicitly as a Poisson–gamma mixture: each unit has its own rate λ\lambda, drawn from a gamma distribution with mean μ\mu and shape kk, and y∣λ∼Poisson(λ)y\mid\lambda\sim\mathrm{Poisson}(\lambda).

DerivationThe negative binomial variance
  1. Var⁡y=E[Var⁡(y∣λ)]+Var⁡(E[y∣λ])=Eλ+Var⁡λ\Var y=\E\big[\Var(y\mid\lambda)\big]+\Var\big(\E[y\mid\lambda]\big)=\E\lambda+\Var\lambda

    Condition on the unit's rate and use the law of total variance:

  2. Ey=μ,Var⁡y=μ+μ2k\E y=\mu,\qquad\Var y=\mu+\frac{\mu^2}{k}

    A gamma with mean μ\mu and shape kk has variance μ2/k\mu^2/k, so

  3. k→∞:Var⁡y→μk\to\infty:\quad\Var y\to\mu

    As k→∞k\to\infty the rates stop varying and the Poisson returns. For fixed kk the negative binomial is a one-parameter exponential family in μ\mu, hence a GLM (usually with a log link); kk is estimated by maximum likelihood, alternating with IRLS.

The two repairs weight observations differently. Quasi-Poisson's variance ϕμ\phi\mu grows linearly with the mean; the negative binomial's μ+μ2/k\mu+\mu^2/k grows quadratically, so it gives large counts less weight. Plotting squared residuals against fitted means shows which pattern the data follow. When the excess is concentrated at zero, zero-inflated or hurdle models add a separate process that produces extra zeros.

Key takeaways

  • An exponential dispersion family exp⁡{(yθ−b(θ))/ϕ+c}\exp\{(y\theta-b(\theta))/\phi+c\} has mean b′(θ)b'(\theta) and variance ϕ b′′(θ)=ϕV(μ)\phi\,b''(\theta)=\phi V(\mu); the variance function (11, μ\mu, μ(1−μ)\mu(1-\mu), μ2\mu^2) is what distinguishes the families.
  • The GLM score is ∑iyi−μiϕV(μi)g′(μi)xi\sum_i\frac{y_i-\mu_i}{\phi V(\mu_i)g'(\mu_i)}\mathbf x_i and the information X⊤WX/ϕX^\top WX/\phi; the canonical link makes the log-likelihood concave with a Hessian free of y\mathbf y, and turns the likelihood equations into X⊤μ^=X⊤yX^\top\hat{\boldsymbol\mu}=X^\top\mathbf y.
  • Fisher scoring is IRLS: regress the working response zi=ηi+(yi−μi)g′(μi)z_i=\eta_i+(y_i-\mu_i)g'(\mu_i) on XX with weights 1/(Vg′2)1/(V g'^2); it fails when the MLE does not exist, as under separation.
  • The deviance is 2ϕ2\phi times a sum of KL divergences from the saturated fit; differences of deviances test nested models, but for 0/1 data the deviance cannot test goodness of fit.
  • Overdispersion inflates Poisson standard errors by ϕ^\sqrt{\hat\phi} (quasi-Poisson) or is modeled by the negative binomial, Var⁡y=μ+μ2/k\Var y=\mu+\mu^2/k; when p/np/n is not small, classical GLM inference fails and needs high-dimensional corrections.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In IRLS for a gamma GLM with a log link, what are the weights Wii=1/(V(μi)g′(μi)2)W_{ii}=1/\big(V(\mu_i)g'(\mu_i)^2\big)?

  1. μi\mu_i
  2. μi2\mu_i^2
  3. All equal to 1
  4. 1/μi1/\mu_i
Show the answer

C. All equal to 1

The gamma variance function is V(μ)=μ2V(\mu)=\mu^2 and the log link has g′(μ)=1/μg'(\mu)=1/\mu, so Vg′2=μ2/μ2=1V g'^2=\mu^2/\mu^2=1. Each IRLS step is an unweighted least-squares fit of the working response ηi+(yi−μi)/μi\eta_i+(y_i-\mu_i)/\mu_i.

Question 2

For a GLM with canonical link and an intercept, the likelihood equations X⊤μ^=X⊤yX^\top\hat{\boldsymbol\mu}=X^\top\mathbf y imply what about the fitted means?

  1. Each fitted mean equals its observation
  2. The fitted means sum to the sum of the observations
  3. The fitted means are all equal
  4. Nothing in general; only the coefficients are constrained
Show the answer

B. The fitted means sum to the sum of the observations

The intercept's column is all ones, so one of the equations is ∑iμ^i=∑iyi\sum_i\hat\mu_i=\sum_iy_i. Each other column gives a matching weighted sum: the model reproduces the sufficient statistic X⊤yX^\top\mathbf y exactly.

Question 3

Why is the residual deviance of a logistic regression on 0/1 data not a valid χn−p2\chi^2_{n-p} goodness-of-fit test?

  1. Because the deviance can be negative for binary data
  2. Because logistic regression has no saturated model
  3. Because the dispersion ϕ\phi is unknown
  4. Because for 0/1 data the deviance is a function of the fitted probabilities alone, so it carries no information about lack of fit
Show the answer

D. Because for 0/1 data the deviance is a function of the fitted probabilities alone, so it carries no information about lack of fit

Under the canonical link the likelihood equations give y⊤η^=μ^⊤η^\mathbf y^\top\hat{\boldsymbol\eta}=\hat{\boldsymbol\mu}^\top\hat{\boldsymbol\eta}, so D=−2∑i[μ^iη^i+log⁡(1−μ^i)]D=-2\sum_i[\hat\mu_i\hat\eta_i+\log(1-\hat\mu_i)]. Two data sets with the same fitted probabilities have the same deviance however badly the model fits either one. Grouped binomial data with many trials per group do support a deviance test.

Question 4

Counts in some group have mean 4 and variance 12. Under the negative binomial model Var⁡y=μ+μ2/k\Var y=\mu+\mu^2/k, what is kk?

  1. k=2k=2
  2. k=3k=3
  3. k=8k=8
  4. k=0.5k=0.5
Show the answer

A. k=2k=2

12=4+16/k12=4+16/k gives 16/k=816/k=8, so k=2k=2. A Poisson would have variance 4; the extra 8 comes from variation of the underlying rates between units.

Further reading

  • J. A. Nelder & R. W. M. Wedderburn, "Generalized linear models," Journal of the Royal Statistical Society, Series A 135(3), 370–384 (1972).
  • P. McCullagh & J. A. Nelder, Generalized Linear Models, 2nd ed. (Chapman & Hall, 1989).
  • R. W. M. Wedderburn, "Quasi-likelihood functions, generalized linear models, and the Gauss–Newton method," Biometrika 61(3), 439–447 (1974).
  • P. Sur & E. J. Candès, "A modern maximum-likelihood theory for high-dimensional logistic regression," Proceedings of the National Academy of Sciences 116(29), 14516–14525 (2019).