SStatistics, Built

Stage III · Master's

Part 24 of 65

Generalized Linear Models

Master'sstarts at this level55 min of film14 chaptersprerequisites: Part 14, Part 21, Part 22

How does one theory fit binary, count, positive and ordinal outcomes?

In 1935 Chester Bliss exposes 481 flour beetles to eight doses of carbon disulphide and counts the dead, from 6 of 59 to 60 of 60; his probit, the logit and the complementary log-log all draw a dose-response curve through them, and the last fits best. Nelder and Wedderburn's 1972 theory makes the logistic and Poisson regressions of Part 14 two members of one exponential dispersion family: a variance function, a link, and one algorithm, Fisher scoring written as weighted least squares on a working response. The deviance takes the place of the residual sum of squares, with a chi-squared reference that works for grouped data and is useless for binary data. Then the family is pushed until it gives: separated data send the slope to infinity, the World's doctor visits are overdispersed and full of zeros, and quasi-likelihood, the sandwich and the negative binomial answer in different ways. Tables become log-linear models, ordered categories get proportional odds, and pupils clustered in schools get GEE with a working correlation. The part ends by grading probability forecasts with proper scoring rules.

What you need. The logistic and Poisson regressions of Part 14, and the score identities of Part 22.

Hook
Bliss's beetles, 1935
Mathematics
exponential dispersion families, IRLS, deviance, quasi-likelihood, separation and Firth, GEE, ordinal models
Built
statkit.glm

What you will be able to do

Bachelor's

  • Read a dose-response curve and its LD50, and say why a straight line is the wrong model for a probability.
  • Name the three parts of a GLM for a given outcome: the family, the linear predictor and the link.

Master's

  • Put a distribution in exponential dispersion form and read off its mean, variance function and canonical link.
  • Derive IRLS from Fisher scoring and implement it for any family and link.
  • Compare nested GLMs by analysis of deviance, and choose between quasi-Poisson, sandwich and negative-binomial answers to overdispersion.

PhD

  • State when the deviance has a chi-squared limit and prove why it cannot for binary data; give the null law of the likelihood-ratio test for overdispersion on the boundary.
  • State what GEE estimates when the working correlation is wrong, and what changes when the mean model is wrong as well.

Practice

  • Diagnose separation from an IRLS path and report a Firth estimate in place of a diverging one.
  • Grade probability forecasts with a proper scoring rule and a calibration plot, not with accuracy.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 9 min · Master's 50 min · PhD 55 min · Practice 17 min.

  1. 0Bliss's beetles, 1935Bachelor's3 min
  2. 1Upgrade: what Part 14 fittedBachelor's3 min
  3. 2The exponential dispersion familyMaster's5 min
  4. 3IRLS derivedMaster's3 min
  5. 4DevianceMaster's5 min
  6. 5Asymptotics for GLMsPhD5 min
  7. 6SeparationPractice4 min
  8. 7Quasi-likelihoodMaster's3 min
  9. 8CountsMaster's4 min
  10. 9Log-linear modelsMaster's4 min
  11. 10Multinomial and ordinalMaster's3 min
  12. 11GEEMaster's4 min
  13. 12Proper scoring rulesPractice4 min
  14. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Bliss's beetles, 1935Bachelor's3 min

In 1935 the entomologist Chester Bliss published a paper on the calculation of the dosage-mortality curve. He had exposed flour beetles for five hours to carbon disulphide gas at eight concentrations and counted the dead. How lethal is each dose, and what dose kills half the beetles? Each beetle's outcome is yes or no, and a straight line through such data would predict probabilities below zero and above one.

Here are Bliss's data as they appear in Annette Dobson's textbook: eight doses, about sixty beetles at each, four hundred and eighty-one in all. At the lowest dose six of fifty-nine died; at the highest, all sixty. Each dot is a proportion killed, with a bar for its binomial uncertainty. The proportions climb in an S.

Bliss's idea: each beetle has its own tolerance, normally distributed on the log-dose scale, and dies if the dose exceeds it. Then the death rate is the normal distribution function of a straight line in the log dose. He called the normal deviate plus five a probit, the five keeping hand calculations free of minus signs. He fitted straight lines through the probits, weighted them, recalculated, and fitted again. In an appendix to the paper, Ronald Fisher showed that the weighted iterations solve the maximum-likelihood score equations under suitable convergence conditions. It was iteratively reweighted least squares, thirty-seven years before it had that name.

Fit three S-shaped curves by maximum likelihood. The logistic, Part 14's model, has deviance eleven point two three. Bliss's probit is barely different, ten point one two. The complementary log-log, which is not symmetric, rising slowly and then steeply, has deviance three point four five. With six residual degrees of freedom, the symmetric curves have lower goodness-of-fit tail probabilities, though neither is rejected at five percent. The asymmetric link has the smallest deviance among these candidates: the beetles at the top die faster than a symmetric curve allows. Chapter four makes the deviance precise.

The quantity of interest is the dose that kills half, the LD fifty. Under the complementary log-log fit it is a log dose of one point seven seven nine, about sixty milligrams per litre. It's a ratio of coefficients, so Part 11's Fieller interval applies: one point seven seven oh to one point seven eight six. The logistic fit puts it at one point seven seven two, near the bottom of that interval: the choice of link moves the answer by about as much as the sampling error does. That's the question of this part: how to choose among models for outcomes that aren't normal, fit them all with one algorithm, and judge them.

Numbers: deviances 11.23 / 10.12 / 3.45; LD50 1.7788 [1.7702, 1.7862]

1Upgrade: what Part 14 fittedBachelor's3 min

Part 14 fitted logistic regression for yes-or-no outcomes and Poisson regression for counts, and promised that the algorithm behind both, iteratively reweighted least squares, would be explained later. It treated them as two separate models, each with its natural link, with a variance fixed by the mean, and with independent units. John Nelder and Robert Wedderburn showed in 1972 that they are members of one family, fitted by one algorithm. This part builds that family and pushes it in every direction.

A generalized linear model has three parts. A random part: each outcome comes from a distribution in the exponential family, with mean mu i. A systematic part: a linear predictor eta i, a linear combination of the covariates, exactly as in Part 23. And a link function that connects them: g of the mean equals the linear predictor. Normal errors with the identity link is ordinary regression; binomial with the logit is logistic regression; Poisson with the log is Poisson regression. Bliss's model is binomial with the probit link.

Why not just run least squares on the zeros and ones? That's the linear probability model, still common in economics, and with Part 23's robust standard errors it can support inference for a best linear approximation under appropriate sampling, moment and leverage conditions. But its fitted probabilities leave zero to one at the edges, as a straight line through Bliss's beetles would above the highest doses. Its errors are heteroskedastic by construction, since a yes-or-no outcome has variance p times one minus p. And an effect cannot be the same size everywhere on a bounded scale: a dose that adds thirty points to a ten percent death rate cannot add thirty to ninety. The link moves the model to a scale where constant effects make sense.

The recipe this part follows. Choose the family from what kind of number the outcome is: a proportion, a count, a positive amount. Choose the link from the scale on which effects should add up: odds, rates, or the mean itself. Fit by IRLS and check the fit with the deviance and residuals. If the variance assumed by the family is wrong, use quasi-likelihood or the sandwich of Parts 22 and 23. And if units come in clusters, use generalized estimating equations, or wait for Part 25's mixed models.

Numbers: the three parts; the linear probability model

2The exponential dispersion familyMaster's5 min

Every distribution in the family has a density of one form: the exponential of y times a canonical parameter theta, minus a function b of theta, all over a dispersion phi divided by a weight, plus a term that doesn't involve theta. Write the Poisson's log probability as y log mu minus mu minus log y factorial, and read off: theta is log mu, b is e to the theta, and the dispersion is one. For a binomial proportion, theta is the log odds and the weight is the number of trials. For the normal, theta is the mean itself and the dispersion is the variance.

Why this form? Take one observation with unit prior weight, and omit terms constant in theta. Part 22's first identity, that the score has mean zero, says the mean of y is b prime of theta. The second identity, that the score's variance is minus the expected curvature, says the variance of y is phi times b double prime. Written as a function of the mean, that's phi times V of mu. The variance function V is the family's fingerprint: mu for the Poisson, mu times one minus mu for the binomial, one for the normal, mu squared for the gamma. Chapter seven will keep only the variance function and drop the rest.

The common members. The normal, for any real outcome, with constant variance. The binomial, for proportions, the Poisson, for counts. The gamma, for positive amounts whose standard deviation grows in proportion to the mean: waiting times, insurance claims, rainfall. And the inverse Gaussian, for positive amounts whose variance is proportional to the cube of the mean. Relative skewness also depends on dispersion. Each has a canonical link, one that makes the linear predictor equal theta, up to a fixed rescaling or sign convention in commonly named inverse links.

An example of the gamma. Model the mean income of fifteen hundred of the World's working adults with a log link and gamma errors. Each decade of age multiplies the mean by one point one one seven, with a dispersion of point eight six, a coefficient of variation of about point nine three. The usual alternative, least squares on log income, gives point one oh oh per decade. They answer different questions: the gamma model describes the log of the mean income, the log-normal regression the mean of the log, which determines the median only under an appropriate symmetric log-error model. By Jensen's inequality from Part 21 they are distinct targets. A changing conditional distribution can also change their age slopes; Jensen alone does not quantify that difference.

Maurice Tweedie noticed in 1984 that the table's variance functions are powers of the mean. Power zero is the normal, one the Poisson, two the gamma, three the inverse Gaussian. Powers between one and two give something new: a Poisson number of gamma-sized amounts. That has an exact zero when the Poisson count is zero, plus a skewed continuous part, which is precisely what a year of insurance claims looks like: most policies claim nothing, and a few claim a lot. Actuaries fit it as a GLM.

For a probability, an inverse link maps the real linear predictor into zero to one; the link itself goes the other way. The logit makes effects additive on the log-odds scale, the canonical choice. The probit corresponds to a normal tolerance, as Bliss argued. The complementary log-log is asymmetric: it approaches one much faster than it leaves zero, which is what you get if death comes from the first of many independent hits, and why it suits Bliss's beetles. The probit is steeper, but stretch it by about one point seven and it is almost indistinguishable from the logit; only data in the tails, or lots of data, can tell them apart.

The canonical link is special. With it, the linear predictor is the canonical parameter itself, and the score equations become the sum of covariates times residuals equals zero, the same form as least squares' normal equations. With known dispersion and fixed prior weights, the weighted predictor-response sum is sufficient for beta. For binomial proportions, trials must enter those weights. And the observed and expected information coincide, so Newton's method and Fisher scoring are the same, as Part 22 noted. Other links lose these conveniences, but often fit better, as the beetles showed.

Numbers: gamma ×1.117 per decade, φ̂ 0.86; log-normal 0.100

3IRLS derivedMaster's3 min

Iteratively reweighted least squares, derived. The score of a generalized linear model follows from the chain rule: residuals, divided by the variance, times the slope of the inverse link, times the covariates. The expected information is X transpose W X over phi, with working weights equal to prior weight times that slope squared over the variance function. For grouped proportions the prior weight is the number of trials. A Fisher scoring step, beta plus the inverse information times the score, rearranges into a weighted least squares fit, of a working response z: the current linear predictor plus the residual stretched back onto the linear-predictor scale. Every step is Part 23's weighted least squares; only the weights and the working response change.

Watch it on Bliss's beetles with the logit link, starting from all coefficients zero, so every fitted probability is one half. The working response is the observed proportion minus a half, divided by a quarter. The weights are the number of beetles times a quarter, nearly equal here. A weighted straight line through those points gives the first step's coefficients, a slope of twenty-one point three.

Recompute the weights and working response at the new fit, and fit again. The first curve is far too shallow. The second is closer, the second brings deviance near thirteen, down from the starting three hundred and six; the first update had brought it to about thirty-nine. By the fourth step the coefficients have three correct digits, and the displayed stopping iteration meets our coefficient-change tolerance. For this canonical-link fit, local Newton convergence is quadratic; the tolerance is not machine precision.

The deviance, which chapter four defines properly, falls at every step from three hundred and six to its minimum, eleven point two three. Far from the answer a full Newton step can overshoot, so the software halves the step until the deviance stops rising, the line search of Part 21. Minimizing the deviance is maximizing the likelihood.

One subtlety. With a canonical link, the weights are both the observed and the expected curvature. With the probit or the complementary log-log, IRLS uses the expected information: Fisher scoring, whose weights are always positive. Newton's method would use the observed curvature, taking different steps, which can reach the same finite maximum when both methods converge appropriately. The two give slightly different standard errors, the observed against the expected information, Part 22's chapter four; software usually reports the expected.

Each step costs one weighted least squares fit, using a stable weighted QR solve as in Part 23. Well-behaved examples often need only a few steps. Noncanonical Fisher scoring need not have quadratic convergence. Software starts not from zero but from the data, nudged away from zero and one, which saves steps. And the standard errors use the final information matrix: the inverse of X transpose W X at the last step, times the dispersion. Bliss computed all this by hand in 1935; R's glm runs this same loop.

Numbers: slope 21.3 → 34.27 in 7 steps; deviance 306 → 11.23

4DevianceMaster's5 min

The saturated model gives every observation its own parameter, so it fits each observed mean, sometimes as a boundary limit rather than at a finite natural parameter. The deviance is twice the gap in log likelihood between the saturated model and ours, scaled by the dispersion: a sum of one piece per observation, the unit deviances. For normal errors it is exactly the residual sum of squares, so the deviance is least squares' yardstick generalized. For the Poisson it's twice the sum of y log y over mu hat, minus the residuals.

Bliss's beetles, with the three links. With grouped data and around sixty beetles per dose, the deviance of a correct model is approximately chi-squared with eight minus two, six, degrees of freedom. The logit's eleven point two has a tail probability of point oh eight; the probit's, point one two; the complementary log-log's three point four five, point seven five. The Akaike criteria agree: the asymmetric link has the lowest AIC by about eight units against the logit, among these three fits. Part 28 explains what such a difference means.

The deviance also compares nested models, like Part 23's residual sums of squares. Two thousand of the World's adults, and the number of times each saw a doctor last year. Add terms one at a time to a Poisson regression. Age cuts the deviance by seven hundred and fifty-four, body mass by three hundred, a diagnosis of high blood pressure by two hundred and fifty-seven, sex by sixty-eight. But the final deviance is nearly six thousand on two thousand degrees of freedom, three times what a Poisson model allows. An approximate quasi-Poisson calculation divides each drop by the estimated dispersion, three point three six. This is a working variance assumption, not an exact F test; chapter seven checks it against a robust sandwich.

That table was sequential: each drop is the contribution of a term given the ones above it. Order matters when predictors are correlated; age and a high blood pressure diagnosis overlap, so whichever enters first collects the shared part. Dropping each term from the full model instead asks what it adds given everything else. Under a correctly specified likelihood, both are nested-model comparisons with the appropriate likelihood-ratio reference; they answer different questions, so say which one you report.

Residuals come in several kinds. The unscaled Pearson residual divides the observed discrepancy by the square root of the variance function and includes prior trial weights. Dispersion is handled separately; their squares add up to Pearson's chi-squared. Deviance residuals take the square root of each unit deviance, with a sign; their squares add up to the deviance. For counts and binary outcomes, neither looks normal, even when the model is right. Peter Dunn and Gordon Smyth's randomized quantile residuals fix that: find where the observation sits in its fitted distribution, spread that point uniformly across the jump of a discrete distribution, and map it through the inverse normal. With the true CDF known, independent randomized probability transforms are exactly normal. Plugging in fitted parameters changes their dependence and finite-sample distribution: the QQ plot is a diagnostic, not an exact normality test.

For binary outcomes even quantile residuals are noisy, and raw residuals form two bands that can be hard to read. The practical fix is to bin: sort observations by fitted probability, and average the residuals within each bin. David Hosmer and Stanley Lemeshow turned the same idea into a chi-squared test over deciles of predicted risk. And the picture behind both, observed rate against predicted, is the calibration plot of chapter twelve.

Here they are for the doctor visits. Under the Poisson model the quantile residuals bend into an S with tails far too long: the counts are much more spread out than the Poisson allows. Under a negative binomial model, chapter eight's, they lie much closer to the line. This supports a better distributional approximation; it does not prove that the negative binomial is the generating mechanism.

Numbers: drops 754 / 299 / 257 / 68; φ̂ 3.36

5Asymptotics for GLMsPhD5 min

Part 22's regular likelihood results apply with identifiability, a finite interior estimate, suitable design and moment conditions. The estimates are approximately normal, with covariance phi times X transpose W X inverse, the last IRLS step's weights. For the beetles' complementary log-log slope that's twenty-two plus or minus about three and a half. With dispersion one, the likelihood-ratio statistic is a drop in deviance, chi-squared with as many degrees of freedom as terms removed. And the score test needs only the smaller model, which makes it the cheap way to screen many candidate terms.

When the dispersion is unknown, estimate it from the Pearson residuals, like s squared in least squares. Then a drop in deviance per term, divided by that estimate, is often compared approximately with an F distribution; the ordinary Gaussian linear-model case has the exact F reference, as in the analysis of deviance we just did. For the gamma and the normal, the dispersion is usually estimated unless supplied externally. For the binomial and the Poisson it's assumed to be one, and the assumption is worth checking: an estimate well above one means overdispersion.

Functions of the coefficients need the same care as in Part 11. The LD fifty is a ratio. The delta method gives a symmetric interval, the estimate plus or minus about point oh oh eight. Fieller's method inverts a test of the ratio directly; for the beetles the two agree to the third decimal, because the slope is estimated very precisely. When the slope is close to zero they part company: Fieller's asymptotic confidence set can be unbounded, including two disjoint rays or the whole line, which is the honest answer when the data can't locate the dose at all.

But the deviance as a test of fit needs care. Simulate two thousand Bliss experiments, same doses and numbers of beetles, from a logistic model that is exactly right. Refit each. The deviances follow chi-squared with six degrees of freedom, and the test rejects six percent of the time. With about sixty beetles per dose, the approximation works.

Now ungrouped data: two hundred people, one yes-or-no outcome each, again from a correct logistic model. The textbook would compare the deviance with chi-squared on a hundred and ninety-eight degrees of freedom. The actual distribution is centred at two hundred and thirty-five with a standard deviation of twelve, much narrower than the chi-squared's twenty, and in the wrong place. Used as a test of fit, it would reject this correct model sixty-three percent of the time. The reason: the saturated model's number of parameters grows with the sample, the Neyman–Scott situation of Part 22. For binary data, fixed-dimensional regular nested-model deviance differences can still have a Wilks reference. Comparing deviance with a growing saturated model does not give a general chi-squared goodness-of-fit test; Hosmer and Lemeshow's grouping, or calibration plots, check fit instead.

Overdispersion can be tested. Under the Poisson the variance equals the mean; the alternative adds alpha times mu squared. Colin Cameron and Pravin Trivedi's score test needs only the Poisson fit: the displayed standardized NB2 score sums squared residuals minus observed counts, with its Poisson-null information scale. It is a one-sided test for positive overdispersion under regularity conditions. The likelihood-ratio test of Poisson against negative binomial puts alpha equal to zero on the edge of its range, in this single-boundary-parameter setting, regular Poisson-null asymptotics give half a point mass at zero and half a chi-squared with one degree of freedom. Other boundary problems can have different limits. For the visits the statistic is nineteen hundred: overwhelming.

So: under regular, correctly specified models with dispersion one, fixed-dimensional nested deviance differences are asymptotically chi-squared. Separation, boundary parameters and misspecification can invalidate that reference. The deviance alone, as a test of fit, can have a useful chi-squared approximation for well-populated groups. Other goodness-of-fit methods and parametric bootstrap calibration remain possible. For intervals, Part 22's profile likelihood beats the Wald interval when probabilities are near zero or one. And in small samples, suitable exact conditional methods, where available, or a plug-in parametric bootstrap can improve calibration. A parametric bootstrap is itself an approximation.

Numbers: grouped 6.0%; binary 63% false rejections; LR for overdispersion 1,924

6SeparationPractice4 min

Twelve observations. Every one with x below zero is a zero, and every one above is a one. A vertical line separates the two outcomes perfectly. A logistic curve fits better the steeper it gets: each steeper curve gives every point a probability closer to its outcome. There is no best curve. The likelihood supremum is approached as the slope diverges; there is no finite maximum-likelihood estimate.

Run IRLS anyway. The slope grows by five every step, a hundred and eight after twenty-five steps, and would keep going. The log likelihood creeps up towards zero, its ceiling, without reaching it. Software stops at its iteration limit and prints a warning that fitted probabilities of zero or one occurred. The standard error it reports is enormous, so the Wald test, Part 22's Hauck–Donner effect at its extreme, says the strongest possible effect is not significant.

Adelin Albert and John Anderson characterized it in 1984. Complete separation means some direction in coefficient space puts every one on one side and every zero on the other. Scaling that direction up sends every fitted probability towards its own outcome, and the log likelihood up towards zero. Quasi-complete separation, with some ties on the boundary, sends just some coefficients to infinity. It happens far more often than one might hope: small samples, rare outcomes, many predictors, or a category in which everyone responded.

David Firth's cure, from 1993, adds half the log determinant of the information to the log likelihood. That's the logarithm of Jeffreys's prior from Part 22, used as a penalty. In the score equations it amounts to adding, for each observation, a fraction of a pseudo-observation split between the two outcomes, which penalizes collapse of the information. For full-rank logistic designs this yields finite fitted coefficients even under separation. For our twelve points the slope is now finite, two point five five. Firth designed it to remove the leading term of the bias of maximum likelihood, which it also does when there is no separation; that it tames separation was a happy bonus.

A milder relative of separation is rarity. With few ones, maximum likelihood can have substantial finite-sample bias, as Gary King and Langche Zeng showed for rare political events. Information can be limited by the number of events. The usual fixed-prevalence bias order is still one over sample size, with constants that can worsen as events become rarer: a million people with fifty cases is a small sample. Firth's correction helps here too. The flip side: for rare outcomes you can sample the cases heavily, a case–control design, and under a correct logistic model with sampling depending only on outcome, logistic slopes remain valid, as Prentice and Pyke established. If cases and controls have selection probabilities s one and s zero, the sample intercept equals the population intercept plus log of s one over s zero.

Separation is fragile. Move just two of the twelve points across the line and the maximum likelihood estimate exists, a slope of three point four five with a sizeable standard error. When it does happen, use Firth's estimate, profile-likelihood intervals, which can be unbounded on one side, or exact conditional methods. A weakly informative prior, Part 26, works too. What not to do is drop the variable because its standard error looked huge: it is the strongest predictor in the data.

Numbers: slope → 108; Firth 2.55 (1.46)

7Quasi-likelihoodMaster's3 min

A Poisson model ties the variance to the mean. The World's doctor visits have a mean of two point one three and a variance of ten point three, five times as big before adjusting for covariates. Variation in conditional means can cause this even with conditionally Poisson data; the adjusted Pearson dispersion supplies further evidence here. Counts are usually overdispersed like this: people differ in ways the covariates don't capture, one event makes another likelier, events cluster. As Part 22 found, with a correct conditional log-mean model, Poisson estimates can remain consistent while model-based standard errors fail. A wrong mean needs attention too.

Robert Wedderburn's 1974 quasi-likelihood, which Part 22 met briefly, assumes only a mean model and a variance that is phi times a known function of the mean. The integral of the standardized residual behaves just like a log likelihood: its derivative has mean zero, and its variance equals minus its expected curvature. Maximizing it gives exactly the GLM score equations, so the same IRLS, the same estimates. Only the covariance changes: multiply by the estimated dispersion.

The doctor visits, four covariates. The Poisson model's standard errors, then quasi-Poisson's, all multiplied by the square root of three point three six, one point eight three. The sandwich's are similar but not uniformly scaled: the diagnosis of high blood pressure gets the biggest increase. A negative binomial model, chapter eight, gives almost the same coefficients with standard errors close to the sandwich's.

But quasi-Poisson makes an assumption of its own: the variance is a constant multiple of the mean. Heterogeneity between people produces something else, the negative binomial's mu plus mu squared over k, which grows faster for large means. The two weight the observations differently, quasi-Poisson assigning greater working weight to observations with large fitted means, as Jay Ver Hoef and Peter Boveng pointed out. The sandwich assumes no variance shape at all.

Proportions can be overdispersed too. If each batch of beetles had its own death rate, drawn from a beta distribution, counts would follow a beta-binomial, with the binomial variance inflated by one plus n minus one times an intraclass correlation. Bliss's beetles under the logit link give a Pearson dispersion of one point six seven, apparently overdispersed. Under the complementary log-log it's point five five. The estimated dispersion changes greatly with the fitted mean curve. Eight grouped observations do not establish which mechanism produced the discrepancy. A misspecified mean shows up as overdispersion, so fix the mean before reaching for the variance.

The Board: a thousand samples of five hundred adults, and the coefficient on a diagnosis of high blood pressure. The target is the World's own Poisson fit, the projection of Part 22. Poisson standard errors cover it sixty-four percent of the time: broken. Quasi-Poisson: ninety, closer but still broken, where a constant-multiple variance model is only an approximation and finite-sample effects can also matter. The sandwich: ninety-four, kept.

Numbers: ×1.83; Bliss φ̂ 1.67 vs 0.55; Board 63.5 / 89.5 / 94.4%

8CountsMaster's4 min

Counts: overdispersion and too many zeros. Where does overdispersion come from? Suppose each person has their own rate: the model's mean times a gamma-distributed frailty with mean one. Given the rate, the count is Poisson. Averaged over the frailty, the count is negative binomial, with variance mu plus mu squared over k. Major Greenwood and Udny Yule derived it in 1920 to describe accident-prone factory workers. As k grows the frailty disappears and the Poisson returns. With k fixed it's a generalized linear model; in practice we alternate IRLS for the coefficients with a scalar numerical optimization for k, checking the fitted likelihood.

First, an essential tool for any count. Counts usually accumulate over some exposure: person-years of follow-up, a town's population, kilometres of road. The mean is the exposure times a rate. With a log link that becomes the log exposure plus the linear predictor. The log exposure enters as an offset, a column whose coefficient is fixed at one, as in Part 14's study of smoking doctors. Every other coefficient then exponentiates to a rate ratio, per unit of exposure.

The World's two thousand adults: forty percent saw no doctor last year. The Poisson regression, with all four covariates, expects only nineteen percent zeros. It also expects too many people with one or two visits and almost nobody with ten. The negative binomial, with k estimated at point eight two, expects thirty-nine percent zeros and approximates the displayed shape much better. Counts above twelve remain in the fit but are outside this viewport.

Excess zeros have a second explanation: some people never go. Diane Lambert's zero-inflated Poisson, from 1992, mixes a share pi of structural zeros with a Poisson for everyone else. It is fitted by Part 22's EM algorithm: the missing information is whether each zero is structural. John Mullahy's hurdle model instead separates the decision from the amount: a logistic regression for whether there are any visits, and a zero-truncated Poisson for how many. Zero inflation says there are two kinds of zero; a hurdle says there's one gate to pass.

Fit all four to the same visits. The Poisson's log likelihood is minus four thousand six hundred and eighty-two. Zero inflation helps a lot, estimating a structural-zero mixture weight of thirty-five percent under that model, not identifying which adults can never attend; the hurdle helps a little more. But the negative binomial has the best AIC among these four candidates, by about seven hundred in AIC: inflating the zeros cannot create the long right tail, which needs people with high rates.

A reassuring fact behind chapter seven's Board. The Poisson score equations involve only the mean. So the Poisson estimates are consistent under a correct log-linear conditional mean, suitable sampling and finite moments, with identifiable coefficients and a finite solution, even when the Poisson variance and distribution are wrong, as Christian Gourieroux, Alain Monfort and Alain Trognon proved in 1984. It even works for continuous non-negative outcomes: economists fit international trade flows this way, Poisson pseudo-maximum likelihood, keeping zeros and targeting the arithmetic conditional mean. Regression on logged positive outcomes answers a different question. Paired with the sandwich, it is one of the most robust tools in this part.

Here's the advantage of a World whose truth we know. It was built with about fifteen percent never-goers, who stay at zero, and a negative binomial with k equal to one point two for everyone else. So the truth is a zero-inflated negative binomial, both stories at once. The plain negative binomial fits well by pretending the heterogeneity is larger than it is, k of point eight two instead of one point two, so that its spread covers the extra zeros. The model that fits best need not be the mechanism that made the data. Part 28 takes up how to choose.

Numbers: zeros 40% vs 19% vs 39%; AIC 9,375 / 8,248 / 8,171 / 7,453; k̂ 0.82 vs 1.2

9Log-linear modelsMaster's4 min

A three-way table from the World: five thousand adults, classified by sex, age group, and whether a doctor has told them they have high blood pressure. Among men, eight, seventeen and forty-four percent have been told, by age group; among women, four, nine and forty-two. With three variables there are many possible associations. Which are real, and which follow from the others?

Treat each cell count as a Poisson count. Model its log mean with main effects and interactions, like an analysis of variance on the log scale: this is a log-linear model, a Poisson GLM whose design matrix is built from the table's margins. Specific collections of absent interactions encode independence. Omitting one higher-order interaction need not imply any conditional independence. The model with only the sex-by-age and age-by-told interactions, written S A, A T, says that being told is independent of sex once age is known: conditional independence.

Fit a ladder of models. Being told independent of both age and sex: deviance eight hundred on five degrees of freedom, hopeless. Told independent of sex given age: thirty-nine on three, still rejected, so sex matters even within age groups. All three two-way associations but no three-way interaction: sixteen on two, p of point oh oo three, also rejected. Only the saturated model fits. The difference between men and women depends on age, which is how the World was built: women's blood pressure is lower until about sixty, and then the gap closes.

The interaction terms are log odds ratios. In the model without a three-way term, the sex-by-told term is a common odds ratio across age groups, point six eight: women are less often told, at any given age. It is a homogeneous-association likelihood estimate, related to but not generally identical to Mantel–Haenszel's ratio-of-sums estimate. This common-odds model was rejected here, so its estimate is only a summary of varying age-group associations. Log-linear models also say when it is safe to collapse a table over a variable, the question behind Simpson's paradox. They're fitted by IRLS, or by iterative proportional fitting, which is Part 18's raking applied to model margins.

Log-linear models have pictures. For a graphical log-linear model, draw one node per variable and include all interactions within each maximal clique. If every path between two variables passes through a third, they're conditionally independent given it: the model S A, A T is a chain with age in the middle. Graphical models are a subset of hierarchical models. The all-pairs, no-three-way model on three variables is hierarchical but not graphical: its complete graph would also require the three-way interaction. For positive model cell probabilities, graph separation gives conditional independences. Sparse graphs restrict clique interactions, the starting point of graphical models, which Part 31 develops for continuous data.

When one variable is naturally the response, being told, a log-linear model that includes every interaction among the predictors is the same as a logistic regression of the response on them. With the required saturated predictor margins or stratum-specific nuisance intercepts, Poisson and conditional multinomial likelihoods give the same response-association estimates. That's the Poisson trick, and it's how the next chapter's multinomial models can be fitted with ordinary Poisson software.

Numbers: 798 / 39.1 / 16.4; OR 0.68

10Multinomial and ordinalMaster's3 min

With more than two unordered outcomes, the multinomial logit gives each category its own linear predictor and turns them into probabilities with the softmax, one category serving as the baseline. Each coefficient vector is a log odds of that category against the baseline. With K categories and p covariates there are K minus one times p coefficients, which adds up quickly. And it assumes the independence of irrelevant alternatives: the odds of choosing the car over the red bus don't change when a blue bus, identical but for colour, is added. Daniel McFadden's famous example shows how odd that can be.

When categories are ordered, underweight, normal, overweight, obese, use the order. Imagine a continuous latent scale, a linear predictor plus logistic noise, chopped into categories by cut-points. Then the log odds of being at or below category j is theta j minus x transpose beta: Peter McCullagh's proportional-odds model, from 1980. A single coefficient vector serves every cut-point, so each covariate has one odds ratio, whichever way the categories are split.

Three thousand of the World's adults, classified by body mass index: eighty-two underweight, a thousand normal, a thousand and forty-five overweight, eight hundred and seventy-three obese. In the proportional-odds model, ten years of age move the latent scale up by point one seven three. So the odds of being in a heavier category, at any cut, are one point one nine times higher per decade. The fitted sex coefficient is compatible with zero. The World's BMI generator has no direct sex term, but a finite fitted coefficient need not be exactly zero.

Here are the fitted probabilities of the four categories across age, stacked. As the latent scale moves up with age, probability flows from underweight and normal into overweight and obese, all governed by one coefficient.

Is one coefficient enough? Fit a separate logistic regression at each cut: underweight against the rest, normal or less against overweight or more, and so on. Under proportional odds the population slopes would agree, while fitted slopes still vary with sampling noise. They don't quite: at the bottom cut the age slope is point three one, nearly twice the others, suggesting a possible difference at that cut. The underweight group is small, and correlated estimation uncertainty must be considered before declaring nonproportionality. A partial proportional-odds model lets that one slope differ; or fall back on the multinomial, at the price of many more parameters.

The cumulative logit is one of several ordinal models. Adjacent-category logits compare each category with the next. Continuation ratios model the chance of going beyond a category given that you reached it, natural for stages passed in order, like school grades or survival through intervals. And the latent noise need not be logistic: a probit gives the ordered probit, and a complementary log-log gives a grouped version of Part 40's proportional-hazards model.

Numbers: 0.173 per decade (OR 1.19); cut slopes 0.31 / 0.18 / 0.15

11GEEMaster's4 min

Part 23's schools again, with a yes-or-no outcome: did the pupil score above five hundred and fifty? Thirty-two percent did, in a sample of forty schools. A logistic regression on the tutoring programme and home background. Fitted as if every pupil were independent, the programme's coefficient has a standard error of point oh nine four. But pupils in the same school share teachers, intake, and the programme itself, so as Part 23 showed for least squares, that standard error is too small.

Kung-Yee Liang and Scott Zeger's generalized estimating equations, from 1986, write a GLM score cluster by cluster: derivatives of the mean, times an inverse covariance, times the residuals. The covariance is a working guess: the binomial variances combined with a working correlation within each cluster, independence, exchangeable, autoregressive or unstructured. The standard errors come from a sandwich that sums each cluster's residual products, Part 23's cluster-robust idea. With a correct mean conditional on the relevant cluster covariates, independent clusters, adequate moments and a regular design, the estimates can remain consistent when the working correlation is wrong. The sandwich then provides asymptotic uncertainty; few clusters need care.

Three fits. GEE with an independence working correlation reproduces the logistic estimate exactly, point four five three, but its robust standard error is point two two eight, two point four times the naive one. With an exchangeable correlation, estimated at point oh nine between pupils of one school, the estimate moves to point four oh five and the model-based and robust errors agree, though agreement in one sample does not establish that the correlation model is correct. The census independence-logistic projection is point three nine two; the census exchangeable estimating-equation target is point three seven eight. They differ slightly because this logistic mean is an approximation. The coverage study uses each procedure's own census target.

GEE estimates a marginal, population-averaged effect: a population-averaged mean-model coefficient. Reading it as the effect of adopting a programme additionally needs a suitable causal design. A mixed model, Part 25, estimates a conditional effect: the change within one school, holding its own effect fixed. For a logistic link they differ: averaging over school effects flattens the curve, so the marginal coefficient is smaller, roughly the conditional one divided by the square root of one plus point three four six times the school-effect variance, as Scott Zeger, Kung-Yee Liang and Paul Albert showed. Neither is wrong. A minister choosing a policy wants the first; a head teacher wants the second. With an identity link and an independent mean-zero random intercept, the marginal and conditional slopes coincide. Some other links also preserve slopes under particular random-effect models; coincidence is not exclusive to linear models.

How much does the working correlation matter? If it's right, GEE is efficient, like generalized least squares, and the model-based and robust standard errors agree, as they did here. With an incorrect working correlation, consistency still needs the correct relevant conditional mean, cluster independence and suitable regularity. Under mean misspecification, changing the working correlation can change the target. With few clusters the sandwich often underestimates uncertainty, the few-cluster problem of Part 23; Lloyd Mancl and Timothy DeRouen's correction helps. And with covariates that change over time, a non-independence working correlation can bias the estimates unless the model conditions on everything that matters, as Margaret Pepe and Garnet Anderson showed.

The Board: five hundred samples of forty schools, against the corresponding census estimating-equation target for each working correlation. Logistic regression with the iid standard error: fifty-five percent, broken. GEE with independence and the robust standard error: ninety-five, kept. GEE with an exchangeable working correlation: about ninety-six, kept.

Numbers: SE 0.094 vs 0.228; α̂ 0.089; truth 0.392; Board 54.8 / 95.0 / 95.8% (method-specific census targets)

12Proper scoring rulesPractice4 min

Every model in this part predicts a probability or a whole distribution. How should such a forecast be graded once we see what happened? A scoring rule assigns a penalty to each forecast and outcome. It is proper if a forecaster who believes the true probability is p does best, on average, by reporting exactly p. An improper score rewards forecasters for shading their beliefs, which is the last thing we want from a model or a weather forecaster. Tilmann Gneiting and Adrian Raftery set out the theory in 2007.

Suppose the truth is a thirty percent chance. The log score, minus the log of the probability given to what happened, is smallest on average when the forecast is exactly point three. So is Glenn Brier's squared error, from weather forecasting in 1950. But the absolute error is smallest at zero: it tells the forecaster to round every probability to zero or one. It is improper, and so is plain accuracy.

A real comparison. Fit a logistic model for being told one has high blood pressure, using age, body mass and sex, and score its forecasts on two thousand new adults. The fitted logistic reference model wins on both proper scores in this holdout. We have not assumed its probabilities are exactly calibrated. An overconfident version, the same model with its log odds doubled around the average, is worse on both, and the forecaster who always says the base rate, seventeen percent, is worst. But accuracy, the share of forecasts on the right side of a half, puts the base rate above the overconfident model, because it only looks at which side of a half each forecast falls. Accuracy throws the probability away.

Here is why. Sort the new adults into ten groups by predicted risk and plot the observed rate in each against the average prediction. The logistic model's binned points are reasonably close to the diagonal, with sampling uncertainty. The overconfident model's run too flat: where it says eighty-six percent, fifty-four percent have actually been told. Yet it ranks people in exactly the same order, so its ROC curve and AUC are identical. AUC alone cannot distinguish these probability scales; proper scores and calibration diagnostics can.

For a whole predictive distribution, the continuous ranked probability score integrates the squared gap between the forecast's distribution function and the step at the outcome. For a normal forecast it has a closed form. When the truth is standard normal, in a shared simulation of twenty thousand outcomes, the honest forecast scores about point five six; one twice too narrow scores point six oh; one twice too wide, point six five. Both are penalized. It is in the units of the outcome, and for a point forecast it reduces to the absolute error.

Murphy's Brier decomposition separates reliability minus resolution plus outcome uncertainty. In the population, define calibration as the conditional event probability given the reported forecast. Reliability is the mean squared gap between that conditional probability and the forecast. Resolution is the variance of those conditional event probabilities. It measures predictive information and is not numerically the same as AUC. With finite arbitrary bins, an exact sample decomposition needs forecasts constant within bins or an additional within-bin term. The log score's expected excess over reporting the true probability is the Kullback--Leibler divergence; the total expected loss also includes the entropy of the truth.

So compare probability forecasts with proper scores. The mean negative log score is the negative average log likelihood on new data, which ties forecasting back to everything in Parts 22 to 24. Accuracy and the area under the ROC curve ignore calibration, so pair them with a calibration plot. And turning a probability into a decision needs the costs of each mistake, Part 19's thresholds.

Numbers: log 0.373 / 0.438 / 0.463; says 86%, sees 54%; CRPS 0.560 / 0.604 / 0.653

Recap, problems, and the road aheadAll tracks3 min

Part twenty-four in fourteen lines. Bliss's probits fitted the beetles; the asymmetric complementary log-log fitted them best. A generalized linear model has a family, a linear predictor and a link. The exponential dispersion family is defined by its canonical parameter, its cumulant function and its variance function. IRLS is Fisher scoring written as weighted least squares, seven steps for the beetles. The deviance and quantile residuals judge fit; for binary data the deviance alone raised false alarms sixty-three percent of the time. Separation sends coefficients to infinity, and Firth brings them back. In our experiment quasi-Poisson improves coverage and the sandwich reaches the Board's tolerance; neither has a universal finite-sample guarantee. The negative binomial beat zero inflation and hurdles for the doctor visits. Graphical log-linear models encode particular independences through missing interactions; not every hierarchical model is graphical. Proportional odds share one slope across cut-points, which must be checked. GEE turned fifty-five percent coverage into ninety-five; it estimates marginal effects, not conditional ones. And probability forecasts are graded by proper scores, which accuracy is not.

Where it comes back. Part 25 fits generalized linear mixed models, the conditional effects of chapter eleven. Part 26 uses suitable proper priors to regularize GLM coefficients under separation. Part 28 chooses links and terms by AIC and cross-validation. Part 30 makes GLMs robust. Part 32 penalizes them, the lasso for logistic regression. Part 34 uses proper scores to grade calibrated predictions. Part 36's propensity scores are fitted GLMs. And Part 40 fits Cox's survival model as a Poisson GLM.

Six problems, with full solutions in the README. The gamma as an exponential dispersion family; Fisher scoring as weighted least squares; the Poisson deviance with an intercept; why separation sends the log likelihood towards its unattained supremum of zero; the negative binomial as a gamma mixture; and whether the Brier and absolute scores are proper. Pause here if you want to try them.

The books this part follows: McCullagh and Nelder's Generalized Linear Models, Agresti's Categorical Data Analysis, Dunn and Smyth's GLMs with examples in R, and Dobson and Barnett's introduction; with the papers from Bliss to Gneiting and Raftery.

Twenty-four parts of sixty-five. One family of models now covers proportions, counts, categories and clusters. Next, estimating many related things at once. In 1975 Bradley Efron and Carl Morris predicted eighteen baseball players' batting averages, and shrinking each towards the others beat using each player's own record. Part 25: borrowing strength.

Where it goes next. Conditional effects and GLMMs follow in Part 25; Bayesian GLMs and priors against separation in Part 26; links and terms are chosen by AIC and cross-validation in Part 28; penalized GLMs are Part 32, calibration and scoring Part 34, propensity scores Part 36, and Cox regression as a Poisson GLM Part 40.

Key results

The part's results in one place, for revision.

The exponential dispersion family\(\displaystyle f(y;\theta,\phi)=\exp\Bigl\{\frac{y\theta-b(\theta)}{\phi}+c(y,\phi)\Bigr\},\qquad\allowbreak \mathbb{E}\,y=b'(\theta)=\mu,\quad\allowbreak \operatorname{Var}y=\phi\,b''(\theta)=\phi V(\mu)\)
IRLS\(\displaystyle \beta^{+}=(X^\top WX)^{-1}X^\top Wz,\qquad\allowbreak z_i=\eta_i+(y_i-\mu_i)\frac{d\eta_i}{d\mu_i},\quad\allowbreak w_i=\frac{(d\mu_i/d\eta_i)^2}{V(\mu_i)}\)
Deviance\(\displaystyle D=2\phi\,(\ell_{\text{sat}}-\ell_{\text{fit}}),\qquad\allowbreak D_{\text{Poisson}}=2\sum_i\Bigl\{y_i\log\frac{y_i}{\hat\mu_i}-(y_i-\hat\mu_i)\Bigr\}\)
The negative binomial as a gamma mixture\(\displaystyle y\mid\lambda\sim\operatorname{Poisson}(\lambda),\ \lambda\sim\operatorname{Gamma}(k,\ \text{mean }\mu)\ \Longrightarrow\ \operatorname{Var}y=\mu+\frac{\mu^2}{k}\)
Generalized estimating equations\(\displaystyle \sum_{g}D_g^\top V_g^{-1}(y_g-\mu_g)=0,\qquad\allowbreak D_g=\frac{\partial\mu_g}{\partial\beta},\quad\allowbreak V_g=\text{the }\allowbreak \text{working }\allowbreak \text{covariance }\allowbreak \text{of }\allowbreak \text{cluster }g\)
A proper score: Brier\(\displaystyle \mathbb{E}_p(q-Y)^2=p(1-q)^2+(1-p)q^2\ \text{ is }\allowbreak \text{minimized }\allowbreak \text{at } q=p\)

Try it

Lab 24 · Bliss's beetles, and when the deviance is chi-squared

Fit the logit, probit and complementary log-log to Bliss's eight doses with the series' IRLS, then simulate from a true logistic model to see the deviance come close to chi-squared for grouped data and fail for binary data.

Figure produced by Lab 24: Bliss's beetles, and when the deviance is chi-squared
Produced by the lab below, seed 0, in 0.7 s.
python -m videos.stats.labs 24 needs numpy, scipy, matplotlib · download lab24.py · source on GitHub
logit: deviance on 6 df                        11.23   (the film: 11.23)
probit: deviance on 6 df                       10.12   (the film: 10.12)
cloglog: deviance on 6 df                      3.45   (the film: 3.45)
IRLS from beta = 0: deviance path              305.6 -> 38.78 -> 13.31 -> 11.26 -> 11.23
cloglog LD50 (log dose), Fieller 95%           1.7788   [1.7702, 1.7862]
grouped data: deviance mean, sd                6.59, 3.67   (chi-squared(6): 6, 3.46)
grouped data: a correct model rejected at 5%   8.0%
binary data: deviance mean, sd                 234.6, 11.8   (chi-squared(198): 198, 19.9)
binary data: a correct model 'rejected' at 5%  60.9%

With many beetles per dose the deviance is a rough goodness-of-fit test; with one trial per row it depends on the fitted probabilities alone and says nothing about fit.
The code (77 lines; it asserts its own result)
"""Lab 24: fit Bliss's beetles by IRLS under three links, and test the deviance's chi-squared approximation."""

import numpy as np
from scipy import special, stats

from videos.coursekit import labs
from explainer.stats import museum
from explainer.stats.kit import glm

TITLE = "Bliss's beetles, and when the deviance is chi-squared"
GOAL = ("Fit the logit, probit and complementary log-log to Bliss's eight doses with the series' IRLS, then simulate "
        "from a true logistic model to see the deviance come close to chi-squared for grouped data and fail for binary data.")
TASKS = [
    "Start IRLS for the cloglog link from zeros (start=np.zeros(2)). How many steps does it take, and does it halve?",
    "Halve every group size in the grouped simulation. At what size does the 5% test stop rejecting about 5%?",
    "For the binary data, compare the deviance drop between two nested models with chi-squared(1). Does Wilks hold?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    x, n, k = museum.bliss()
    X = np.column_stack([np.ones(len(x)), x])
    fits = {link: glm.glm_fit(X, k / n, glm.family("binomial", link), n=n) for link in ("logit", "probit", "cloglog")}
    cold = glm.glm_fit(X, k / n, glm.family("binomial"), n=n, start=np.zeros(2))
    ld = glm.ld50(fits["cloglog"])
    lab = labs.Lab()
    for link, film in (("logit", 11.23), ("probit", 10.12), ("cloglog", 3.45)):
        f = fits[link]
        lab.row(f"{link}: deviance on {f.df_resid} df", f"{f.deviance:.2f}   (the film: {film})")
    lab.row("IRLS from beta = 0: deviance path", " -> ".join(f"{d:.4g}" for d in cold.deviance_path[:5]))
    lab.row("cloglog LD50 (log dose), Fieller 95%", f"{ld['x']:.4f}   [{ld['fieller'][0]:.4f}, {ld['fieller'][1]:.4f}]")

    reps = 800
    p_true = special.expit(X @ fits["logit"].coef)  # a true logistic model at Bliss's doses and group sizes
    grouped = np.array([glm.glm_fit(X, rng.binomial(n.astype(int), p_true) / n, glm.family("binomial"), n=n).deviance
                        for _ in range(reps)])
    nb, binary = 200, []
    for _ in range(reps):
        xb = rng.normal(size=nb)
        yb = (rng.random(nb) < special.expit(0.3 + xb)).astype(float)
        binary.append(glm.glm_fit(np.column_stack([np.ones(nb), xb]), yb, glm.family("binomial")).deviance)
    binary = np.array(binary)
    rej_g = np.mean(grouped > stats.chi2.ppf(0.95, 6))
    rej_b = np.mean(binary > stats.chi2.ppf(0.95, nb - 2))
    lab.row("grouped data: deviance mean, sd", f"{grouped.mean():.2f}, {grouped.std():.2f}   (chi-squared(6): 6, 3.46)")
    lab.row("grouped data: a correct model rejected at 5%", f"{rej_g:.1%}")
    lab.row("binary data: deviance mean, sd", f"{binary.mean():.1f}, {binary.std():.1f}   (chi-squared(198): 198, 19.9)")
    lab.row("binary data: a correct model 'rejected' at 5%", f"{rej_b:.1%}")
    lab.note = ("With many beetles per dose the deviance is a rough goodness-of-fit test; with one trial per row it depends on "
                "the fitted probabilities alone and says nothing about fit.")
    for link, film in (("logit", 11.23), ("probit", 10.12), ("cloglog", 3.45)):
        assert abs(fits[link].deviance - film) < 0.01, f"{link} deviance"
    assert np.all(np.diff(cold.deviance_path) <= 1e-8) and np.allclose(cold.coef, fits["logit"].coef, atol=1e-6), "IRLS"
    assert abs(ld["x"] - 1.7788) < 2e-4 and ld["fieller"][0] < fits["logit"].coef[0] / -fits["logit"].coef[1] < ld["x"]
    assert abs(grouped.mean() - 6) < 1.0 and 0.03 < rej_g < 0.12, "grouped deviance is close to chi-squared(6)"
    assert binary.std() < 16 and abs(rej_b - 0.05) > 0.2, "binary deviance is not chi-squared(198)"

    fig, ax = labs.figure(3, size=(13.5, 4.2))
    grid = np.linspace(1.66, 1.91, 200)
    Xg = np.column_stack([np.ones(200), grid])
    ax[0].scatter(x, k / n, s=28, color=labs.INK, zorder=3, label="Bliss's eight doses")
    for link, color in (("logit", labs.BLUE), ("probit", labs.GREEN), ("cloglog", labs.GOLD)):
        ax[0].plot(grid, fits[link].fam.ginv(Xg @ fits[link].coef), color=color,
                   label=f"{link}: deviance {fits[link].deviance:.2f}")
    ax[0].set(title="Three links through the beetles", xlabel="log10 dose", ylabel="proportion killed")
    ax[0].legend(fontsize=8)
    for a, dev, df, name in ((ax[1], grouped, 6, "Grouped: 8 doses of about 60"), (ax[2], binary, nb - 2, "Binary: 200 single trials")):
        lo, hi = min(dev.min(), stats.chi2.ppf(0.001, df)), max(dev.max(), stats.chi2.ppf(0.999, df))
        g = np.linspace(lo, hi, 200)
        a.hist(dev, bins=30, density=True, color=labs.BLUE, alpha=0.6, label=f"{reps} deviances, model true")
        a.plot(g, stats.chi2.pdf(g, df), color=labs.RED, label=f"chi-squared({df})")
        a.axvline(stats.chi2.ppf(0.95, df), color=labs.MUTED, ls="--", lw=1)
        a.set(title=name, xlabel="residual deviance", ylabel="density")
        a.legend(fontsize=8)
    lab.fig = fig
    return lab

Now change it

  1. Start IRLS for the cloglog link from zeros (start=np.zeros(2)). How many steps does it take, and does it halve?
  2. Halve every group size in the grouped simulation. At what size does the 5% test stop rejecting about 5%?
  3. For the binary data, compare the deviance drop between two nested models with chi-squared(1). Does Wilks hold?

Problems, with solutions

Try each problem before opening its solution.

1. The gamma family. Write the gamma density in exponential-dispersion form: find \(\theta\), \(b(\theta)\), \(\phi\) and \(V(\mu)\).

Solution

With shape ν and mean μ, log f = ν log ν − log Γ(ν) + (ν − 1) log y − ν log μ − νy/μ = (y(−1/μ) − log μ)/(1/ν) + c(y, ν).

  • The parameters. θ = −1/μ, b(θ) = −log(−θ) = log μ, φ = 1/ν.
  • The moments. b′(θ) = −1/θ = μ, and b″(θ) = 1/θ² = μ², so V(μ) = μ².
  • The link. The canonical link is θ = −1/μ, the (negative) inverse.

2. Scoring as least squares. Show that one Fisher-scoring step for a GLM is the weighted regression of \(z = \eta + (y - \mu)\,d\eta/d\mu\).

Solution

U = Σ xᵢ(yᵢ − μᵢ)(dμᵢ/dηᵢ)/(φVᵢ) = X'W(z − η)/φ, where wᵢ = (dμᵢ/dηᵢ)²/Vᵢ and zᵢ − ηᵢ = (yᵢ − μᵢ)dηᵢ/dμᵢ. The expected information is X'WX/φ. Then β + I⁻¹U = β + (X'WX)⁻¹X'W(z − η) = (X'WX)⁻¹X'Wz, since Xβ = η.

3. Poisson deviance. Poisson deviance: show \(D = 2\sum y_i \log(y_i/\hat\mu_i)\) when the model has an intercept and the log link.

Solution

D = 2Σ{yᵢ log(yᵢ/μ̂ᵢ) − (yᵢ − μ̂ᵢ)}. With a log link and an intercept, the intercept's score equation is Σ(yᵢ − μ̂ᵢ) = 0, so the second sum vanishes and D = 2Σ yᵢ log(yᵢ/μ̂ᵢ).

4. Separation. Show that complete separation makes \(\ell(c\,b)\) increase to 0 as \(c \to \infty\).

Solution

If xᵢ'b > 0 exactly when yᵢ = 1, then for c > 0, ℓ(cb) = Σ_{y=1} −log(1 + e^{−c xᵢ'b}) + Σ_{y=0} −log(1 + e^{c xᵢ'b}). In both sums the exponent's argument tends to −∞ as c → ∞, so every term increases to 0. The supremum, 0, is not attained.

5. The negative binomial as a mixture. NB as a mixture: \(y \mid \lambda \sim\) Poisson\((\lambda)\), \(\lambda \sim\) Gamma\((k, k/\mu)\): derive \(E\,y\) and Var \(y\).

Solution

Take λ ~ Gamma with shape k and mean μ, so Var λ = μ²/k.

  • The mean. E y = E E(y | λ) = E λ = μ.
  • The variance. Var y = E Var(y | λ) + Var E(y | λ) = E λ + Var λ = μ + μ²/k.
  • The marginal distribution. Integrating the Poisson against the gamma gives the negative binomial probability function.

6. Propriety. Show that the Brier score is proper: \(E_p (q - y)^2\) is minimized at \(q = p\). Is \(|q - y|\)?

Solution

E_p(q − y)² = p(1 − q)² + (1 − p)q², whose derivative 2(q − p) vanishes at q = p, a minimum, so the Brier score is proper. E_p|q − y| = p(1 − q) + (1 − p)q = p + q(1 − 2p) is linear in q. It is minimized at q = 0 when p < ½ and at q = 1 when p > ½, so the absolute score is improper: it rewards rounding.

Notes and sources

Where it comes back

Idea Returns in
GLMMs: conditional effects 25
Bayesian GLMs; priors against separation 26
choosing links and terms: AIC, CV 28
robust GLMs 30
penalized GLMs 32
calibration and scoring of predictions 34
propensity scores 36
Cox regression as a Poisson GLM 40
the Coverage Board every part; 65

Glossary

  • Generalized linear model; linear predictor; link: an exponential-family outcome whose mean, through g, is linear in the covariates.
  • Exponential dispersion family; canonical parameter; cumulant function b; dispersion φ; variance function V: f = exp{(yθ − b(θ))/φ + c}; μ = b′(θ); Var y = φV(μ).
  • Canonical link: g(μ) = θ, giving score X′diag(w)(y − μ)/φ and sufficient X′diag(w)y for β at known dispersion and fixed prior weights.
  • Probit; logit; complementary log-log; tolerance distribution: inverse links for probabilities; the latent threshold story behind them.
  • IRLS; working response; working weights: Fisher scoring as repeated weighted least squares.
  • Deviance; saturated model; analysis of deviance: twice the log-likelihood gap to a perfect fit; comparing nested models by drops.
  • Pearson, deviance and randomized quantile residuals: standardized differences; signed root unit deviances; Φ⁻¹ of a randomized CDF; exactly N(0, 1) for the known true conditional CDF, with fitted residuals used diagnostically.
  • Separation; Firth's penalized likelihood: perfect prediction and infinite MLEs; the Jeffreys-prior penalty that keeps them finite.
  • Overdispersion; quasi-likelihood; quasi-Poisson; beta-binomial: more variation than the family allows; a mean–variance model without a distribution; φμ; a binomial with beta-distributed p.
  • Negative binomial; zero-inflated model; hurdle model; offset: a gamma-mixed Poisson; structural zeros plus a count model; a gate then a truncated count; a log exposure with coefficient 1.
  • Log-linear model; conditional independence; graphical model: Poisson models for table counts; specific absent interaction sets; graphical models retain all maximal-clique interactions.
  • Multinomial logit; IIA; proportional odds; cut-points: softmax over categories; the independence of irrelevant alternatives; one slope for all cumulative logits; the thresholds on the latent scale.
  • GEE; working correlation; marginal vs conditional effect: cluster-wise score equations with a robust sandwich; the guessed within-cluster correlation; population-averaged against cluster-specific coefficients.
  • Proper scoring rule; log score; Brier score; CRPS; calibration; resolution: penalties that reward honesty; −log q_y; (q − y)²; the integrated squared CDF gap; agreement of forecasts and rates; spread of forecasts.

Sources

  • History.
    • C. Bliss, Ann. Appl. Biol. 22 (1935), with R. A. Fisher's appendix.
    • J. Nelder & R. Wedderburn, JRSS A 135 (1972); M. Greenwood & G. U. Yule, JRSS 83 (1920).
  • Methods.
    • R. Wedderburn, Biometrika 61 (1974); P. McCullagh, JRSS B 42 (1980); M. Tweedie (1984).
    • A. Albert & J. Anderson, Biometrika 71 (1984); D. Firth, Biometrika 80 (1993); G. King & L. Zeng, Political Analysis 9 (2001); R. Prentice & R. Pyke, Biometrika 66 (1979).
    • P. Dunn & G. Smyth, JCGS 5 (1996); D. Hosmer & S. Lemeshow (1980); D. Williams, Applied Statistics 31 (1982).
    • J. Ver Hoef & P. Boveng, Ecology 88 (2007); A. C. Cameron & P. Trivedi, J. Econometrics 46 (1990).
    • D. Lambert, Technometrics 34 (1992); J. Mullahy, J. Econometrics 33 (1986); C. Gourieroux, A. Monfort & A. Trognon, Econometrica 52 (1984); J. Santos Silva & S. Tenreyro, REStat 88 (2006).
    • J. Darroch, S. Lauritzen & T. Speed, Ann. Stat. 8 (1980).
    • K.-Y. Liang & S. Zeger, Biometrika 73 (1986); S. Zeger, K.-Y. Liang & P. Albert, Biometrics 44 (1988); L. Mancl & T. DeRouen, Biometrics 57 (2001); M. Pepe & G. Anderson (1994).
    • G. Brier, Monthly Weather Review 78 (1950); A. Murphy, J. Appl. Meteorology 12 (1973); T. Gneiting & A. Raftery, JASA 102 (2007).
  • Books.
    • P. McCullagh & J. Nelder, Generalized Linear Models (2nd ed., 1989).
    • A. Agresti, Categorical Data Analysis (3rd ed., 2013).
    • P. Dunn & G. Smyth, Generalized Linear Models with Examples in R (2018).
    • A. Dobson & A. Barnett, An Introduction to Generalized Linear Models (4th ed., 2018).
About this partfrom its README

Part 24 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the fourth part of Stage III, Master's. Part 14 fitted logistic and Poisson regressions. This part shows they are two members of one family, fitted by one algorithm (Nelder & Wedderburn 1972). It then pushes that family to overdispersion, excess zeros, tables, ordered categories, clusters and the grading of probability forecasts.

It opens with Chester Bliss's 1935 flour beetles: 481 beetles at eight doses of carbon disulphide, with deaths rising from 6/59 to 60/60.

  • Bliss's probit, the logit and the complementary log-log all fit; their deviances on 6 df are 10.12, 11.23 and 3.45.
  • Among the three fitted links, cloglog has the lowest AIC, with AIC 33.6 against 41.4 for the logit.
  • Its LD50 is a log dose of 1.7788 (60 mg/l), with Fieller interval [1.7702, 1.7862]. The logit's 1.7717 sits near the bottom of that interval.

From there the part covers:

  • The upgrade. The three parts of a GLM; why not the linear probability model.
  • The exponential dispersion family.
    • Canonical parameter, b(θ), dispersion; mean b′ and variance φV(μ) from Part 22's score identities.
    • A table of families.
    • Gamma regression of the World's incomes (mean ×1.117 per decade, φ̂ = 0.86) against a log-normal fit (0.100 per decade): different targets.
    • Tweedie's power variance; logit, probit and cloglog curves; the canonical link.
  • IRLS derived.
    • Fisher scoring as weighted least squares on the working response.
    • The beetles from β = 0: slope 21.3 → 30.4 → 33.8 → 34.26 → 34.27. The deviance goes 306 → 38.8 → 13.3 → 11.26 → 11.23, converging in 7 steps from the displayed zero start, using a coefficient-change tolerance.
    • Step-halving; non-canonical links.
  • Deviance.
    • The saturated model; the beetles' deviances.
    • Analysis of deviance for 2,000 of the World's doctor visits: drops of 754, 299, 257 and 68 against a residual 5,948 on 1,995 df (φ̂ = 3.36), and why order matters.
    • Pearson, deviance and randomized quantile residuals (Dunn & Smyth 1996); binned residuals.
    • Quantile-residual QQ plots: Poisson against negative binomial.
  • Asymptotics.
    • Wald, LR and score; the dispersion and F tests.
    • The LD50 by delta and Fieller; testing overdispersion (LR 1,924, with a ½χ²₀ + ½χ²₁ null).
    • The deviance's χ² approximation. For grouped data, 2,000 fake Bliss experiments reject 6.0%. For binary data the deviance has mean 235 and SD 12 against χ²₁₉₈, so it would "reject" a correct model 63% of the time.
  • Separation.
    • Twelve separated points: IRLS slopes climb by 5 a step to 108, while the log likelihood → 0.
    • Albert & Anderson; Firth's penalized likelihood gives 2.55 (SE 1.46).
    • Rare events and case–control sampling. With two points swapped, the MLE exists: 3.45 (SE 2.19).
  • Quasi-likelihood.
    • Wedderburn's construction.
    • The visits: SEs ×1.83 for quasi-Poisson; sandwich SEs up to ×2.17; negative-binomial fits.
    • Quasi-Poisson's constant-multiple shape against the NB's μ + μ²/k; the beta-binomial.
    • Bliss's φ̂: 1.67 under the logit but 0.55 under the cloglog (a wrong mean looks like overdispersion).
    • Three Board rows.
  • Counts.
    • The negative binomial as a gamma mixture (Greenwood & Yule 1920); offsets and rate ratios.
    • 40% zeros against the Poisson's 19% and the NB's 39%.
    • Poisson, ZIP (π̂ = 0.35, by EM), hurdle and NB: AIC 9,375, 8,248, 8,171 and 7,453.
    • Poisson pseudo-maximum likelihood.
    • The World's truth is a zero-inflated NB (15% never-goers, k = 1.2). The NB fits best by shrinking k to 0.82.
  • Log-linear models.
    • Sex × age group × told high blood pressure for 5,000 adults.
    • Deviances: [SA][T] 798 on 5 df, [SA][AT] 39.1 on 3, [SA][AT][ST] 16.4 on 2 (p = 0.0003). The saturated model fits by definition, because the sex gap changes with age.
    • Homogeneous-association OR 0.68 (the common-OR model is rejected); graphical models; the Poisson trick.
  • Multinomial and ordinal.
    • Baseline-category logits and IIA.
    • Proportional odds for four BMI categories in 3,000 adults: age 0.173 per decade (OR 1.19); sex −0.04 (none, as the World was built).
    • Fitted category probabilities by age.
    • Separate-cut slopes of 0.31, 0.18 and 0.15: not quite proportional. Other ordinal models.
  • GEE.
    • Pupils passing 550 in 40 of the World's schools. The iid SE of the programme is 0.094; GEE-independence gives the same estimate (0.453) with robust SE 0.228. Exchangeable (α̂ = 0.089) gives 0.405 with model and robust SEs agreeing.
    • The census independence-logistic projection is 0.392; the census exchangeable-equation target is 0.378. The working mean is approximate, so the two targets need not coincide. Marginal against conditional effects (Zeger, Liang & Albert 1988); choosing the working correlation.
    • Three Board rows.
  • Proper scoring rules.
    • Log, Brier and absolute scores at p = 0.3.

    • Forecasting a high blood pressure diagnosis on 2,000 new adults:

      Forecaster Log score Brier Accuracy
      fitted logistic reference 0.373 0.115 83.5%
      overconfident 0.438 0.131 81.9%
      base rate 0.463 0.144 82.6%
    • The held-out calibration plot, with 200 adults per risk decile and Wilson uncertainty bars: the overconfident model says 86% where 54% happen, with the same AUC.

    • CRPS (0.560 honest, 0.604 too narrow, 0.653 too wide); Murphy's decomposition.

Every number on screen is computed in compute.py:

  • Bliss's beetles are the Museum's;
  • doctor visits, health, incomes and schools are the World's;
  • the rest are seeded simulations.

Built in this part:

  • statkit.glm II (explainer/stats/kit/glm.py), checked in tests/test_stats_kit_glm2.py:
    • Family, with links (identity, log, logit, probit, cloglog, inverse), variance functions and unit deviances;
    • glm_fit, a general IRLS recording its path, with deviance, Pearson/deviance/randomized quantile residuals, φ̂, and model, quasi and sandwich covariances;
    • LD50 with delta and Fieller intervals;
    • Firth's logistic regression, and separation paths;
    • negative binomial regression; ZIP by EM; Poisson hurdle;
    • multinomial logit; proportional odds;
    • GEE for binary outcomes (independence and exchangeable);
    • log and CRPS scores.
  • The dose–response panel (DoseResponse in explainer/stats/viz.py).
  • The World: the visits block, doctor visits with structural zeros (VISITS_NEVER) and NB heterogeneity (VISITS_K = 1.2).
  • The Museum: BLISS_BEETLES and bliss().

The Coverage Board gains six rows:

Method Setting Reps Achieved Verdict
Poisson model SE doctor visits, n = 500 1,000 63.5% broken
quasi-Poisson SE doctor visits, n = 500 1,000 89.5% broken
sandwich SE doctor visits, n = 500 1,000 94.4% kept
logistic, iid SE 40 schools, pupils clustered 500 54.8% broken
GEE, independence 40 schools, robust SE 500 95.0% kept
GEE, exchangeable 40 schools, robust SE; own census target 500 95.8% kept
Chapter notes
# Chapter Numbers
0 Bliss's beetles, 1935 deviances 11.23 / 10.12 / 3.45; LD50 1.7788 [1.7702, 1.7862]
1 Upgrade: what Part 14 fitted the three parts; the linear probability model
2 The exponential dispersion family gamma ×1.117 per decade, φ̂ 0.86; log-normal 0.100
3 IRLS derived slope 21.3 → 34.27 in 7 steps; deviance 306 → 11.23
4 Deviance drops 754 / 299 / 257 / 68; φ̂ 3.36
5 Asymptotics for GLMs grouped 6.0%; binary 63% false rejections; LR for overdispersion 1,924
6 Separation slope → 108; Firth 2.55 (1.46)
7 Quasi-likelihood ×1.83; Bliss φ̂ 1.67 vs 0.55; Board 63.5 / 89.5 / 94.4%
8 Counts zeros 40% vs 19% vs 39%; AIC 9,375 / 8,248 / 8,171 / 7,453; k̂ 0.82 vs 1.2
9 Log-linear models 798 / 39.1 / 16.4; OR 0.68
10 Multinomial and ordinal 0.173 per decade (OR 1.19); cut slopes 0.31 / 0.18 / 0.15
11 GEE SE 0.094 vs 0.228; α̂ 0.089; truth 0.392; Board 54.8 / 95.0 / 95.8% (method-specific census targets)
12 Proper scoring rules log 0.373 / 0.438 / 0.463; says 86%, sees 54%; CRPS 0.560 / 0.604 / 0.653
13 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Bliss (1935). Beetle mortality at eight doses; probits and the LD50.
  2. Upgrade card (Part 14).
  3. The exponential dispersion family. Variance functions; canonical links; Nelder & Wedderburn (1972).
  4. IRLS derived. Fisher scoring = weighted least squares on a working response.
  5. Deviance. The saturated model; analysis of deviance; residuals (Dunn & Smyth 1996).
  6. Asymptotics for GLMs. Wald, score, LR; the dispersion parameter.
  7. Separation (Albert & Anderson 1984). The likelihood rising forever; Firth (1993).
  8. Quasi-likelihood (Wedderburn 1974). Only a mean–variance relation; overdispersion (Board).
  9. Counts. Negative binomial; zero inflation (Lambert 1992); hurdle models.
  10. Log-linear models. Three-way tables as GLMs; conditional independence as zeros.
  11. Multinomial and ordinal. Baseline-category logits; proportional odds (McCullagh 1980).
  12. GEE (Liang & Zeger 1986). Working correlations; marginal vs conditional effects (Board).
  13. Proper scoring rules (Gneiting & Raftery 2007).
  14. Outro.

Built: statkit.glm (II). Data: Bliss (1935).

Build the film

python -m videos.stats.stats24.compute        # the part's numbers, into .cache/stats24
python tools/build.py stats24                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats24 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats24. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.stats.stats24.compute         # once (about a minute; cached in .cache/stats24)
python tools/build.py stats24 -q l             # fast 480p preview
python tools/build.py stats24                  # 1080p30 -> renders/stats24.mp4
python tools/qa_scene.py stats24 Counts
python tools/lecture_length.py stats24 --floor 50