Module contents
Lesson 20 of 27Advanced 105 min

Generalized linear models

Build generalized linear models using exponential families, links, IRLS, deviance and overdispersion remedies.

After this lesson you can

  • Choose a family and link suited to response support, variance and effect scale.
  • Derive canonical likelihood equations and the IRLS Fisher scoring update.
  • Interpret deviance, rates, offsets and model coefficients.
  • Detect overdispersion and compare quasi-likelihood, negative binomial and sandwich methods.

Before you start

Motivation: responses that are not normal

The Gaussian linear model of the previous lesson assumes three things at once: the mean of YY is linear in predictors, variance is constant, and errors are normal. Many practical responses violate all three:

  • Counts. The number of vulnerabilities an analyzer finds in a repository is a nonnegative integer, often zero, whose dispersion grows with its mean: a repository averaging 50 findings fluctuates far more than one averaging 2. A least-squares line predicts negative counts for small repositories and treats a 0 as equally reliable as a 50.
  • Proportions and binary events. Whether a user clicks, a build fails, or what fraction of a build’s tests fail. The mean is a probability confined to [0,1][0, 1], and variance μ(1−μ)\mu(1 - \mu) depends on it: maximal at 0.50.5 and zero at endpoints.
  • Positive skewed quantities. Build times, latencies, spending per customer. They are positive, have long right tails and standard deviation often proportional to the mean: 10% variation on a 30 s build is 3 s; on a 20-minute build, two minutes.

A tempting way out is to transform the response and continue with least squares: regress log⁡y\log y or y\sqrt{y}. This sometimes works but fails in essential ways. The log of a zero count does not exist; and even when it does, E[log⁡Y]≠log⁡E[Y]\E[\log Y] \neq \log\E[Y], so the transformed model describes a mean different from the one of interest, and one transform cannot simultaneously linearize the mean and stabilize variance.

Generalized linear models (GLMs, Nelder and Wedderburn, 1972) separate these roles. A link function makes the mean linear on a suitable scale; a distribution family governs variance and shape. Fitting uses maximum likelihood, and prior lessons’ theory (Fisher information, asymptotic normality, Wald, likelihood ratio, sandwich) applies directly. The result is one toolkit for linear, logistic, Poisson and gamma regression with one fitting algorithm.

The three ingredients

The exponential dispersion family

In lesson 7 you saw the exponential family in canonical form h(y)exp⁡(η⊤T(y)−A(η))h(y)\exp(\eta\T T(y) - A(\eta)). GLMs use the scalar case with T(y)=yT(y) = y, adding a scale parameter. Resolve a notational conflict now: in a GLM, η\eta is reserved for the linear predictor, so the natural parameter is called θ\theta (as in McCullagh and Nelder) and log-partition bb.

Mean and variance follow from bb without integration. One observation’s log-likelihood is ℓ=w(yθ−b(θ))/ϕ+c\ell = w(y\theta - b(\theta))/\phi + c, with score ∂ℓ/∂θ=w(y−b′(θ))/ϕ\partial\ell/\partial\theta = w(y - b'(\theta))/\phi and second derivative −w b′′(θ)/ϕ-w\,b''(\theta)/\phi. The two score identities from lesson 6, E[∂ℓ/∂θ]=0\E[\partial\ell/\partial\theta] = 0 and E[(∂ℓ/∂θ)2]=−E[∂2ℓ/∂θ2]\E[(\partial\ell/\partial\theta)^2] = -\E[\partial^2\ell/\partial\theta^2], give

μ=E[Y]=b′(θ),Var⁡(Y)=ϕw b′′(θ).\mu = \E[Y] = b'(\theta), \qquad \Var(Y) = \frac{\phi}{w}\, b''(\theta).

Since b′′>0b'' > 0, b′b' is strictly increasing and invertible: θ=(b′)−1(μ)\theta = (b')^{-1}(\mu). Variance is then a function of the mean,

Var⁡(Y)=ϕwV(μ),V(μ)=b′′((b′)−1(μ)),\Var(Y) = \frac{\phi}{w} V(\mu), \qquad V(\mu) = b''\big((b')^{-1}(\mu)\big),

the variance function. It is the family’s fingerprint: choosing a family is chiefly choosing how variance grows with mean.

FamilySupportθ(μ)\theta(\mu)b(θ)b(\theta)ϕ\phiV(μ)V(\mu)
Normal N(μ,σ2)\Normal(\mu, \sigma^2)R\Rμ\muθ2/2\theta^2/2σ2\sigma^211
Binomial: success proportion in mm trials (w=mw = m){0,1m,…,1}\{0, \tfrac1m, \dots, 1\}log⁡μ1−μ\log\frac{\mu}{1 - \mu}log⁡(1+eθ)\log(1 + e^\theta)11μ(1−μ)\mu(1 - \mu)
Poisson{0,1,2,… }\{0, 1, 2, \dots\}log⁡μ\log\mueθe^\theta11μ\mu
Gamma with mean μ\mu and shape ν\nu(0,∞)(0, \infty)−1/μ-1/\mu−log⁡(−θ)-\log(-\theta)1/ν1/\nuμ2\mu^2
Inverse Gaussian(0,∞)(0, \infty)−1/(2μ2)-1/(2\mu^2)−−2θ-\sqrt{-2\theta}1/λ1/\lambdaμ3\mu^3

Check one row. Gamma with mean μ\mu and shape ν\nu has density 1Γ(ν)(ν/μ)νyν−1e−νy/μ\frac{1}{\Gamma(\nu)}(\nu/\mu)^\nu y^{\nu - 1}e^{-\nu y/\mu}, whose logarithm is ν(−y/μ−log⁡μ)+c(y,ν)\nu(-y/\mu - \log\mu) + c(y, \nu). With θ=−1/μ\theta = -1/\mu read ν(yθ−b(θ))\nu(y\theta - b(\theta)) with b(θ)=−log⁡(−θ)=log⁡μb(\theta) = -\log(-\theta) = \log\mu, so ϕ=1/ν\phi = 1/\nu, b′(θ)=−1/θ=μb'(\theta) = -1/\theta = \mu and b′′(θ)=1/θ2=μ2b''(\theta) = 1/\theta^2 = \mu^2. Variance ϕμ2\phi\mu^2: standard deviation proportional to mean, constant coefficient of variation 1/ν1/\sqrt\nu. Exactly how build times behave.

The Gaussian linear model is the normal case with identity gg. Notice what the link does not do: transform data. It transforms the mean, a deterministic number, so one never calculates log⁡0\log 0. Variance is not modeled separately: the mean determines it through V(μ)V(\mu).

The link’s obvious job is mapping R\R (where η\eta lives) to allowed means. Logit and probit map R\R to (0,1)(0, 1); logarithm to (0,∞)(0, \infty). Identity maps R\R nowhere particular, a problem for a count family.

InteractiveLink and family
Simulated Poisson data, mean μ(x)\mu(x) and band μ±2ϕV(μ)\mu \pm 2\sqrt{\phi V(\mu)}
Inverse link μ=g−1(η)\mu = g^{-1}(\eta) and means admitted by the family
  • valid means
  • section used by the data
  • data
  • mean μ(x)\mu(x)
  • μ±2\mu \pm 2 standard deviations
  • impossible mean
Family
Link gg
1.20
0.55
Link and its inverseg(μ)=log⁡μ,μ=eηg(\mu) = \log\mu,\quad \mu = e^{\eta}
Variance function and mean supportV(μ)=μ,μ>0V(\mu) = \mu,\quad \mu > 0
Range of η\eta for x∈[−3,3]x \in [-3, 3][−0.45, 2.85]
Impossible means0% of the x range
Canonical link: the linear predictor is the natural parameter, θ=η\theta = \eta (apart from the sign for gamma). The likelihood equations are X⊤(y−μ)=0\mat{X}\T(\vb{y} - \vb{\mu}) = \vb{0}.
Left: simulated data from your specified model; orange curve is mean μ(x)=g−1(β0+β1x)\mu(x) = g^{-1}(\beta_0 + \beta_1 x) and band is μ±2ϕV(μ)\mu \pm 2\sqrt{\phi V(\mu)}. Right: inverse link with the same vertical axis; green strip shows means allowed by the family and thick segment the η\eta values data use. Start with Poisson and log link and compare band width where mean is small (left of data panel) and large (right). Switch to identity: what happens to small repositories? Try gamma (band widens proportionally to mean) and binomial with identity link (linear probability model).

Three things the figure shows:

  1. Family decides band shape. Normal has constant width; Poisson grows as μ\sqrt\mu; gamma as μ\mu; binomial narrows near 0 and 1. Ordinary least squares cannot reproduce these shapes.
  2. Link decides whether the mean is possible. With Poisson and identity link, η=β0+β1x\eta = \beta_0 + \beta_1 x becomes negative for small xx, and the model requests a negative mean, disallowed by the family: no data can be simulated there and log-likelihood is undefined. MLE sometimes exists with that link, but fitting must avoid the boundary and the model cannot extrapolate.
  3. Link decides the scale of additive effects. With log link, adding β1\beta_1 to the predictor multiplies the mean by eβ1e^{\beta_1}: effects are multiplicative, often natural for counts and times.

One link is privileged among all: the one making the linear predictor equal the natural parameter.

From the θ(μ)\theta(\mu) column: identity for normal, logit for binomial, log for Poisson and −1/μ-1/\mu for gamma (often used as 1/μ1/\mu with the sign of β\vb{\beta} changed). Canonical does not mean the best model for your data; it means algebra simplifies in a precise way.

With canonical link, sample log-likelihood is

ℓ(β)=∑i=1nwi(yi xi⊤β−b(xi⊤β))ϕ+∑ic(yi,ϕ/wi)=β⊤X⊤W0y−∑iwi b(xi⊤β)ϕ+cte.,\ell(\vb{\beta}) = \sum_{i=1}^n \frac{w_i\big(y_i\,\vb{x}_i\T\vb{\beta} - b(\vb{x}_i\T\vb{\beta})\big)}{\phi} + \sum_i c(y_i, \phi/w_i) = \frac{\vb{\beta}\T\mat{X}\T\mat{W}_0\vb{y} - \sum_i w_i\, b(\vb{x}_i\T\vb{\beta})}{\phi} + \text{cte.},

with W0=diag⁡(w1,…,wn)\mat{W}_0 = \diag(w_1, \dots, w_n). Data enter only through X⊤W0y\mat{X}\T\mat{W}_0\vb{y}, so with known ϕ\phi that vector of pp numbers is a sufficient statistic by the factorization theorem. It is the sufficient statistic of a pp-parameter exponential family with natural parameter β\vb{\beta}.

The proof is direct (differentiate twice above) and you will do it step by step in the exercises. Its consequences are used constantly:

  • Moments match. With an intercept, the first equation says ∑iwiyi=∑iwiμ^i\sum_i w_i y_i = \sum_i w_i\hat\mu_i: Poisson regression’s total fitted counts exactly match observed, and in logistic regression fitted probabilities sum to the number of ones. This also holds within each level of a categorical predictor.
  • No spurious local optima. Any algorithm finding a zero-score point has found the global maximum.
  • Observed and expected Hessians coincide, because they do not depend on y\vb{y}. This will make two different algorithms coincide.

Existence is not guaranteed. If in logistic regression a hyperplane separates ones from zeros (complete separation), likelihood strictly increases as β\vb{\beta} goes to infinity normal to that hyperplane and approaches its supremum, 1 (log-likelihood 0), without reaching it, so the MLE does not exist; Poisson has the same issue if all counts at a factor level are zero (that level’s estimated rate is 0, i.e. β^=−∞\hat\beta = -\infty). You will see this in the IRLS figure.

With a noncanonical link, score carries an extra factor (calculated next), the Hessian depends on y\vb{y} and concavity is no longer guaranteed. That does not make such links worse: probit, log-binomial, gamma with log link or Poisson with identity link are legitimate when effect scale calls for them.

IRLS: fitting as repeated weighted least squares

Except for normal with identity, likelihood equations are nonlinear in β\vb{\beta} and must be solved iteratively. Lesson 5’s numerical MLE used Newton; here Fisher scoring (Newton with Hessian replaced by negative expected information) has an especially elegant GLM form: each step is weighted linear regression.

The derivation fits in six lines: calculate score, then the Fisher information matrix, then rearrange the scoring step. Write μi′=dμi/dηi=1/g′(μi)\mu_i'= \mathrm{d}\mu_i/\mathrm{d}\eta_i = 1/g'(\mu_i) and define diagonal matrices

W=diag⁡(wi μi′2V(μi)),D=diag⁡(μi′).\mat{W} = \diag\Big(\frac{w_i\,\mu_i'^2}{V(\mu_i)}\Big), \qquad \mat{D} = \diag(\mu_i').
∂ℓi∂β=∂ℓi∂θi dθidμi dμidηi ∂ηi∂β\pd{\ell_i}{\vb{\beta}} = \pd{\ell_i}{\theta_i}\,\frac{\mathrm{d}\theta_i}{\mathrm{d}\mu_i}\,\frac{\mathrm{d}\mu_i}{\mathrm{d}\eta_i}\,\pd{\eta_i}{\vb{\beta}}
Chain rule for contribution of observation ii, depending on β\vb{\beta} through ηi→μi→θi\eta_i \to \mu_i \to \theta_i.
1/7

The second claim is the last consequence of the previous theorem: with canonical link, observed Hessian does not depend on y\vb{y} and therefore equals its expectation, −I(β)-\mathcal{I}(\vb{\beta}). Newton and scoring produce exactly the same iterates. You will reconstruct this in a guided exercise.

In logistic regression, g′(μ)=1/(μ(1−μ))g'(\mu) = 1/(\mu(1 - \mu)), so Wii=μi(1−μi)W_{ii} = \mu_i(1 - \mu_i) and zi=ηi+(yi−μi)/(μi(1−μi))z_i = \eta_i + (y_i - \mu_i)/(\mu_i(1 - \mu_i)). Points with μ^i\hat\mu_i near 0 or 1, already confidently classified, receive little weight; points near the boundary dominate each regression.

InteractiveIRLS step by step
Data, weights wiw_i (size), and boundary μ^=0.5\hat\mu = 0.5 at iteration 0
  • y = 1
  • y = 0
  • current boundary
  • μ^=0.1\hat\mu = 0.1 and 0.90.9
  • previous iterations
Working regression: ziz_i versus the new ηi\eta_i (size ∝wi\propto \sqrt{w_i})
z = η (weighted fit)
Mean score norm versus iteration (log-log)
  • IRLS
  • gradient (step 2)
  • tolerance 10−610^{-6}
iteration 0
Data
2
Iteration 0: β^0,β^1,β^2\hat\beta_0, \hat\beta_1, \hat\beta_20.000, 0.000, 0.000
Deviance DD97.0406
∥X⊤(y−μ)∥/n\lVert\mat{X}\T(\vb{y}-\vb{\mu})\rVert / n0.276
Iterations to 10−610^{-6}: IRLS | gradient4 | 226
IRLS takes the score below 10−610^{-6} in 4 steps; gradient descent with step size 2 needs 226. Near the optimum, IRLS doubles the correct digits at each step (quadratic convergence).
Logistic regression with two predictors. Each IRLS step calculates weights wi=μi(1−μi)w_i = \mu_i(1 - \mu_i) (point size) and working response ziz_i from current coefficients, then fits weighted least squares: top right, ziz_i versus new linear predictor with the line z=ηz = \eta produced by the fit. Below, score norm on log-log scale. Step from β=0\vb{\beta} = \vb{0}: how many steps does IRLS need, and gradient descent? Change gradient step size. Then choose 'separable': what happens to weights, deviance and coefficients?

What you should have seen:

  • From β=0\vb{\beta} = \vb{0}, the first step is ordinary least squares. All means are 0.50.5, weights 0.250.25, and zi=4(yi−0.5)=±2z_i = 4(y_i - 0.5) = \pm 2. The first boundary comes from linear regression of ±2\pm 2 on (x1,x2)(x_1, x_2), already pointing the right way.
  • Quadratic convergence. With overlapping classes, IRLS brings score below 10−610^{-6} in 4 steps, and the number of correct digits doubles in each final step: Newton’s hallmark. Gradient descent needs hundreds of iterations with the largest tolerable step and thousands with small steps; increase it further and convergence becomes oscillation. It converges linearly, at a rate dependent on Hessian condition number; here predictors are correlated (ρ=0.85\rho = 0.85) and uncentered, typical of real data. IRLS is immune: weighted regression exactly solves any linear reparameterization of X\mat{X}.
  • Separation. With separable data deviance approaches 0, coefficients grow without bound, and all point weights vanish because all are eventually classified with probability near 1. IRLS does not “fail”: it correctly pursues an unattained supremum. Beware stopping criteria: score and deviance also approach 0, so software watching only one declares convergence. In practice the symptom is huge coefficients with even larger standard errors and, at best, a warning of separation or fitted probabilities equal to 0 or 1.

Two implementation details. No initial β\vb{\beta} is needed: initial means making g(μ(0))g(\mu^{(0)}) finite suffice, such as (yi+yˉ)/2(y_i + \bar y)/2 for Poisson or (yi+0.5)/2(y_i + 0.5)/2 for binomial (used by statsmodels). With noncanonical links a step can worsen likelihood or leave the domain (negative Poisson mean with identity); hence R’s glm halves the step while deviance is nonfinite or means leave the domain, and glm2 also halves while deviance rises.

Deviance

In the linear model, residual sum of squares measures lack of fit and differences compare nested models. Its GLM generalization is deviance, comparing your model with the best imaginable fit: one parameter per observation.

The integral formula follows in one line: ∂ℓi/∂μ=wi(y−μ)/(ϕV(μ))\partial\ell_i/\partial\mu = w_i(y - \mu)/(\phi V(\mu)), so 2ϕ(ℓ(y)−ℓ(μ))/wi2\phi(\ell(y) - \ell(\mu))/w_i is the integral of 2(y−t)/V(t)2(y - t)/V(t) from μ\mu to yy. Since the integrand has the sign of y−ty - t, d(y,μ)≥0d(y, \mu) \ge 0 with equality only if μ=y\mu = y. Unit deviances of the four main families are:

Familyd(y,μ)d(y, \mu)
Normal(y−μ)2(y - \mu)^2
Binomial (proportion)2(ylog⁡yμ+(1−y)log⁡1−y1−μ)2\big(y\log\frac{y}{\mu} + (1 - y)\log\frac{1 - y}{1 - \mu}\big)
Poisson2(ylog⁡yμ−(y−μ))2\big(y\log\frac{y}{\mu} - (y - \mu)\big)
Gamma2(−log⁡yμ+y−μμ)2\big(-\log\frac{y}{\mu} + \frac{y - \mu}{\mu}\big)

with convention 0log⁡0=00\log 0 = 0. For normal, DD is residual sum of squares and ϕ=σ2\phi = \sigma^2. For Poisson with intercept, −(y−μ)-(y - \mu) sums to zero by moment matching, leaving the familiar G2=2∑yilog⁡(yi/μ^i)G^2 = 2\sum y_i\log(y_i/\hat\mu_i).

Compare nested models. If M0⊂M1M_0 \subset M_1 have p0<p1p_0 < p_1 parameters and fit the same data with the same family, saturated terms cancel:

D0−D1ϕ=2(ℓ(μ^1)−ℓ(μ^0)),\frac{D_0 - D_1}{\phi} = 2\big(\ell(\hat{\vb{\mu}}_1) - \ell(\hat{\vb{\mu}}_0)\big),

This is the likelihood-ratio test statistic; by Wilks’s theorem, under M0M_0 it is approximately χp1−p02\chi^2_{p_1 - p_0}. In Poisson and binomial ϕ=1\phi = 1 and deviance difference is directly compared to χ2\chi^2. If ϕ\phi is unknown (normal, gamma, or quasi-likelihood), estimate it with the larger model and use

F=(D0−D1)/(p1−p0)ϕ^  ≈  Fp1−p0,  n−p1,ϕ^=X2n−p1,X2=∑iwi(yi−μ^i)2V(μ^i),F = \frac{(D_0 - D_1)/(p_1 - p_0)}{\hat\phi} \;\approx\; F_{p_1 - p_0,\; n - p_1}, \qquad \hat\phi = \frac{X^2}{n - p_1},\quad X^2 = \sum_i \frac{w_i(y_i - \hat\mu_i)^2}{V(\hat\mu_i)},

which in the normal case is exactly the nested-model F test. X2X^2 is the generalized Pearson statistic. A sequence of these comparisons, adding terms one at a time, is an analysis of deviance, analogous to ANOVA.

Goodness of fit, with care. Comparing DD with χn−p2\chi^2_{n - p} to judge fit is tempting. The approximation only holds in the small-dispersion regime: large Poisson counts or binomials with large mim_i, so each yiy_i is approximately normal. When nn grows with fixed mim_i it fails because the saturated model gains one parameter per observation and Wilks does not apply. The extreme is binary data (mi=1m_i = 1): for logistic regression, likelihood equations give 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), a function of fitted values that does not depend on yiy_i beyond what the fit already contains. It says nothing about goodness of fit.

Inference and residuals

Everything you know about MLE applies. By MLE asymptotic normality,

β^  ≈  N(β, ϕ(X⊤W^X)−1),\hat{\vb{\beta}} \;\approx\; \Normal\big(\vb{\beta},\ \phi(\mat{X}\T\hat{\mat{W}}\mat{X})^{-1}\big),

with W^\hat{\mat{W}} the final IRLS weight: the covariance matrix comes free from the algorithm. Three inference tools:

  • Wald. The Wald test zj=β^j/EEjz_j = \hat\beta_j/\mathrm{EE}_j and interval β^j±1.96 EEj\hat\beta_j \pm 1.96\,\mathrm{EE}_j appear in every coefficient table.
  • Likelihood ratio. The previous section’s deviance difference. For one coefficient, compare the model with and without it.
  • Profile intervals. The profile-likelihood interval inverts the likelihood ratio: {βj:D(βj)−D(β^j)≤ϕ χ1,0.952}\{\beta_j : D(\beta_j) - D(\hat\beta_j) \le \phi\,\chi^2_{1, 0.95}\}, where D(βj)D(\beta_j) minimizes deviance over other coefficients. It is invariant under monotone transformations (the interval for rate ratio eβje^{\beta_j} is the exponential of that for βj\beta_j, without new approximations) and respects likelihood skewness.

All three agree asymptotically and are barely distinguishable for large samples and moderate effects (in the laboratory below, z2=36.86z^2 = 36.86 versus likelihood ratio 36.8936.89). They diverge for small samples, low counts or extreme probabilities, where Wald is least reliable. Logistic regression also has the Hauck–Donner effect (1977): for very large effects, standard error grows faster than the coefficient and Wald statistic decreases as it moves away from null, potentially failing to reject nearly separated data. Likelihood ratio and profile avoid this problem.

Residuals. Raw GLM residuals yi−μ^iy_i - \hat\mu_i are not comparable because each observation has its own variance. Two standardized versions are:

riP=(yi−μ^i)wiV(μ^i),riD=sign⁡(yi−μ^i)wi d(yi,μ^i),r^P_i = \frac{(y_i - \hat\mu_i)\sqrt{w_i}}{\sqrt{V(\hat\mu_i)}}, \qquad r^D_i = \operatorname{sign}(y_i - \hat\mu_i)\sqrt{w_i\,d(y_i, \hat\mu_i)},

Pearson and deviance residuals, with ∑i(riP)2=X2\sum_i (r^P_i)^2 = X^2 and ∑i(riD)2=D\sum_i (r^D_i)^2 = D. To compare with standard normal divide by ϕ(1−hii)\sqrt{\phi(1 - h_{ii})}, where hiih_{ii} is the hat-matrix diagonal of the last weighted regression, H=W1/2X(X⊤WX)−1X⊤W1/2\mat{H} = \mat{W}^{1/2}\mat{X}(\mat{X}\T\mat{W}\mat{X})^{-1}\mat{X}\T\mat{W}^{1/2}. Deviance residuals tend to be closer to normal for skewed families (low-mean Poisson, gamma), because the square root of deviance corrects some skewness.

For discrete responses and small means no residual is normal: in binary logistic regression, residuals versus η^\hat\eta form two curved bands, one for each yy, and reveal nothing by eye. Alternatives are grouping (compare observed and fitted proportions in μ^\hat\mu bins) or Dunn–Smyth randomized quantile residuals (1996), exactly standard normal under the correct model evaluated at true parameters (approximately so with estimates).

Interpreting coefficients: odds, rates and exposure

A GLM coefficient is additive on the link scale. What that means on the mean scale depends on the link.

Log link (Poisson, gamma, negative binomial). If xjx_j increases one unit holding others fixed,

μ(x+ej)μ(x)=eβj.\frac{\mu(\vb{x} + \vb{e}_j)}{\mu(\vb{x})} = e^{\beta_j}.

Effects are multiplicative and eβje^{\beta_j} is a rate ratio, or for times, a mean ratio. A coefficient 0.30.3 for a binary variable means the group with xj=1x_j = 1 has mean e0.3=1.35e^{0.3} = 1.35 times larger: 35% more, not 30%. For small coefficients, eβ≈1+βe^{\beta} \approx 1 + \beta and “100β100\beta %” is approximately right; for β=0.7\beta = 0.7 it is misleading (e0.7=2.01e^{0.7} = 2.01).

Logit link. Now βj\beta_j is the change in log odds, log⁡(μ/(1−μ))\log(\mu/(1 - \mu)), and eβje^{\beta_j} is an odds ratio. Its probability effect is not constant:

∂μ∂xj=βj μ(1−μ),∣∂μ∂xj∣≤∣βj∣4,\pd{\mu}{x_j} = \beta_j\,\mu(1 - \mu), \qquad \Big|\pd{\mu}{x_j}\Big| \le \frac{|\beta_j|}{4},

maximal in absolute value at μ=0.5\mu = 0.5 and negligible near 0 or 1. Bound ∣βj∣/4|\beta_j|/4 (the “divide by four” rule) gives the largest possible probability change per unit of xjx_j. For rare events, small μ\mu, odds μ/(1−μ)\mu/(1 - \mu) approximate μ\mu and odds ratio approximates risk ratio; otherwise they can differ greatly. Probit coefficients are read on a latent-normal scale and are approximately logit coefficients divided by 1.6.

Rates and exposure: the offset

Counts often depend on how much was observed. A service monitored 2000 hours accumulates more incidents than one monitored 200 even if both are equally fragile. Model the rate λ(x)\lambda(\vb{x}) per exposure unit, with E[Yi]=ti λ(xi)\E[Y_i] = t_i\,\lambda(\vb{x}_i) and known exposure tit_i (hours, users, lines of code, person-years). With log link,

log⁡μi=log⁡ti+xi⊤β.\log\mu_i = \log t_i + \vb{x}_i\T\vb{\beta}.

Term log⁡ti\log t_i enters the linear predictor with fixed coefficient 1: an offset. Rate models with exposure offsets use the same IRLS, subtracting the offset from working response (zi=ηi−log⁡ti+(yi−μi)/μiz_i = \eta_i - \log t_i + (y_i - \mu_i)/\mu_i) and adding it back when recalculating η\eta. Coefficients are log rate ratios.

Forgetting the offset is not harmless. If exposure correlates with a predictor, that predictor absorbs exposure differences. In the laboratory below, critical services are monitored about 2.5 times as many hours; without offset, estimated rate ratio for “critical” is 3.83.8 when truth is 1.491.49: more exposure is confused with more risk. Including log⁡ti\log t_i as a covariate with free coefficient is valid if proportionality is uncertain; including tit_i without log is not.

Overdispersion

Poisson and binomial have no free dispersion parameter: ϕ=1\phi = 1 and the mean fixes variance. Real data rarely obey this.

The usual cause is unobserved heterogeneity. If each repository has its own rate, Y∣λ∼Pois⁡(λ)Y \given \lambda \sim \Pois(\lambda), and rates vary around the model mean with E[λ]=μ\E[\lambda] = \mu and Var⁡(λ)=αμ2\Var(\lambda) = \alpha\mu^2, total variance gives

Var⁡(Y)=E[Var⁡(Y∣λ)]+Var⁡(E[Y∣λ])=μ+αμ2.\Var(Y) = \E[\Var(Y \given \lambda)] + \Var(\E[Y \given \lambda]) = \mu + \alpha\mu^2.

If λ\lambda is gamma, marginal YY is exactly negative binomial. In binomial data, positive correlation within each group of mm trials (tests in one build failing together) gives group success-count variance Var⁡=mμ(1−μ)(1+(m−1)ρ)\Var = m\mu(1 - \mu)\big(1 + (m - 1)\rho\big) instead of mμ(1−μ)m\mu(1 - \mu): model ϕV(μ)/w\phi V(\mu)/w with ϕ=1+(m−1)ρ\phi = 1 + (m - 1)\rho when groups share mm.

What fails and what does not. Estimating equations X⊤WD−1(y−μ)=0\mat{X}\T\mat{W}\mat{D}^{-1}(\vb{y} - \vb{\mu}) = \vb{0} involve only the mean; if the mean model is correct their expectation is zero even under another variance, and β^\hat{\vb{\beta}} remains consistent: an M-estimator with unbiased equations. Uncertainty fails: actual covariance is approximately ϕ\phi times model covariance, standard errors are too small by ϕ\sqrt\phi, zz statistics too large and intervals too narrow. With ϕ=3\phi = 3, a nominal 95% interval covers about 74%. This is a classic source of false discoveries.

Detection. Ratio X2/(n−p)X^2/(n - p) (or D/(n−p)D/(n - p) if counts are not small) should be near 1; values 2 or 3 clearly indicate overdispersion. Before blaming variance, rule out a wrong mean model (missing predictor, nonlinearity, unsuitable link), which also inflates the ratio.

InteractiveOverdispersion and standard errors
A sample of n=60n = 60 counts with the Poisson fit
  • counts
  • true band μ±2μ+αμ2\mu \pm 2\sqrt{\mu + \alpha\mu^2}
  • Poisson fit and its band ±2μ^\pm 2\sqrt{\hat\mu}
  • true mean
Distribution of β^1\hat\beta_1 (Poisson) across 400 replications and the normal curves implied by the standard errors
β₁ = 0.5
  • simulated β^1\hat\beta_1
  • Poisson
  • quasi-Poisson
Actual coverage of the 95% Wald intervals
Poisson 67.5 %quasi-Poisson 93.3 %sandwich 90.3 %negative binomial 92.3 %
0.50
Sample size nn
D/(n−p)D/(n-p) in this sample | mean across replications3.27 | 3.24
True standard deviation of β^1\hat\beta_1 (Monte Carlo)0.2033
Mean SE: Poisson | quasi-Poisson0.1060 | 0.1917
Mean SE: sandwich | negative binomial0.1859 | 0.1865
With α=0.50\alpha = 0.50 the true variance is about 3.3 times the Poisson variance: Poisson standard errors are about 3.3≈1.83\sqrt{3.3} \approx 1.83 times too small, and its interval covers 68 %. Estimates remain centered (mean β^1\hat\beta_1: 0.484); only the uncertainty fails.
Counts generated with log⁡μ=1.5+0.5x\log\mu = 1.5 + 0.5x and variance μ+αμ2\mu + \alpha\mu^2 (gamma–Poisson mixture). Left: a sample with the true band and Poisson fit's assumed band. Top right: distribution of β^1\hat\beta_1 over 400 replicates versus normals promised by Poisson and quasi-Poisson standard errors. Bottom: actual coverage of 95% Wald intervals using four standard errors. Reduce α\alpha to 0 and increase gradually: what happens to histogram, Poisson curve and coverage? Does histogram center move? Reduce nn to 30 and inspect sandwich.

The figure summarizes diagnosis: with α=0\alpha = 0 everything works and D/(n−p)≈1D/(n - p) \approx 1; increasing α\alpha widens the β^1\hat\beta_1 histogram while keeping it centered at 0.50.5, Poisson’s promised normal stays narrow and its coverage falls far below 95%, while the other three remain near it. Three standard remedies follow.

1. Quasi-likelihood. Wedderburn (1974) observed that IRLS uses only mean and variance function, never the complete distribution. If we specify only

E[Yi]=μi(β),Var⁡(Yi)=ϕ V(μi)/wi,\E[Y_i] = \mu_i(\vb{\beta}), \qquad \Var(Y_i) = \phi\,V(\mu_i)/w_i,

the quasi-score U=X⊤WD−1(y−μ)/ϕ\vb{U} = \mat{X}\T\mat{W}\mat{D}^{-1}(\vb{y} - \vb{\mu})/\phi satisfies both score properties needed for asymptotic theory: zero expectation and Var⁡(U)=E[−∂U/∂β⊤]\Var(\vb{U}) = \E[-\partial\vb{U}/\partial\vb{\beta}\T]. It derives from quasi-likelihood Q(μ;y)=∫yμy−tϕV(t) ⁣dtQ(\mu; y) = \int_y^\mu \frac{y - t}{\phi V(t)}\dd t, behaving like log-likelihood without corresponding to a distribution. In practice quasi-Poisson gives Poisson’s same β^\hat{\vb{\beta}}, estimates ϕ^=X2/(n−p)\hat\phi = X^2/(n - p), multiplies standard errors by ϕ^\sqrt{\hat\phi} and compares models using the deviance section’s FF test. Use when variance is proportional to mean.

2. Negative binomial. Models Var⁡(Y)=μ+αμ2\Var(Y) = \mu + \alpha\mu^2 and estimates α\alpha by maximum likelihood. With fixed α\alpha it is a GLM (own variance function), fitted with IRLS alternating with estimation of α\alpha. Its log-link weights Wii=μi/(1+αμi)W_{ii} = \mu_i/(1 + \alpha\mu_i) give high-mean observations relatively less weight than Poisson, so β^\hat{\vb{\beta}} differs somewhat. Use when variance grows quadratically with mean (plot (yi−μ^i)2(y_i - \hat\mu_i)^2 versus μ^i\hat\mu_i). Testing α=0\alpha = 0 by likelihood ratio has a nuance: null is on the parameter boundary, and null distribution is a 50% mixture of mass at 0 and χ12\chi^2_1, so p-value is half the χ12\chi^2_1 value.

3. Sandwich errors. The sandwich variance from lesson 8,

Cov⁡^(β^)=(X⊤W^X)−1(∑iu^iu^i⊤)(X⊤W^X)−1,u^i=wiμ^i′(yi−μ^i)V(μ^i)xi,\widehat{\Cov}(\hat{\vb{\beta}}) = (\mat{X}\T\hat{\mat{W}}\mat{X})^{-1}\Big(\sum_i \hat{\vb{u}}_i\hat{\vb{u}}_i\T\Big)(\mat{X}\T\hat{\mat{W}}\mat{X})^{-1}, \qquad \hat{\vb{u}}_i = \frac{w_i\hat\mu_i'(y_i - \hat\mu_i)}{V(\hat\mu_i)}\vb{x}_i,

assumes nothing about variance: only correct mean specification and independent observations (or independent groups in its clustered version). It is a safety net when no variance model is trustworthy. Its price: no improvement in β^\hat{\vb{\beta}} (still Poisson, inefficient if actual variance differs), noisier variance estimate and downward bias in small samples: with n=30n = 30 the figure shows some undercoverage, motivating HC1–HC3 corrections.

Excess zeros. A common case: more zeros than the model permits because a subpopulation never produces events (archived repositories, services without traffic). Detect by comparing observed zeros with expected ∑ie−μ^i\sum_i e^{-\hat\mu_i} for Poisson. Negative binomial often explains them already, since a highly dispersed gamma mean places much mass near zero; otherwise use zero-inflated models (mixture of structural zero and count) or hurdle models (a binary model for “zero or not” and a truncated model for positives).

Implementation from scratch

Generic IRLS needs, for each link, gg, g−1g^{-1} and dμ/dη\mathrm{d}\mu/\mathrm{d}\eta, and for each family, V(μ)V(\mu), unit deviance and initial means. Everything else is the previous section’s iteration.

[ ]GLM with IRLS from scratchBrowser
import numpy as np
from scipy import special, stats

class Enlace:
    def __init__(self, nombre, g, ginv, dmu):
        self.nombre, self.g, self.ginv, self.dmu = nombre, g, ginv, dmu   # dmu(eta) = dmu/deta

identidad = Enlace("identidad", lambda m: m, lambda e: e, lambda e: np.ones_like(e))
logit = Enlace("logit", special.logit, special.expit, lambda e: special.expit(e) * special.expit(-e))
probit = Enlace("probit", special.ndtri, special.ndtr, lambda e: np.exp(-e**2 / 2) / np.sqrt(2 * np.pi))
log = Enlace("log", np.log, np.exp, np.exp)
inversa = Enlace("inversa", lambda m: 1 / m, lambda e: 1 / e, lambda e: -1 / e**2)

def ylogy(y, mu):
    """y log(y / mu), con 0 log 0 = 0."""
    return special.xlogy(y, y) - special.xlogy(y, mu)

class Familia:
    def __init__(self, nombre, V, d, mu0, canonico, phi_fija):
        self.nombre, self.V, self.d, self.mu0 = nombre, V, d, mu0
        self.canonico, self.phi_fija = canonico, phi_fija

binomial = Familia("binomial", lambda m: m * (1 - m),
                   lambda y, m: 2 * (ylogy(y, m) + ylogy(1 - y, 1 - m)),
                   lambda y: (y + 0.5) / 2, logit, True)
poisson = Familia("Poisson", lambda m: m,
                  lambda y, m: 2 * (ylogy(y, m) - (y - m)),
                  lambda y: (y + y.mean()) / 2, log, True)
gamma = Familia("gamma", lambda m: m**2,
                lambda y, m: 2 * (-np.log(y / m) + (y - m) / m),
                lambda y: (y + y.mean()) / 2, inversa, False)

def ajustar_glm(X, y, familia, enlace=None, pesos=None, offset=None, tol=1e-10, max_iter=50):
    """IRLS: scoring de Fisher escrito como mínimos cuadrados ponderados."""
    enlace = enlace or familia.canonico
    n, p = X.shape
    w0 = np.ones(n) if pesos is None else np.asarray(pesos, float)    # pesos a priori (m_i en la binomial)
    off = np.zeros(n) if offset is None else np.asarray(offset, float)
    mu = familia.mu0(y)
    eta = enlace.g(mu)
    dev = np.inf
    for it in range(1, max_iter + 1):
        dmu = enlace.dmu(eta)
        z = eta - off + (y - mu) / dmu             # respuesta de trabajo (sin el offset)
        W = w0 * dmu**2 / familia.V(mu)            # pesos de trabajo
        XtW = X.T * W
        beta = np.linalg.solve(XtW @ X, XtW @ z)   # ecuaciones normales ponderadas
        eta = X @ beta + off
        mu = enlace.ginv(eta)
        dev_nueva = np.sum(w0 * familia.d(y, mu))
        hecho = abs(dev_nueva - dev) < tol * (abs(dev_nueva) + 0.1)
        dev = dev_nueva
        if hecho:
            break
    dmu = enlace.dmu(eta)
    W = w0 * dmu**2 / familia.V(mu)
    pearson = np.sum(w0 * (y - mu)**2 / familia.V(mu))
    phi = 1.0 if familia.phi_fija else pearson / (n - p)
    cov = phi * np.linalg.inv((X.T * W) @ X)
    return dict(beta=beta, se=np.sqrt(np.diag(cov)), mu=mu, desviacion=dev,
                pearson=pearson, phi=phi, iter=it, gl=n - p)

# vulnerabilidades por repositorio (datos sintéticos)
rng = np.random.default_rng(20)
n = 500
kloc = np.exp(rng.normal(3.0, 1.0, n))          # miles de líneas de código
deps = rng.poisson(40, n)                         # dependencias directas
ci = rng.binomial(1, 0.6, n)                      # análisis estático en la integración continua
X = np.column_stack([np.ones(n), np.log(kloc), deps / 10, ci])
nombres = ["intercepto", "log kLOC", "deps/10", "CI"]
y = rng.poisson(np.exp(X @ np.array([-2.0, 0.6, 0.15, -0.5])))

propio = ajustar_glm(X, y, poisson)
import statsmodels.api as sm
ref = sm.GLM(y, X, family=sm.families.Poisson()).fit()
print(f"{'':12s}{'propio':>10s}{'statsmodels':>13s}{'EE propio':>11s}{'EE sm':>9s}")
for j, nm in enumerate(nombres):
    print(f"{nm:12s}{propio['beta'][j]:10.5f}{ref.params[j]:13.5f}{propio['se'][j]:11.5f}{ref.bse[j]:9.5f}")
print(f"desviación: {propio['desviacion']:.4f} (sm {ref.deviance:.4f}) con {propio['gl']} gl; iteraciones IRLS: {propio['iter']}")
print("máx |Δβ| frente a statsmodels:", np.max(np.abs(propio['beta'] - ref.params)))

# Wald y razón de verosimilitudes para el coeficiente de CI
sin_ci = ajustar_glm(X[:, :3], y, poisson)
rv = sin_ci['desviacion'] - propio['desviacion']
zw = propio['beta'][3] / propio['se'][3]
print(f"\nCI: Wald z² = {zw**2:.2f} (p = {stats.chi2.sf(zw**2, 1):.2e}); "
      f"RV = D0 - D1 = {rv:.2f} (p = {stats.chi2.sf(rv, 1):.2e})")
b, s = propio['beta'][3], propio['se'][3]
print(f"razón de tasas de CI: {np.exp(b):.3f}, IC 95 % de Wald [{np.exp(b - 1.96 * s):.3f}, {np.exp(b + 1.96 * s):.3f}]")

The custom fit agrees with statsmodels to rounding error in five iterations, and standard errors follow from (X⊤W^X)−1(\mat{X}\T\hat{\mat{W}}\mat{X})^{-1} with no extra work. Deviance 506 on 496 degrees of freedom does not indicate overdispersion: data were generated from Poisson. Continuous integration’s effect is rate ratio 0.6150.615: repositories with static analysis in CI have 38.5% fewer vulnerabilities at the same size and dependency count. The interval is constructed on the β\beta scale and exponentiated afterward, hence asymmetric around 0.6150.615.

Now noncanonical links and gamma. The fraction of failed tests per build is modeled with binomial and weights mim_i (number of tests run); build times with gamma. Finally, distance from MLE at each iteration shows quadratic convergence.

[ ]Noncanonical links, gamma and quadratic convergenceBrowser
import warnings

# 1) proporción de tests fallidos por build: binomial con m_i ensayos, logit (canónico) y probit
rng = np.random.default_rng(3)
nb = 300
cambios = rng.gamma(2.0, 150, nb)                  # líneas cambiadas en el commit
nocturno = rng.binomial(1, 0.3, nb)
m = rng.integers(50, 400, nb)                       # tests ejecutados en cada build
Xb = np.column_stack([np.ones(nb), np.log(cambios), nocturno])
fallos = rng.binomial(m, special.ndtr(Xb @ np.array([-3.2, 0.25, 0.3])))
yb = fallos / m
for enl, link_sm in [(logit, sm.families.links.Logit()), (probit, sm.families.links.Probit())]:
    f = ajustar_glm(Xb, yb, binomial, enl, pesos=m)
    r = sm.GLM(np.column_stack([fallos, m - fallos]), Xb, family=sm.families.Binomial(link=link_sm)).fit()
    print(f"binomial-{enl.nombre:7s} β = {np.round(f['beta'], 4)}  D = {f['desviacion']:.3f} "
          f"(sm {r.deviance:.3f})  |Δβ| = {np.max(np.abs(f['beta'] - r.params)):.1e}  iter = {f['iter']}")

# 2) tiempos de compilación (forma 4, φ = 0.25): gamma con enlace log y con el canónico
nc = 250
modulos = rng.integers(1, 60, nc)
cache = rng.binomial(1, 0.5, nc)
Xc = np.column_stack([np.ones(nc), np.log(modulos), cache])
tiempos = rng.gamma(4.0, np.exp(Xc @ np.array([1.0, 0.8, -0.6])) / 4.0)
for enl, link_sm in [(log, sm.families.links.Log()), (inversa, sm.families.links.InversePower())]:
    f = ajustar_glm(Xc, tiempos, gamma, enl)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")    # statsmodels avisa: 1/mu no garantiza medias positivas
        r = sm.GLM(tiempos, Xc, family=sm.families.Gamma(link=link_sm)).fit(scale="X2")
    print(f"gamma-{enl.nombre:8s} β = {np.round(f['beta'], 4)}  φ̂ = {f['phi']:.4f} (sm {r.scale:.4f})  "
          f"EE = {np.round(f['se'], 4)} (sm {np.round(r.bse, 4)})")

# 3) convergencia cuadrática: distancia al EMV en cada iteración (logística de los builds)
beta_hat = ajustar_glm(Xb, yb, binomial, logit, pesos=m, tol=0)["beta"]
mu = binomial.mu0(yb)
eta = logit.g(mu)
for it in range(1, 7):
    dmu = logit.dmu(eta)
    W = m * dmu**2 / binomial.V(mu)
    z = eta + (yb - mu) / dmu
    beta = np.linalg.solve((Xb.T * W) @ Xb, (Xb.T * W) @ z)
    eta = Xb @ beta
    mu = logit.ginv(eta)
    print(f"iteración {it}: ‖β - β̂‖ = {np.linalg.norm(beta - beta_hat):.2e}")

Three observations. Build data were generated with probit, yet logit has lower deviance (326.8 versus 332.1): with 300 builds the links are nearly indistinguishable and such a difference cannot select one. Logit coefficients are 2 to 2.2 times probit, not 1.6: the 1.6 rule holds for intermediate probabilities, while failure rates here are a few percent, where the logistic tail is heavier than normal and the ratio of link slopes (normal density at Φ−1(μ)\Phi^{-1}(\mu) divided by μ(1−μ)\mu(1 - \mu)) rises from 1.6 at μ=0.5\mu = 0.5 to 2.2 at μ=0.05\mu = 0.05. For gamma, log link (true) estimates ϕ^=0.2506\hat\phi = 0.2506, nearly the 1/ν=0.251/\nu = 0.25 used to simulate data; canonical link, misspecified for these data, leaves more variability unexplained and its ϕ^\hat\phi rises to 0.320.32. The final trace shows textbook quadratic convergence: 2.5×10−22.5\times 10^{-2}, 6.5×10−56.5\times 10^{-5}, 4.3×10−104.3\times 10^{-10}; each error is of order the previous error squared.

With libraries: incident rates with exposure

In statsmodels, a GLM is sm.GLM(y, X, family=...) or, with formulas, smf.glm("y ~ a + b", datos, family=...). Important options:

Itemstatsmodels
Family and linksm.families.Poisson(), Binomial(link=sm.families.links.Probit()), Gamma(link=sm.families.links.Log())
Binomial with mim_i trialstwo-column response [éxitos, fracasos], or proportion with var_weights=m
Exposureoffset=np.log(t) (or exposure=t, which takes the log)
Quasi-likelihood.fit(scale="X2"): ϕ^=X2/(n−p)\hat\phi = X^2/(n - p)
Sandwich errors.fit(cov_type="HC0") (or "HC1", or "cluster" with groups)
Negative binomial with estimated α\alphasmf.negativebinomial(...) (discrete model, joint MLE)
Deviance, Pearson, residualsres.deviance, res.pearson_chi2, res.resid_deviance, res.resid_pearson

The laboratory simulates security incidents in 300 services with two risk factors (criticality and internet exposure), monitoring hours depending on criticality, and unobserved heterogeneity with α=0.6\alpha = 0.6.

[ ]Incident rates per service with exposureBrowser
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(7)
n = 300
critico = rng.binomial(1, 0.35, n)
internet = rng.binomial(1, 0.5, n)
horas = np.round(rng.uniform(200, 2000, n) * (1 + 1.5 * critico))   # los críticos se vigilan más horas
tasa = np.exp(0.2 + 0.4 * critico + 0.7 * internet)                 # incidentes por 1000 horas
alpha = 0.6                                                          # heterogeneidad no observada
y = rng.poisson(horas / 1000 * tasa * rng.gamma(1 / alpha, alpha, n))
df = pd.DataFrame(dict(incidentes=y, critico=critico, internet=internet, horas=horas))
expo = np.log(df.horas / 1000)

form = "incidentes ~ critico + internet"
pois = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit()
sin_off = smf.glm(form, df, family=sm.families.Poisson()).fit()
print("razones de tasas (verdad: crítico 1.49, internet 2.01)")
print("  con offset:", np.round(np.exp(pois.params[1:]).values, 3))
print("  sin offset:", np.round(np.exp(sin_off.params[1:]).values, 3))

print(f"\nPearson/gl = {pois.pearson_chi2 / pois.df_resid:.2f}   D/gl = {pois.deviance / pois.df_resid:.2f}")
quasi = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit(scale="X2")
sand = smf.glm(form, df, family=sm.families.Poisson(), offset=expo).fit(cov_type="HC0")
nbm = smf.negativebinomial(form, df, offset=expo).fit(disp=0)
print(f"α̂ de la binomial negativa (EMV): {nbm.params['alpha']:.3f}  (verdad {alpha})")
print(f"\n{'':18s}{'β internet':>11s}{'EE':>8s}{'IC 95 % de la razón de tasas':>32s}")
for nombre, r in [("Poisson", pois), ("cuasi-Poisson", quasi), ("sándwich (HC0)", sand), ("binomial negativa", nbm)]:
    b, s = r.params["internet"], r.bse["internet"]
    print(f"{nombre:18s}{b:11.4f}{s:8.4f}        [{np.exp(b - 1.96 * s):.3f}, {np.exp(b + 1.96 * s):.3f}]")

# ceros observados frente a esperados
mu_p = pois.fittedvalues
mu_nb = nbm.predict(df, offset=expo)
a = nbm.params["alpha"]
print(f"\nceros: observados {np.sum(y == 0)}, esperados Poisson {np.sum(np.exp(-mu_p)):.1f}, "
      f"binomial negativa {np.sum((1 + a * mu_nb) ** (-1 / a)):.1f}")
# razón de verosimilitudes para α = 0 (en la frontera: mitad de una χ²₁)
rv = 2 * (nbm.llf - pois.llf)
print(f"RV de α = 0: {rv:.1f}, p = {0.5 * stats.chi2.sf(rv, 1):.1e}")

The output tells the entire overdispersion section with data:

  • Offset matters. With it, rate ratios (1.541.54 and 2.072.07) are near truth; without, the “critical” ratio jumps to 3.83.8 because it absorbs extra monitoring hours.
  • Clear overdispersion. X2/gl≈3X^2/\text{gl} \approx 3, and negative binomial estimates α^=0.65\hat\alpha = 0.65, near the true 0.60.6. The test of α=0\alpha = 0 is overwhelming.
  • Poisson standard errors are half what they should be. For “internet,” 0.0630.063 versus 0.1090.109 (quasi), 0.1320.132 (sandwich) and 0.1210.121 (negative binomial). Poisson’s rate-ratio interval, [1.83,2.34][1.83, 2.34], is misleadingly narrow. All three remedies agree in order of magnitude; negative binomial also changes the point estimate (0.650.65 versus 0.730.73) because it weights differently.
  • Zeros reveal the problem. Poisson expects 51 incident-free services and there are 80; negative binomial expects 80.4. No zero-inflated model is needed: heterogeneity explains them.

Common mistakes

Exercises

NumericA rate ratio
In Poisson regression with log link, the coefficient for a binary variable (internet-exposed service) is β^=0.3\hat\beta = 0.3. What is the rate ratio of exposed to unexposed services?
NumericFrom odds ratio to probability
In logistic regression, the coefficient for mandatory code review in the probability that a build passes is 0.80.8. For a team without review, fitted probability is 0.20.2. What is the fitted probability for the same team with mandatory review, holding other predictors fixed?
NumericExpected count with exposure
A Poisson incident model with offset log⁡(horas)\log(\text{horas}) has β^0=−3.5\hat\beta_0 = -3.5 and coefficient β^1=0.4\hat\beta_1 = 0.4 for 'critical service'. How many incidents do you expect for a critical service observed for 500 hours?
NumericWald with quasi-Poisson
A Poisson regression with n−p=150n - p = 150 residual degrees of freedom gives β^j=0.10\hat\beta_j = 0.10, standard error 0.040.04 and Pearson statistic X2=450X^2 = 450. What is the Wald zz statistic for βj\beta_j in the quasi-Poisson model?
NumericAnalysis of deviance
Two nested Poisson models fit to the same 200 counts have deviances D0=412.3D_0 = 412.3 (4 parameters) and D1=398.1D_1 = 398.1 (6 parameters). Assuming no overdispersion, what is the p-value of the likelihood-ratio test of M0M_0 versus M1M_1?
QuizFamily, link and offset
Which specifications suit the problems described? Select all that apply.

More than one answer may be correct.

QuizWhat a logit coefficient says
A logistic regression models the probability a pull request introduces a vulnerability; the coefficient for an author external to the team is 0.80.8. Which statements are correct? Select all that apply.

More than one answer may be correct.

QuizWhich model fits better?
Fit Poisson (D=310D = 310, 196 df) and negative binomial (D=215D = 215, 196 df, α^=0.4\hat\alpha = 0.4) to the same 200 counts. Which conclusions are valid? Select all that apply.

More than one answer may be correct.

QuizGoodness of fit with binary data
You fit logistic regression to n=500n = 500 binary responses with 5 parameters and obtain D=497.2D = 497.2. What can comparing DD with χ4952\chi^2_{495} tell you?
ProofLikelihood equations and concavity with canonical link
Prove: In a GLM with canonical link, weights wiw_i and known dispersion ϕ\phi, likelihood equations are X⊤W0(y−μ)=0\mat{X}\T\mat{W}_0(\vb{y} - \vb{\mu}) = \vb{0} and log-likelihood is concave in β\vb{\beta} (strictly if X\mat{X} has rank pp).
0
With canonical link, θi=ηi=xi⊤β\theta_i = \eta_i = \vb{x}_i\T\vb{\beta}, so ℓ(β)=∑iwi(yixi⊤β−b(xi⊤β))/ϕ+cte\ell(\vb{\beta}) = \sum_i w_i\big(y_i\vb{x}_i\T\vb{\beta} - b(\vb{x}_i\T\vb{\beta})\big)/\phi + \text{cte}.

Step 1 of 4. What is the gradient of ℓ\ell with respect to β\vb{\beta}?

ProofIRLS is Fisher scoring, and Newton with canonical link
Prove: A GLM's Fisher scoring update is β(t+1)=(X⊤WX)−1X⊤Wz\vb{\beta}^{(t+1)} = (\mat{X}\T\mat{W}\mat{X})^{-1}\mat{X}\T\mat{W}\vb{z} with zi=ηi+(yi−μi)g′(μi)z_i = \eta_i + (y_i - \mu_i)g'(\mu_i) and Wii=wi/(V(μi)g′(μi)2)W_{ii} = w_i/(V(\mu_i)g'(\mu_i)^2), and with canonical link coincides with Newton's step.
0
Score is U=1ϕX⊤WD−1(y−μ)\vb{U} = \frac{1}{\phi}\mat{X}\T\mat{W}\mat{D}^{-1}(\vb{y} - \vb{\mu}) with D=diag⁡(μi′)\mat{D} = \diag(\mu_i') and μi′=1/g′(μi)\mu_i' = 1/g'(\mu_i).

Step 1 of 4. What is Fisher information I(β)=E[−∂U/∂β⊤]\mathcal{I}(\vb{\beta}) = \E[-\partial\vb{U}/\partial\vb{\beta}\T]?

CodeDeviance and deviance residuals
Implement desviacion(y, mu, familia, m=None) to return total deviance D=∑imi d(yi,μi)D = \sum_i m_i\, d(y_i, \mu_i), and residuos_desviacion(y, mu, familia, m=None) to return vector sign⁡(yi−μi)mi d(yi,μi)\operatorname{sign}(y_i - \mu_i)\sqrt{m_i\, d(y_i, \mu_i)}. familia is 'poisson' or 'binomial'; for binomial, y is success proportion and m the number of trials (if None, mi=1m_i = 1). Ignore m for Poisson. Use convention 0log⁡0=00\log 0 = 0: with yi=0y_i = 0 or yi=1y_i = 1 no nan should appear.
import numpy as np

def desviacion(y, mu, familia, m=None):
  """Desviación total para 'poisson' o 'binomial' (y = proporción, m = ensayos)."""
  y = np.asarray(y, dtype=float)
  mu = np.asarray(mu, dtype=float)
  # tu código: desviación unidad d(y, mu) de cada familia, ponderada por m
  return 0.0

def residuos_desviacion(y, mu, familia, m=None):
  """sign(y - mu) * sqrt(m * d(y, mu))."""
  y = np.asarray(y, dtype=float)
  return np.zeros_like(y)
Shift+Enter to run

Summary

Key idea
A GLM separates what linear regression mixes: the link makes the mean linear on a suitable scale and the family fixes how variance grows with mean. Fitting is maximum likelihood, and each algorithm step (IRLS) is weighted linear regression on a linearized response.
  • Ingredients. Response from an exponential dispersion family (μ=b′(θ)\mu = b'(\theta), Var⁡(Y)=ϕV(μ)/w\Var(Y) = \phi V(\mu)/w), linear predictor η=x⊤β\eta = \vb{x}\T\vb{\beta} and link g(μ)=ηg(\mu) = \eta. Normal, binomial, Poisson and gamma have V(μ)=1V(\mu) = 1, μ(1−μ)\mu(1 - \mu), μ\mu and μ2\mu^2.
  • Canonical link. θ=η\theta = \eta: sufficient statistic is X⊤W0y\mat{X}\T\mat{W}_0\vb{y}, likelihood equations are X⊤W0(y−μ^)=0\mat{X}\T\mat{W}_0(\vb{y} - \hat{\vb{\mu}}) = \vb{0} and log-likelihood is concave. MLE may not exist (separation).
  • IRLS. Fisher scoring rewritten as weighted least squares of z=η+(y−μ)g′(μ)z = \eta + (y - \mu)g'(\mu) with weights w/(Vg′2)w/(Vg'^2); with canonical link it is Newton and converges quadratically. Asymptotic covariance is ϕ(X⊤W^X)−1\phi(\mat{X}\T\hat{\mat{W}}\mat{X})^{-1}.
  • Deviance. D=2ϕ(ℓsat−ℓ)D = 2\phi(\ell_{\text{sat}} - \ell); differences between nested models are likelihood ratios (χ2\chi^2, or FF with estimated ϕ\phi). Absolute value measures fit only with small dispersion, never binary data.
  • Interpretation. With log link, eβje^{\beta_j} is a rate ratio; with logit, an odds ratio, and probability effect is bounded by βj/4\beta_j/4. Rates with exposure use log⁡t\log t as offset.
  • Overdispersion. Coefficients remain consistent, but Poisson or binomial standard errors are too small by ϕ\sqrt\phi. Detect with X2/(n−p)X^2/(n - p) and correct using quasi-likelihood, negative binomial or sandwich errors.