Stage II · Bachelor's: Methods
Part 14 of 65Counts and Categories
How do you regress a yes/no or a count, and read a table?
On the evening of 27 January 1986 the teleconference before Challenger's launch looks at the seven flights with O-ring distress, where temperature and damage are uncorrelated. Adding the sixteen flights with no distress, all launched at 66 F or warmer, shows the effect. A least-squares line through the 0/1 outcomes predicts a probability of 1.75 at the forecast 31 F, so the part builds logistic regression: log-odds linear in temperature, fitted by maximum likelihood, with Newton's method drawn as a sequence of weighted regressions. The Challenger fit puts the probability of distress at 31 F at 0.9996, with a profile interval of [0.80, 1] and an extrapolation caveat. Poisson regression does the same for counts, and overdispersion breaks its standard errors. The part turns to tables at Berkeley in 1973, where the pooled table and the department tables disagree (Simpson's paradox) and Mantel-Haenszel pools the strata, then to case-control studies with Doll and Hill, and ends by scoring forecasts with ROC curves, calibration and the Brier score.
What you need. Calculus, logarithms and exponentials; the regression of Part 12.
- Hook
- the Challenger O-rings, 1986
- Mathematics
- logistic and Poisson regression, odds ratios, tables, Simpson's paradox, case–control
- Built
- a Challenger dashboard
What you will be able to do
Bachelor's
- Explain why a straight line is the wrong model for a 0/1 outcome, and turn a logistic coefficient into an odds ratio.
- Compute an odds ratio, a relative risk and a chi-squared test from a 2 x 2 table, and recognise Simpson's paradox in stratified rates.
Master's
- Derive the logistic score and Hessian, and carry out one IRLS step as a weighted regression.
- Fit a Poisson regression with an offset, and compare classical, quasi-Poisson and sandwich standard errors under overdispersion.
- Pool stratified 2 x 2 tables by Mantel-Haenszel and test with CMH.
PhD
- Show why outcome-dependent sampling leaves the logistic slopes unchanged and shifts only the intercept, and state what the Prentice-Pyke result adds.
- Explain why the maximum likelihood estimate fails to exist under separation, and what that does to Wald and likelihood-ratio inference.
Practice
- Report a logistic fit with a profile-likelihood interval, and flag a prediction that extrapolates beyond the data.
- Judge a probabilistic forecast by discrimination (AUC), calibration and the Brier score, and say which of them a threshold decision needs.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 25 min · Master's 49 min · PhD 53 min · Practice 36 min.
- 027 January 1986Bachelor's3 min
- 1Why not least squaresBachelor's3 min
- 2Logistic regressionBachelor's5 min
- 3Fitting by maximum likelihoodMaster's4 min
- 4The Challenger fitBachelor's5 min
- 5Poisson regressionMaster's5 min
- 6OverdispersionPractice5 min
- 7Two-way tablesBachelor's4 min
- 8Simpson's paradoxBachelor's3 min
- 9Three-way tablesMaster's4 min
- 10Case-control studiesPhD5 min
- 11Scoring predictionsPractice6 min
- 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.
27 January 1986Bachelor's3 min
On the evening of the twenty-seventh of January, 1986, engineers and managers from NASA and from Morton Thiokol, the company that built the space shuttle's solid rocket boosters, held a teleconference. The next morning's launch of Challenger was forecast to be far colder than any before it. The joints between the booster's segments were sealed by rubber O-rings, and rubber stiffens in the cold. Thiokol's engineers recommended not launching below fifty-three degrees Fahrenheit, the coldest launch so far. After an off-line caucus, Thiokol's managers reversed the recommendation. The data at the centre of the argument were a few numbers about past flights.
Here is the kind of picture that was discussed: the flights on which O-rings had shown thermal distress, plotted by launch temperature. There were seven. The coldest, at fifty-three degrees, had two damaged rings. But so did a flight at seventy-five, and there was damage at seventy as well. Among these seven flights, the correlation between temperature and damage is essentially zero. Problems seemed to happen at any temperature. But the picture shows only the flights that had problems.
Now add the sixteen flights that had no O-ring distress at all. Every one of them launched at sixty-six degrees or warmer. Below sixty-six, there were four flights, and all four had distress. The temperature effect is plain, once the zeros are in the picture. And the forecast for the launch, in the analysis that statisticians Siddhartha Dalal, Edward Fowlkes and Bruce Hoadley published three years later, was thirty-one degrees: twenty-two degrees colder than any shuttle had flown.
On the morning of the twenty-eighth of January, Challenger launched at about thirty-six degrees. A joint on the right booster failed, and seventy-three seconds into the flight the vehicle broke apart. The seven crew members were killed. The presidential commission that investigated found the cause in the O-ring seal, made worse by the cold. At one hearing, the physicist Richard Feynman dropped a piece of the O-ring rubber into a glass of iced water and showed that it didn't spring back. Three years later Dalal, Fowlkes and Hoadley published the analysis that should have been possible that night: a logistic regression on all twenty-three flights. And Edward Tufte later argued that the right chart alone would have shown the danger.
Numbers: 7 flights with distress, r = 0.02; all 16 without at ≥ 66 °F; forecast 31 °F
1Why not least squaresBachelor's3 min
Simplify the outcome to yes or no: did any O-ring on the flight show distress? Seven flights say yes, sixteen say no. Each dot now sits at zero or one, at its launch temperature. What we want is the probability of distress as a function of temperature, and especially its value far to the left, at thirty-one degrees.
The obvious first try is Part 12's least squares, with the zeros and ones as the response. It's called the linear probability model. The fitted line falls by about four percentage points per degree. At thirty-one degrees it predicts a probability of one point seven five. At eighty-five, minus point two seven. A straight line can't respect the fact that probabilities live between zero and one. Near the middle of the data it's a fair summary; at the temperature that mattered, it's nonsense.
There are deeper problems too. A yes-or-no outcome is a Bernoulli variable, with probability p of x. Its variance is p times one minus p: tied to the mean, so it changes with x, largest at a half and vanishing near zero and one. The residuals at each x take only two values. When p varies, Bernoulli variance generally varies too; it can coincide at symmetric probabilities. The errors are nonnormal and unconstrained linear predictions can leave zero to one. The sandwich standard errors of Part 12 can patch the first problem, and economists still use the linear probability model for its simple coefficients. But for prediction, and especially for extrapolation, we need a different curve.
In fairness to the straight line: economists use the linear probability model all the time. Its coefficient is a change in the fitted linear probability per unit of x, easy to read and the same everywhere. The heteroskedasticity is known, so it can be handled with Part 12's sandwich standard errors. As a descriptive linear projection over a restricted range, the line is often close to the logistic curve's slope there. Its probability forecasts can fail badly at the edges, which is exactly where Challenger's question lay.
What we want is a curve that runs from zero to one, rising steeply in the middle and flattening at both ends, where a probability can't go further. And to keep the convenience of regression, we'd like the curve to be linear in x on some transformed scale. The most popular answer is the logistic curve, e to the eta over one plus e to the eta. It was introduced by Pierre-François Verhulst in the 1840s, to describe population growth.
Numbers: p̂ = 2.90 − 0.0374T; p̂(31) = 1.75, p̂(85) = −0.27
2Logistic regressionBachelor's5 min
Start from the odds: p over one minus p. A probability of point eight is odds of four to one. Odds run from zero to infinity. Take the logarithm, and the log-odds, or logit, run over the whole real line, with a probability of one half at zero. Now regression can do its usual thing: model the log-odds as a straight line in x. Inverting gives the probability: the logistic curve. That's logistic regression, popularized for medical data by Joseph Berkson in 1944, and given its modern form by David Cox in 1958.
A few values. Between point two and point eight, the log-odds behave much like the probability itself, stretched out. Near zero or one they stretch enormously: going from point nine nine to point nine nine nine six, the Challenger number we'll meet, is a step of three point two on the log-odds scale. And since logs turn products into sums, adding a constant to the log-odds multiplies the odds: two point three is a factor of ten.
Here's the logistic curve fitted to all twenty-three flights: logit p equals fifteen point oh four minus point two three two times the temperature. It crosses one half at about sixty-five degrees, between the warm flights and the cold ones. At seventy degrees it gives a twenty-three percent chance of distress; at fifty-three, the coldest flight, ninety-four percent. We'll see how it was fitted in a moment, and what it says at thirty-one degrees after that.
How do you read the coefficient? The slope is the change in log-odds for each degree. So e to the slope is an odds ratio: the factor by which the odds change per degree, the same at every temperature, though the change in probability isn't. Ten degrees colder, the odds of distress are multiplied by about ten. With only twenty-three flights the uncertainty is large: the profile-likelihood interval, which we'll build in chapter four, runs from about two to about a hundred and seventy. Under the fitted model it excludes one: lower temperature is associated with more distress.
A second, hypothetical latent-variable representation; it is not a physical seal-failure mechanism. Imagine a hidden strain on the seal, y star, which is a straight line in temperature plus random noise. The seal shows distress when the strain crosses a threshold, zero. If the noise has the logistic distribution, the probability of crossing is exactly the logistic curve of eta. As the temperature drops, eta rises, the whole distribution slides right, and more of it lies past the threshold. If the noise is normal instead, the probability is the normal CDF of eta: the probit model, which Chester Bliss introduced in 1934 for the doses that kill insects.
Fit both models to the flights. The logit coefficients are about one point seven times the probit ones, because the logistic distribution is more spread out than the standard normal; its standard deviation is pi over root three. Where the data are, the two curves are close. At thirty-one degrees, both say distress is nearly certain, but the logit model leaves four chances in ten thousand of no distress, and the probit about two in a million. That difference comes entirely from the assumed shape of the tail. The data can't tell the two apart, which is the first warning about extrapolating.
Why the logit, of all transformations? Write the Bernoulli distribution in Part 3's exponential-family form. The quantity multiplying y, its natural parameter, is exactly the log-odds. Do the same for the Poisson, and the natural parameter is the log of the mean, which is why Poisson regression will use logs. Setting the natural parameter equal to a linear predictor is called using the canonical link, and it makes the score equations take the simple form X transpose times y minus the mean. This is the unifying idea of generalized linear models, which Part 24 develops.
Numbers: logit p̂ = 15.04 − 0.232T; p̂ = 0.5 at 64.8 °F; p̂(70) = 0.23, p̂(53) = 0.94; OR per 10 °F colder 10.2 [1.8, 173]; logit/probit 1.72
3Fitting by maximum likelihoodMaster's4 min
There's no formula for the logistic coefficients. They come from Part 9's maximum likelihood. The likelihood is the product, over flights, of p for the flights with distress and one minus p for the others. Its logarithm simplifies to a sum of y times eta minus log of one plus e to the eta, a strictly concave function at finite coefficients when X has full column rank. A finite maximum is unique if it exists; separation can make it nonexistent. At the maximum the score is zero: X transpose times the residuals, y minus p, vanishes. That's Part 12's normal equations, with the fitted probabilities in place of fitted values. But p depends on beta nonlinearly, so we can't solve it in one step. The curvature is X transpose W X, with weights p times one minus p: the Fisher information, whose inverse gives the standard errors.
Here is the log-likelihood as a landscape over the two coefficients, brighter where it's higher. It has one long ridge and a single peak. The ridge is diagonal because the temperatures are all far from zero: a bigger intercept can be traded for a steeper slope with almost the same fit. Centring temperature would round it out. The peak, the maximum likelihood estimate, is at fifteen point oh four and minus point two three two. How do we climb to it?
Use Newton's method: step by the gradient divided by the curvature. Now a little algebra. Define a working response z: the current linear predictor, plus the residuals divided by the weights. It's what y looks like on the log-odds scale, to first order. Then the Newton step is exactly a weighted least squares regression of z on X, with weights W: Part 12's machinery, reused. Recompute the probabilities, the weights and the working response, and fit again. Iteratively reweighted least squares, a standard algorithm in generalized linear model programs since John Nelder and Robert Wedderburn's 1972 paper. Part 24 develops the theory.
Watch it work on the flights. Start from zero: every flight gets probability one half, a flat line. The log-likelihood is minus fifteen point nine. One weighted regression later, the curve already tilts the right way, and the log-likelihood jumps to minus ten point six. The next steps refine it: minus ten point one eight, minus ten point one five eight. By the fifth step the coefficients are fixed to five decimals, and they stop changing. Newton's method converges quadratically: near the answer, each step roughly doubles the number of correct digits.
How good is the fit, and does temperature matter? The deviance, which for zero-one data is minus twice the maximized log-likelihood, is twenty point three. A model with no temperature at all, the same probability for every flight, has deviance twenty-eight point three. The drop, seven point nine five, is Part 10's likelihood-ratio statistic, approximately chi-squared with one degree of freedom: p of point zero zero five. The Wald test, the coefficient divided by its standard error, gives z of minus two point one four, p of point zero three: the same rejection here; neither approximation guarantees finite-sample calibration, and the Wald test leans on a quadratic approximation that's poor with twenty-three flights. Deviances are to generalized linear models what sums of squares are to least squares.
Numbers: IRLS from 0: ℓ = −15.94, −10.59, −10.18, −10.158, …; D = 20.32 vs D₀ = 28.27, LR = 7.95, p = 0.0048; Wald z = −2.14, p = 0.032
4The Challenger fitBachelor's5 min
Here is the Challenger dashboard: the flights, the fitted curve, and a ninety-five percent band around it. At eighty-one degrees, the warmest flight, the fitted chance of O-ring distress is about two percent. At seventy, twenty-three percent. At fifty-three, the coldest flight anyone had flown, ninety-four percent, and the band is already wide. Now keep going, past the last data point, to thirty-one degrees. The fitted probability is point nine nine nine six. The band spreads out in a way we need to look at.
On the log-odds scale, the fitted value at thirty-one degrees is seven point eight five, odds of about two thousand five hundred to one. Its standard error comes from the inverse information, exactly like Part 12's prediction standard error, and it's big: four point oh, because thirty-one degrees is so far from the data. The Wald interval, plus or minus one point nine six standard errors, runs from about zero to fifteen point eight. Mapped back to probabilities: from point four eight to nearly one. As stated, that's uninformative, somewhere between a coin flip and certainty. But the Wald interval trusts a quadratic approximation to the log-likelihood, far from where it was fitted.
An alternative interval uses the likelihood itself with an asymptotic likelihood-ratio cutoff. For each possible value of the log-odds at thirty-one degrees, find the best fit to the flights that has that value, and record its log-likelihood. That's the profile log-likelihood, in green. The Wald interval pretends it's the teal parabola. They agree near the top and part company in the tails: the real profile falls steeply on the left, and only slowly on the right. Part 11's likelihood-ratio interval keeps every value within one point nine two of the maximum, half the chi-squared cutoff. On the log-odds scale, one point four to eighteen. As a probability, from point eight oh to one. Even at the edge most favourable to launching, the flights say distress at thirty-one degrees is at least four times as likely as not.
Side by side: the Wald interval, point four eight to one, and the profile interval, point eight oh to one, from the same fit to the same twenty-three flights. The profile interval has a property the Wald interval lacks: it transforms consistently under one-to-one changes of scale, probability, odds or log-odds, because it's defined by the likelihood, not by an approximation on one scale. The Wald interval depends on the scale it was built on. Which keeps its promise with only twenty-three flights? Likelihood geometry favours profiling, while its chi-squared calibration is asymptotic; the Coverage Board, at the end of chapter six, has a surprise.
Now the caveat that every statistics course must teach with this example. Thirty-one degrees is twenty-two degrees colder than any flight: an extrapolation. The probability there comes from the model's tail, and as chapter two showed, the logit and probit tails differ by a factor of more than a hundred in the chance of no distress. And nothing in the data can check whether the log-odds keep falling in a straight line below fifty-three degrees. A second fit treats each flight's six O-rings as binomial trials, assuming equal risk and independence within flight: each ring's chance of distress at thirty-one is about point eight two, so this binomial model puts the chance of at least one distress event very near one. Shared flight conditions can violate ring independence. The models disagree about the number. They agree about the direction: colder is worse, and nothing in twenty-three flights suggests that thirty-one degrees was safe. The fitted probabilities describe thermal distress, not the probability of catastrophic vehicle loss.
So, the Challenger analysis in four lines. Use all the evidence, including the flights where nothing happened: selecting on the outcome hid the effect. Model the probability with a curve that stays between zero and one, fitted by maximum likelihood. Report the estimate with an interval that respects the likelihood's shape. And say plainly that a prediction far outside the data rests on the model's assumptions, a point Michael Lavine made about exactly this example in 1991.
Numbers: η̂(31) = 7.85, SE 4.04; Wald p ∈ [0.48, 1]; profile η ∈ [1.41, 18.4], p ∈ [0.80, 1]; binomial model: each ring 0.82
5Poisson regressionMaster's5 min
Now counts. Part 2's World has a silent condition whose risk rises with age. Here are the cases among the World's women, in six-year age bands. The counts rise to a peak around seventy and then fall. Does the risk fall in old age? No: there are simply fewer people in each older band, as the population pyramid narrows. A count means nothing until you know the exposure it came from: the number of people, or the person-years, or the miles driven.
Divide each count by the number of women in its band, and the rate per thousand rises steadily with age, from about two at twenty to nearly fifty at ninety-eight. It rises faster and faster: it looks multiplicative. On a logarithmic scale, the log rate is nearly a straight line in age. That suggests the model.
We approximate each band's binomial count by Poisson: rare events among many people, Part 3's law of small numbers, the horse kicks again. Its mean is the band's population times a rate, and the log of the rate is linear in age and sex. Taking logs, the population enters as log N, a term in the linear predictor whose coefficient is fixed at one: an offset. Exponentiate, and each coefficient multiplies the rate: e to beta one is the rate ratio for one more unit of age. It's fitted by the same iteratively reweighted least squares, with weights equal to the fitted means, because a Poisson variance equals its mean.
Here are both sexes, on the log scale: women in coral, men in blue. The fitted model is a pair of parallel straight lines, one for each sex, since sex enters additively on the log scale. The two lines nearly coincide. The oldest bands bend away a little: the World's true risk is logistic in age, which is close to exponential only while it's small. A model is a description, good where it's checked.
Reading the coefficients. With age coded in decades from fifty, the intercept gives the baseline: seven point seven cases per thousand women aged fifty. Each extra decade multiplies the rate by one point five five, with a tight interval, from one point five three to one point five seven, because there are seven thousand cases. Men versus women: a rate ratio of point nine nine, with an interval from point nine four to one point oh three, which contains one. And in the World, the condition truly ignores sex. The fitted age trend is clear; the interval is compatible with no sex association, which is consistent with this simulator's construction.
Does the model fit? The deviance compares it with a perfect fit, one parameter per band. It's thirty-one on twenty-five degrees of freedom: about what chance alone would give. A second check is the Pearson dispersion: the squared residuals divided by the fitted means, averaged over the degrees of freedom. It's one point two two. For truly Poisson counts it is expected to be near one under a suitable Poisson mean model; it is not a proof of fit, because a Poisson variance equals its mean. When it's far above one, the Poisson standard errors are wrong, which is the next chapter.
One more connection. When the chance per person is small, a binomial count is nearly Poisson, Part 3's law of small numbers. And for a small probability, the log and the logit nearly agree. So for a rare condition, Poisson regression's log rate ratio per decade, point four four, is close to logistic regression's log odds ratio per decade on the same World, point four five. For rare outcomes the two models tell the same story, and the appropriate choice also depends on the sampling unit and mean model: Poisson handles exposure and person-time through the offset, logistic handles individual yes-or-no records.
Numbers: 7.7 per 1,000 at 50; rate ratio per decade 1.554 [1.535, 1.574]; men 0.986 [0.94, 1.03]; D = 31.0 on 25 df, φ̂ = 1.22
6OverdispersionPractice5 min
A second count: a month of clinic visits in each of the World's two hundred towns, simulated on the World's real town sizes. The model is the same: Poisson, with the log of the town's adults as the offset, and the town's east-west position as the predictor. The fitted slope is point two three on the log scale. But look at the big towns, in green. With tens of thousands of adults, Poisson noise in their rates should be tiny; instead they scatter by a factor of three or more. The towns differ in ways the model leaves out: doctors, habits, distance to the clinic. That extra variation is overdispersion.
Plot each town's squared residual against its fitted mean, both on log scales. If the counts were Poisson, the points would scatter around the grey line, variance equal to the mean. Instead they follow the red curve, mu plus mu squared over four, which is what the simulation built in: each town's rate multiplied by a random factor with a standard deviation of a half. The Pearson dispersion is twenty-two. For big towns, the variance grows like the square of the mean, so Poisson's assumption fails worst exactly where the data are most plentiful.
What does it do to the inference? The Poisson standard error of the slope is point zero two one: it believes each big town is a nearly exact measurement. Robert Wedderburn's quasi-likelihood of 1974 keeps the estimating equations and scales the variance by the dispersion: the standard error grows by the square root of twenty-two, to point one oh. The sandwich standard error of Part 12 allows heteroskedasticity under independent towns and a correct mean model, giving point one eight, larger still, because here the variance isn't proportional to the mean. All three share the same estimate. With a correct conditional mean and independent towns, overdispersion can leave the coefficient consistent and makes its Poisson standard error wrong by a factor of eight.
The remedies. Quasi-Poisson, a quick fix when the variance is roughly proportional to the mean. The negative binomial, a Poisson whose rate is itself gamma-distributed, with variance mu plus mu squared over k, exactly our simulation's structure; Major Greenwood and George Udny Yule used it in 1920 for accident counts among munitions workers. Sandwich standard errors, asymptotically valid with a correct mean, independent units, finite moments and no dominating town; it does not repair dependence or mean-model bias. Or random effects, which model the towns' differences directly, Part 25. And always check before trusting a Poisson standard error: the dispersion, the deviance against its degrees of freedom, and the residuals against the fitted means.
The Coverage Board, with eight rows. First, the logistic intervals: twenty-three flights at the Challenger temperatures, simulated ten thousand times from the fitted curve. In about two percent of samples the zeros and ones are completely or quasi-separated by temperature, and no finite estimate exists; those count as misses for Wald, while a likelihood-ratio confidence set can still be checked directly using the correct likelihood supremum. For the slope, the Wald interval covers ninety-five point three percent: kept, even with the separated samples counted against it. The profile interval covers ninety-one point six: broken. For the probability at thirty-one degrees, the same pattern: Wald ninety-five point three, profile ninety-one point five. So at twenty-three flights it's the profile likelihood interval that falls short, because the chi-squared calibration of the likelihood ratio is itself a large-sample result, while the Wald interval here is saved by being very wide. Small samples keep asymptotic theory honest, and Part 16's bootstrap and Part 22's corrections return to this. Then the Poisson rate ratio on the two hundred towns. With truly Poisson counts, the classical interval keeps its promise. With the towns' extra variation, it covers less than a fifth of the time. Quasi-Poisson repairs part of the damage, about two thirds; the sandwich covers about ninety-one percent: better, still short with two hundred towns. The right fix depends on getting the variance right, and Part 24 returns to it.
Numbers: φ̂ = 22.3; slope SE 0.021 (Poisson), 0.101 (quasi), 0.179 (sandwich)
7Two-way tablesBachelor's4 min
In the autumn of 1973, the graduate division of the University of California at Berkeley received thousands of applications. Here are the six largest departments together: of two thousand six hundred and ninety-one men, forty-four and a half percent were admitted; of one thousand eight hundred and thirty-five women, thirty point four percent. The graduate division's associate dean, Eugene Hammel, worried that the university could be sued for discrimination, asked the statistician Peter Bickel to look at the data. Their analysis, published in Science in 1975 with J. William O'Connell, is one of the most famous in statistics. We'll start where anyone would: with this table.
Is admission independent of sex? If it were, each cell's expected count would be its row total times its column total, over the grand total. Pearson's chi-squared statistic, from Part 10, adds up the squared gaps between observed and expected counts, each divided by the expected count. Here it's ninety-two, on one degree of freedom, a p-value of about ten to the minus twenty-one. Fisher's exact test, conditioning on the table's margins, agrees. Whatever is going on, these counts strongly disagree with the aggregate independence model. The question is what it is.
Three ways to say how different the two proportions are. The risk difference: forty-four and a half minus thirty point four, fourteen percentage points. The relative risk: men were one point four seven times as likely to be admitted. And the odds ratio: the odds of admission for men, divided by the odds for women, a d over b c in the table's letters: one point eight four. Its log has a simple standard error, the square root of the sum of the reciprocals of the four counts, which Barnet Woolf gave in 1955. Why have three measures, and why do statisticians love the odds ratio?
Hold the odds ratio fixed at two, and vary the baseline risk. The relative risk isn't fixed: when the outcome is rare, a few percent, the two nearly agree, but when it's common, an odds ratio of two can mean a relative risk of only one point three. Reporting an odds ratio as if it were a relative risk exaggerates effects on common outcomes, a classic error in medical journalism. So why use odds ratios at all? They're what logistic regression estimates, and, as chapter ten will show, they survive a way of collecting data that relative risks don't.
The table is also a logistic regression: admission on a single dummy variable for women. The fitted coefficient is minus point six one, the difference in log-odds. Exponentiate its negative and you get one point eight four, the table's odds ratio, exactly. A two-by-two table is logistic regression on one dummy, and that's the door through which other variables can enter. At Berkeley, one variable changes everything.
The chi-squared test isn't limited to two-by-two tables. For a table with r rows and c columns, the same sum has r minus one times c minus one degrees of freedom. Cross the six departments with admission: chi-squared of seven hundred and seventy-nine on five degrees of freedom. The departments admitted at wildly different rates. Cross sex with department: over a thousand. Men and women applied to very different departments. A variable tied strongly both to the outcome and to the group being compared: those are the ingredients of the next chapter.
Numbers: men 44.5% vs women 30.4%; X² = 92.2; OR 1.84 [1.62, 2.09], RR 1.47; dept × admission X² = 779, sex × dept 1,068
8Simpson's paradoxBachelor's3 min
Admissions at Berkeley were decided by each department, so break the table down by department. In department A, eighty-two percent of women were admitted and sixty-two percent of men. In B, D and F, women also did as well as or better than men. In C and E, men were slightly ahead, by a few points. Department by department, there's no sign of the fourteen-point gap against women. If anything, it points the other way.
So where does the gap come from? Look at where each sex applied, with the departments ordered by their overall admission rate. More than half of the men applied to A and B, which admitted most of their applicants. Most women applied to C, D, E and F, which admitted few of anyone. Department F admitted six percent of its applicants, men and women alike. Women were concentrated in the departments that were hardest to enter.
A mosaic plot shows it all at once. Each column is a department; its width is the number of applications, and the coloured part is the share admitted. Men on the left, women on the right. Most department rates are much closer than the pooled comparison; department A is an exception with a large gap. What differs is the widths. The men's picture is dominated by the wide, mostly coloured columns A and B; the women's by the wide, mostly dark columns C to F.
The arithmetic is simple. The men's overall admission rate is a weighted average of the department rates, weighted by where the men applied. The women's is a weighted average of theirs, weighted by where the women applied. The weights differ. So the averages can differ by fourteen points in one direction while the rates, department by department, lean the other way. Edward Simpson described the reversal in 1951; George Udny Yule had noticed it in 1903. Part 1 met it in the World's clinic, and Part 12 as omitted-variable bias.
Bickel, Hammel and O'Connell concluded that the admissions committees, taken together, showed little evidence of an overall within-department disadvantage for women. These aggregate counts alone cannot establish the absence of discrimination. The aggregate gap arose because women applied in larger numbers to departments that were crowded and had few places. That raises its own questions, about the earlier choices and the funding that shaped those applications, and admissions mechanisms; a causal conclusion needs more than these counts. Which table is right depends on the question being asked. Deciding which variables to condition on is a causal question, and Parts 35 and 36 give the tools, diagrams among them, for answering it.
Numbers: A: women 82% vs men 62%; women ahead in 4 of 6
9Three-way tablesMaster's4 min
The Berkeley data are a three-way table: sex, by admission, by department. Slice it into six two-by-two tables and compute each department's odds ratio, men's odds of admission over women's. Five departments sit near one. Department A, where women did much better, sits well below. The pooled table's odds ratio, one point eight four, is higher than every single department's. We'd like a single summary of the association between sex and admission within departments, which pools the six tables without letting the departments' different sizes and rates distort it.
Each department has its own odds ratio, a d over b c. Nathan Mantel and William Haenszel's 1959 estimator pools them: add up a d over n across the strata, add up b c over n, and divide. It's a weighted average of the departments' odds ratios, robust when some strata are small. For Berkeley it's point nine oh five: within departments, men's odds of admission were slightly lower than women's. Turned around, women's odds were about eleven percent higher. The pooled table's one point eight four against women has become one point one one in their favour.
And a test. In each department, condition on the margins, as in Fisher's exact test: the count of admitted men then has a known expected value and a hypergeometric variance. The Cochran–Mantel–Haenszel statistic adds up the deviations across departments before squaring, so that consistent small effects accumulate and opposite ones cancel. For Berkeley it's one point five two, p equals point two two: no clear common directional association after stratification. Opposite associations can cancel, so this does not establish independence in every department. The p of ten to the minus twenty-one has evaporated.
The same conclusion comes from logistic regression with a dummy for each department, so each department gets its own baseline log-odds. The coefficient for women is now plus point one oh. The sign has flipped. As an odds ratio, one point one oh, with an interval from about point nine four to one point three: close to Mantel and Haenszel's estimate. Without the department dummies it was minus point six one. Leaving out the department, a variable related both to sex, through where people applied, and to admission, changes the comparison. Unlike linear regression, odds ratios are also noncollapsible: marginal and conditional ORs may differ without confounding, so Part 12's linear bias identity does not transfer.
A pooled odds ratio summarizes well only if the strata roughly agree. Test that: do all six departments share one odds ratio? Norman Breslow and Nicholas Day's test says no: chi-squared of eighteen point eight on five degrees of freedom, p of point zero zero two. Leave out department A and the other five are entirely consistent with a common odds ratio. Removing A is exploratory, since the data suggested it. A descriptive summary has two parts: in the selected five, no clear common association between sex and admission; in department A, women were admitted at a notably higher rate than men. Neither part shows the bias the pooled table seemed to.
Mantel and Haenszel weren't thinking about admissions. They worked at the National Cancer Institute, and their 1959 paper was about retrospective studies of disease, building on William Cochran's work of 1954. Their setting was patients with a disease and comparable people without it, stratified by age and other factors. In that setting the odds ratio isn't just convenient. It's a disease odds ratio identifiable without knowing the case/control sampling fractions. That's the next chapter. Their paper became one of the most cited in epidemiology.
Numbers: OR_MH = 0.905; CMH X² = 1.52, p = 0.22; women's adjusted log-odds +0.100 (SE 0.081) vs −0.610 pooled; Breslow–Day 18.8, p = 0.002 (without A: 2.6, p = 0.63)
10Case-control studiesPhD5 min
In 1950 Richard Doll and Austin Bradford Hill published a study of patients with lung cancer in twenty London hospitals. Each patient was matched with another patient, of the same sex and age group, who did not have lung cancer, and everyone was asked about their smoking. Among six hundred and forty-nine men with lung cancer, only two had never smoked. Among the six hundred and forty-nine controls, twenty-seven had never smoked. The crude aggregated odds ratio is fourteen. Inference for the matched design requires the paired or matched-stratum data, so this marginal table alone does not justify an unmatched confidence interval or Fisher test. But notice what the design fixed: the number of people with cancer. So what can such a study estimate?
The study can't estimate the risk of lung cancer for a smoker: it decided for itself that half its subjects would have cancer. What it measures directly is the odds of having smoked, among cases and among controls, and their ratio, a d over b c. The ratio we actually want compares the odds of being a case among smokers and among non-smokers. Write it out in the table's letters, and it's the same a d over b c. The odds ratio is symmetric: it doesn't care which margin was fixed by the design. Jerome Cornfield pointed this out in 1951, and it's why case–control studies report odds ratios.
The same is true with regression. Suppose that in the population, the log-odds of disease are linear in a risk factor x. Sample the cases at one rate and the controls at another, the rates depending only on the outcome. By Bayes's rule, among the sampled people the log-odds are still linear in x, with the same slope; only the intercept shifts, by the log of the ratio of sampling rates. So an ordinary logistic regression on case–control data consistently estimates the population logistic slopes with asymptotically valid model-based standard errors under the stated regularity and sampling assumptions, as Ross Prentice and Ronald Pyke proved in 1979. Without sampling fractions or external prevalence, the baseline risk is not identifiable; matched or exposure-dependent sampling needs a design-appropriate analysis.
Check it on the World, where we know the truth. Among all seven hundred and forty thousand adults, the log-odds of the silent condition rise by point four five per decade of age. A cohort of forty thousand random adults contains three hundred and seventy-three cases, and estimates point four nine. A case–control study takes four hundred cases and four hundred controls, and estimates point four one. Both slopes are within about one and a half standard errors of the truth. The case–control intercept is off by four point six eight, and the theory predicted four point six three: the log of the sampling-rate ratio. And look at the precision: eight hundred people, chosen on the outcome, give a standard error only forty percent larger than forty thousand people chosen at random. For a rare disease, that's why case–control studies exist.
Here's what the case–control sample looks like: the ages of the four hundred controls and the four hundred cases. The cases are older, and that shift is what the slope measures. The fifty-fifty split between cases and controls is the design's choice, and says nothing about how common the condition is. In the World, it affects about one adult in a hundred.
For a rare disease, chapter seven showed that the odds ratio is close to the relative risk. So a case–control study can estimate how much a factor multiplies the risk of a rare disease, with a few hundred subjects instead of a cohort of hundreds of thousands followed for decades. Its weak point isn't the arithmetic. It's the controls: do they represent the exposure distribution in the source population that generated the cases, within the chosen strata? And people with a disease may remember their past differently. Doll and Hill knew this, and in 1951 began following forty thousand British doctors forward in time. The cohort confirmed the case–control result, and then some.
Numbers: Doll & Hill crude aggregate OR 14.0; matched inference requires matched-stratum data; World slopes 0.451 (all), 0.493 (cohort of 40,000), 0.411 (400 + 400); intercept shift 4.68 vs 4.63 predicted
11Scoring predictionsPractice6 min
Logistic regression produces probabilities. How do you judge a probability forecast? Fit risk models for the World's silent condition on fifty thousand adults, and judge them on fifty thousand others. Model one uses age alone. Model two adds the results of Part 2's two screening tests. And a third, deliberately bad, model takes model one's forecasts and multiplies every risk's odds by four. The condition affects one adult in a hundred. Which forecasts are good, and in what sense?
The first question is ranking: does the model give higher risks to the people who have the condition? Choose a threshold, and call everyone above it positive. Record the fraction of cases caught, the true-positive rate, against the fraction of healthy people wrongly flagged, the false-positive rate, and slide the threshold from top to bottom. That traces the receiver operating characteristic curve, a name from radar in the Second World War. Age alone gives a curve bowed modestly above the diagonal: an area under the curve of point seven two five. With the two tests the curve hugs the top-left corner: point nine nine two. A coin would give the diagonal, an area of a half.
The area under the curve has a lovely meaning: pick one person with the condition and one without, at random; the AUC is the probability that the model gives the case a higher score, plus half the probability of a tie. It's the Mann–Whitney statistic of Part 16, scaled. For age alone, point seven two five: its ranking credit is about three quarters, counting an age tie as half. But the deliberately bad model, with every risk's odds quadrupled, has exactly the same AUC, because multiplying the odds doesn't change anyone's rank. The AUC can't tell whether the probabilities mean what they say.
The second question is calibration: do the probabilities mean what they say? Sort the test set into ten groups by forecast risk, and plot each group's average forecast against the fraction who actually had the condition. Model one's points lie along the diagonal: when it says two percent, about two percent have the condition. This binned check is compatible with calibration, subject to sampling error; it does not prove calibration at every forecast value. The odds-quadrupled model's points lie far to the right: it forecasts too high everywhere, by up to four times. A forecast of ten percent should come true one time in ten. A doctor, an insurer or a launch director acting on these numbers needs that, and the AUC doesn't check it.
One number can judge both at once. Glenn Brier's 1950 score for weather forecasts is the average squared difference between the forecast probability and what happened, one or zero. Lower is better. A forecaster who always says the training prevalence, point nine percent, scores point zero zero nine nine. Age alone improves on that only slightly: age is a weak predictor of a rare condition. The odds-quadrupled model scores worse than the constant training-prevalence forecast, though it ranks people exactly as well as model one: its miscalibration costs more than its ranking gains. With correctly encoded screening tests, the score falls to about point zero zero three four five, roughly a third of the baseline.
Why squares? If the true chance is p and you forecast q, your expected Brier score is q minus p squared, plus a term you can't control. It's smallest when q equals p: the score rewards forecasting exactly what you believe. That makes it a proper scoring rule. Allan Murphy showed in 1973 that the population Brier score splits into three parts, conditioning on the forecast: reliability, which is calibration; resolution, how much the forecasts vary with the outcome; and the uncertainty of the base rate itself. The logarithmic score, minus the log of the probability given to what happened, is also proper, as I. J. Good noted in 1952. For individual Bernoulli outcomes, summing it gives half the deviance, so maximum likelihood is fitting by the log score. Part 34 returns to prediction with guarantees.
Finally, a forecast becomes an action through a threshold. Flag everyone whose risk exceeds t, trading missed cases against false alarms; each point on the ROC curve is one threshold. If a false alarm costs one unit and a missed case costs another, the best threshold is the ratio of the false alarm's cost to the sum of both. If missing a case is ninety-nine times worse than a false alarm, flag anyone whose risk exceeds one percent. The threshold is a decision about costs, not a property of the data, and the rule only works if the probabilities are calibrated. A model with a fine AUC but inflated risks would flag far too many people.
Numbers: AUC 0.725 (age), 0.992 (age + tests); Brier 0.00990 (training-prevalence forecast, 0.9%), 0.00983 (age), 0.01099 (odds × 4), 0.00345 (with tests)
Recap, problems, and the road aheadAll tracks3 min
Part fourteen in thirteen lines. On the eve of the Challenger launch, a chart without the flights that had no damage hid the effect of cold. Least squares on zeros and ones gives impossible probabilities. Logistic regression makes the log-odds linear, so its coefficients are log odds ratios, and the logit and probit agree where the data are. Maximum likelihood is fitted by iteratively reweighted least squares, and deviances compare models, with both likelihood-ratio and Wald calibrations requiring checking. At thirty-one degrees the fit gives point nine nine nine six, with a profile interval from point eight to one, but that number lives in the model's tail. Poisson regression models rates through an offset, and overdispersion makes its standard errors far too small. Tables have chi-squared tests, odds ratios and relative risks, and Berkeley's admissions reverse when departments are separated. Mantel and Haenszel pool strata, and case–control studies estimate odds ratios by sampling on the outcome. Finally, a forecast is judged by its ranking, its calibration and its Brier score.
Where it comes back. The next part reads probabilities as degrees of belief. Exact and rank tests and the bootstrap arrive in Part 16. Generalized linear models get their full theory in Part 24, and mixed models for clustered counts in Part 25. Choosing models, classification and prediction with guarantees come in Parts 19, 28 and 34; the causal reading of tables in Parts 35 and 36; and missing data and measurement error, which haunt every case–control study, in Part 41.
Six problems, with full solutions in the README. Reading the Challenger coefficients; the logistic score and Hessian; a rate ratio with its interval; the kidney-stone version of Simpson's paradox; the symmetry of the odds ratio; and the Brier score of a constant forecast. Pause here if you want to try them.
The books and papers this part follows: Agresti's Categorical Data Analysis, McCullagh and Nelder, Hosmer and Lemeshow, Tufte, and Breslow and Day, with the papers from Berkson to Prentice and Pyke.
Fourteen parts of sixty-five, the fourth of Stage II. We can regress yes-or-no outcomes and counts, interpret tables with their assumptions, and judge a forecast. All along, probability has described data: how often things happen. But the engineers at that teleconference were really arguing about a degree of belief in a single launch. Around the middle of the eighteenth century a Presbyterian minister, Thomas Bayes, imagined a ball rolled on a table, and showed how to put a probability on something you cannot see. Part 15: first Bayes.
Where it goes next. The Challenger posterior is computed on a grid in Part 15; exact tests arrive in Part 16; GLMs get their full theory in Part 24 and clustered counts in Part 25; the causal reading of tables comes in Parts 35 and 36, and classification and scoring return in Parts 19 and 34.
Key results
The part's results in one place, for revision.
Try it
Lab 14 · The Challenger fit, and what sampling on the outcome preserves
Fit distress against launch temperature on all 23 flights by IRLS and check it against a direct maximization; then draw 400 cases and 400 controls from a simulated cohort, 300 times, and compare the slope and the intercept with what the theory of case-control sampling predicts.
python -m videos.stats.labs 14
needs numpy, scipy, matplotlib · download lab14.py ·
source on GitHublogit p-hat = b0 + b1 T 15.04 -0.232 T (direct maximization 15.04 -0.232 T)
log-likelihood after each IRLS step -15.94 -10.59 -10.18 -10.16 -10.16
p-hat at 31 F: least squares, logistic 1.75, 0.9996 (Wald interval on the logit scale [0.48, 1.00])
odds ratio per 10 F colder 10.2
cohort of 200,000: cases, slope 3966, 0.507 (truth 0.5)
400 + 400 case-control: mean slope 0.503 (sd across samples 0.074)
intercept shift, case-control minus cohort 3.90 (predicted log(pi1/pi0) = 3.90)
Sampling on the outcome moves only the intercept, by the log ratio of the sampling fractions: the slope, a log odds ratio, is the same in the cohort and in the case-control study.
The code (86 lines; it asserts its own result)
"""Lab 14: fit the Challenger flights by logistic regression, then check that a case-control sample keeps the slope."""
import numpy as np
from scipy import optimize
from videos.coursekit import labs
from explainer.stats import museum
from explainer.stats.kit import glm
TITLE = "The Challenger fit, and what sampling on the outcome preserves"
GOAL = ("Fit distress against launch temperature on all 23 flights by IRLS and check it against a direct "
"maximization; then draw 400 cases and 400 controls from a simulated cohort, 300 times, and compare the "
"slope and the intercept with what the theory of case-control sampling predicts.")
TASKS = [
"Fit only the flights at 66 F or warmer. What happens to the slope's standard error and to the interval at 31 F?",
"Fit the number of distressed rings out of 6 (n_trials=6) instead of any distress. How does p-hat at 31 F per ring compare?",
"Draw 400 cases and 4,000 controls instead. Predict the intercept shift before you run it.",
]
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# ---- the 23 flights ------------------------------------------------------------------------------------
temp = np.array(museum.CHALLENGER_TEMP, float)
y = (np.array(museum.CHALLENGER_DISTRESS) > 0).astype(float)
X = np.column_stack([np.ones_like(temp), temp])
fit = glm.logistic(X, y)
nll = lambda b: float(np.sum(np.logaddexp(0.0, X @ b) - y * (X @ b))) # noqa: E731
direct = optimize.minimize(nll, np.zeros(2), method="Nelder-Mead", options={"xatol": 1e-9, "fatol": 1e-12, "maxiter": 4000})
path = [-nll(b) for b in fit.path]
line = np.linalg.lstsq(X, y, rcond=None)[0]
x31 = np.array([1.0, museum.CHALLENGER_LAUNCH_F])
p31 = float(fit.predict(x31))
lo, _, hi = fit.predict_ci(x31)
lab.row("logit p-hat = b0 + b1 T", f"{fit.coef[0]:.2f} {fit.coef[1]:+.3f} T (direct maximization {direct.x[0]:.2f} {direct.x[1]:+.3f} T)")
lab.row("log-likelihood after each IRLS step", " ".join(f"{v:.2f}" for v in path[:5]))
lab.row("p-hat at 31 F: least squares, logistic", f"{float(x31 @ line):.2f}, {p31:.4f} (Wald interval on the logit scale [{lo[0]:.2f}, {hi[0]:.2f}])")
lab.row("odds ratio per 10 F colder", f"{np.exp(-10 * fit.coef[1]):.1f}")
assert np.allclose(fit.coef, direct.x, atol=2e-3), "IRLS finds the maximum of the likelihood"
assert all(b >= a - 1e-9 for a, b in zip(path, path[1:])), "every IRLS step raises the likelihood"
assert abs(fit.coef[0] - 15.04) < 0.01 and abs(fit.coef[1] + 0.232) < 0.001 and abs(path[0] + 15.94) < 0.01
assert float(x31 @ line) > 1 and 0.999 < p31 < 1, "the line leaves [0, 1]; the logistic curve cannot"
# ---- a cohort, and case-control samples from it --------------------------------------------------------
N, b0, b1, m, reps = 200_000, -4.0, 0.5, 400, 300
x = rng.standard_normal(N)
d = rng.random(N) < 1 / (1 + np.exp(-(b0 + b1 * x)))
D = np.column_stack([np.ones(N), x])
cohort = glm.logistic(D, d.astype(float))
cases, controls = np.flatnonzero(d), np.flatnonzero(~d)
shift = np.log((m / len(cases)) / (m / len(controls))) # log of the ratio of sampling fractions
cc = np.empty((reps, 2))
for r in range(reps):
idx = np.r_[rng.choice(cases, m, replace=False), rng.choice(controls, m, replace=False)]
cc[r] = glm.logistic(D[idx], d[idx].astype(float)).coef
slope = cc[:, 1].mean()
lab.row("cohort of 200,000: cases, slope", f"{len(cases)}, {cohort.coef[1]:.3f} (truth {b1})")
lab.row("400 + 400 case-control: mean slope", f"{slope:.3f} (sd across samples {cc[:, 1].std(ddof=1):.3f})")
lab.row("intercept shift, case-control minus cohort", f"{cc[:, 0].mean() - cohort.coef[0]:.2f} (predicted log(pi1/pi0) = {shift:.2f})")
lab.note = ("Sampling on the outcome moves only the intercept, by the log ratio of the sampling fractions: the "
"slope, a log odds ratio, is the same in the cohort and in the case-control study.")
assert abs(slope - cohort.coef[1]) < 0.03 and abs(slope - b1) < 0.06, "the slope survives outcome-dependent sampling"
assert abs(cc[:, 0].mean() - cohort.coef[0] - shift) < 0.05, "the intercept shifts by log(pi1/pi0)"
assert abs(cc[:, 0].mean() - cohort.coef[0]) > 3, "and the shift is large: risks cannot be read off"
fig, ax = labs.figure(2, size=(11, 4.2))
grid = np.linspace(28, 84, 200)
G = np.column_stack([np.ones_like(grid), grid])
jitter = np.where(y > 0, -1, 1) * 0.012 * (np.arange(len(y)) % 4)
ax[0].scatter(temp, y + jitter, s=22, color=labs.BLUE, zorder=3, label="23 flights (1 = distress)")
ax[0].plot(grid, fit.predict(G), color=labs.GOLD, label="logistic fit")
ax[0].plot(grid, G @ line, color=labs.RED, ls="--", label="least squares line")
ax[0].axvline(31, color=labs.MUTED, ls=":", lw=1)
ax[0].text(31.8, 0.42, "forecast 31 F", color=labs.MUTED, fontsize=9)
ax[0].set(title="Challenger: any O-ring distress against temperature", xlabel="launch temperature (F)",
ylabel="probability of distress", ylim=(-0.35, 1.85))
ax[0].legend(loc="upper right")
ax[1].hist(cc[:, 1], bins=30, color=labs.BLUE, alpha=0.7, label="slopes of 300 case-control fits")
ax[1].axvline(cohort.coef[1], color=labs.GOLD, lw=2, label=f"the cohort's slope {cohort.coef[1]:.3f}")
ax[1].axvline(b1, color=labs.MUTED, ls="--", lw=1, label=f"truth {b1}")
ax[1].set(title="Case-control sampling keeps the slope", xlabel="fitted slope (log odds ratio per unit of x)", ylabel="samples")
ax[1].legend(loc="upper right")
ax[1].set_ylim(0, ax[1].get_ylim()[1] * 1.35)
lab.fig = fig
return lab
Now change it
- Fit only the flights at 66 F or warmer. What happens to the slope's standard error and to the interval at 31 F?
- Fit the number of distressed rings out of 6 (n_trials=6) instead of any distress. How does p-hat at 31 F per ring compare?
- Draw 400 cases and 4,000 controls instead. Predict the intercept shift before you run it.
Problems, with solutions
Try each problem before opening its solution.
1. Reading the Challenger coefficients. With \(\text{logit}\,p = 15.04 - 0.232\,T\): find \(p\) at \(60^\circ\)F, and the odds ratio for \(10^\circ\)F colder.
Solution
At 60 °F, η = 15.04 − 0.232 × 60 = 1.11, so p = 1/(1 + e^(−1.11)) = 0.75. Ten degrees colder changes the log-odds by +2.32, so the odds multiply by e^2.32 = 10.2.
2. The logistic score and Hessian. For logistic regression, derive the score \(X^\top(y - p)\) and the Hessian \(-X^\top W X\), \(W = \mathrm{diag}(p_i(1 - p_i))\).
Solution
ℓ(β) = Σ[yᵢηᵢ − log(1 + e^ηᵢ)], with ηᵢ = xᵢᵀβ.
- Score: ∂/∂β of log(1 + e^η) is pᵢxᵢ, so ∇ℓ = Σ(yᵢ − pᵢ)xᵢ = Xᵀ(y − p).
- Hessian: ∂pᵢ/∂β = pᵢ(1 − pᵢ)xᵢ, so ∇²ℓ = −Σpᵢ(1 − pᵢ)xᵢxᵢᵀ = −XᵀWX.
The Hessian is negative definite whenever X has full rank, so ℓ is concave and the maximum is unique when it exists.
3. A rate ratio. 30 events in 10,000 person-years exposed, 20 in 20,000 unexposed: the rate ratio and a 95% Wald interval.
Solution
RR = (30/10,000)/(20/20,000) = 3. Then SE(log RR) = √(1/30 + 1/20) = 0.289. The 95% interval is 3 × e^(±1.96 × 0.289) = [1.70, 5.28].
4. Kidney stones (Charig et al., BMJ 1986).
Solution
- Small stones: A cures 93%, B 87%.
- Large stones: A cures 73%, B 69%.
- In total: A cures 273/350 = 78%, B 289/350 = 83%.
A is better for both kinds of stone. B looks better in total because it was given mostly small stones, which are easier to cure: 270 of B's 350 patients, against 87 of A's. Stone size affected both which treatment was used and the chance of a cure, so compare within stone size.
5. The odds ratio's symmetry. Show that the odds ratio of a \(2\times2\) table is the same whether you compare rows or columns.
Solution
Comparing rows gives (a/b)/(c/d) = ad/(bc). Comparing columns gives (a/c)/(b/d) = ad/(bc), the same.
6. The Brier score of a constant forecast. A constant forecast \(q\) for a condition of prevalence \(\pi\): show the expected Brier score is \((q - \pi)^2 + \pi(1 - \pi)\).
Solution
E[(q − y)²] = q² − 2qπ + E[y²]. Since E[y²] = π, this equals q² − 2qπ + π = (q − π)² + π(1 − π). It is smallest at q = π, so the score is proper. The minimum is π(1 − π), which is 0.0099 for π = 0.01: the "always 1%" forecaster of chapter 11.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| probabilities as beliefs | 15 |
| exact and permutation tests, the bootstrap | 16 |
| likelihood theory: Wald, score and LR; Hauck–Donner | 22 |
| GLMs in full: exponential families, quasi-likelihood | 24 |
| random effects for clustered counts | 25 |
| classification, cross-validation | 19, 28 |
| calibration and prediction with guarantees | 34 |
| causal readings of tables | 35, 36 |
| missing data and measurement error | 41 |
| the Coverage Board | every part; 65 |
Sources
- Challenger.
- Report of the Presidential Commission on the Space Shuttle Challenger Accident (1986).
- S. Dalal, E. Fowlkes & B. Hoadley, JASA 84 (1989); M. Lavine, JASA 86 (1991).
- E. Tufte, Visual Explanations (1997), ch. 2.
- Logistic and Poisson regression.
- J. Berkson, JASA 39 (1944); C. Bliss, Science 79 (1934); D. Cox, JRSS B 20 (1958).
- J. Nelder & R. Wedderburn, JRSS A 135 (1972); R. Wedderburn, Biometrika 61 (1974).
- M. Greenwood & G. U. Yule, JRSS 83 (1920).
- Tables.
- P. Bickel, E. Hammel & J. W. O'Connell, Science 187 (1975); E. Simpson, JRSS B 13 (1951); G. U. Yule, Biometrika 2 (1903).
- B. Woolf, Ann. Hum. Genet. 19 (1955); W. Cochran, Biometrics 10 (1954); N. Mantel & W. Haenszel, JNCI 22 (1959).
- N. Breslow & N. Day, Statistical Methods in Cancer Research I (1980).
- Case–control studies. R. Doll & A. B. Hill, BMJ 2 (1950); J. Cornfield, JNCI 11 (1951); R. Prentice & R. Pyke, Biometrika 66 (1979).
- Scoring.
- G. Brier, Monthly Weather Review 78 (1950); A. Murphy, J. Appl. Meteor. 12 (1973).
- I. J. Good, JRSS B 14 (1952); J. Hanley & B. McNeil, Radiology 143 (1982).
- Textbooks.
- A. Agresti, Categorical Data Analysis (3rd ed., 2013).
- P. McCullagh & J. Nelder, Generalized Linear Models (2nd ed., 1989).
- D. Hosmer, S. Lemeshow & R. Sturdivant, Applied Logistic Regression (3rd ed., 2013).
About this partfrom its README
Part 14 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Parts 12 and 13 assumed measurements. This part regresses yes-or-no outcomes and counts, and reads tables.
It opens on 27 January 1986: the Challenger teleconference, and a chart of the seven flights with O-ring distress (r = 0.02). Adding the sixteen flights with no distress shows the effect: every one launched at 66 °F or warmer. From there the part covers:
- why least squares on 0/1 gives p̂(31) = 1.75, and where the linear probability model is still used;
- logistic regression: odds, log-odds and odds ratios; the latent-threshold picture; logit vs probit; the canonical link;
- maximum likelihood: the log-likelihood landscape, Newton's method as iteratively reweighted least squares (each step drawn), the deviance, and LR vs Wald;
- the Challenger fit with a dashboard:
- p̂(31 °F) = 0.9996;
- a Wald interval [0.48, 1] vs a profile interval [0.80, 1], with the profile log-likelihood drawn;
- the extrapolation caveat;
- Poisson regression with offsets on the World's screening condition by age and sex (the age effect found, the sex estimate consistent with no effect, without proving equality), and the rare-outcome link to logistic regression;
- overdispersion in the World's 200 towns: quasi-Poisson and sandwich SEs;
- two-way tables at Berkeley 1973: χ², risk difference, RR, OR with Woolf's interval, OR vs RR, r × c tables;
- Simpson's paradox: rates by department, application shares, mosaic plots, weighted averages;
- three-way tables: stratum odds ratios, Mantel–Haenszel, the CMH test, logistic regression with department dummies, Breslow–Day;
- case–control studies: Doll & Hill 1950, the odds ratio's symmetry, Prentice–Pyke, and a World cohort vs case–control check;
- scoring predictions: ROC and AUC, calibration, the Brier score, proper scoring rules, thresholds and costs.
Every number on screen is computed in compute.py or inline in a scene:
- the Challenger flights, the Berkeley admissions and Doll & Hill's counts come from the Museum;
- the screening condition, ages and towns are the World's (seed 1662);
- the clinic visits are simulated on the World's towns.
Built in this part:
-
statkit.glm(I) (explainer/stats/kit/glm.py):- logistic and Poisson regression by IRLS, with step-halving, offsets and binomial trials;
- classical, quasi and sandwich covariances; deviance and Pearson dispersion;
- Wald and profile-likelihood intervals (constrained IRLS with continuation);
- 2 × 2 measures with Woolf and Katz intervals, Mantel–Haenszel and CMH;
- ROC/AUC, the Brier score and calibration.
Everything is checked against statsmodels and SciPy in
tests/test_stats_kit_glm.py. -
The Challenger dashboard (
ChallengerDashboardinexplainer/stats/viz.py): the flights, the fitted curve with its Wald band, and a temperature probe that reads out p̂ and its interval.
The Coverage Board gains eight rows, all 95% intervals, R = 10,000.
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| logistic slope, Wald | Challenger temperatures, n = 23 | 95.34% | kept |
| logistic slope, profile likelihood | Challenger temperatures, n = 23 | 91.63% | broken |
| p at 31 °F, Wald (logit scale) | Challenger temperatures, n = 23 | 95.33% | kept |
| p at 31 °F, profile likelihood | Challenger temperatures, n = 23 | 91.46% | broken |
| Poisson rate ratio, classical SE | 200 towns, Poisson counts | 95.10% | kept |
| Poisson rate ratio, classical SE | 200 towns, gamma frailty | 17.56% | broken |
| Poisson rate ratio, quasi-Poisson SE | 200 towns, gamma frailty | 67.43% | broken |
| Poisson rate ratio, sandwich SE | 200 towns, gamma frailty | 90.61% | broken |
Notes on the logistic rows:
- In 205 of the 10,000 samples separation prevents a finite MLE: 115 are completely separated and 90 are quasi-separated at tied temperatures. They have no finite estimate, so they count as Wald misses.
- The likelihood-ratio confidence set is checked directly using the correct supremum, including the nonzero tied-outcome limit under quasi-separation: the likelihood-ratio statistic at the truth must fall below χ²₁(0.95).
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | 27 January 1986 | 7 flights with distress, r = 0.02; all 16 without at ≥ 66 °F; forecast 31 °F |
| 1 | Why not least squares | p̂ = 2.90 − 0.0374T; p̂(31) = 1.75, p̂(85) = −0.27 |
| 2 | Logistic regression | logit p̂ = 15.04 − 0.232T; p̂ = 0.5 at 64.8 °F; p̂(70) = 0.23, p̂(53) = 0.94; OR per 10 °F colder 10.2 [1.8, 173]; logit/probit 1.72 |
| 3 | Fitting by maximum likelihood | IRLS from 0: ℓ = −15.94, −10.59, −10.18, −10.158, …; D = 20.32 vs D₀ = 28.27, LR = 7.95, p = 0.0048; Wald z = −2.14, p = 0.032 |
| 4 | The Challenger fit | η̂(31) = 7.85, SE 4.04; Wald p ∈ [0.48, 1]; profile η ∈ [1.41, 18.4], p ∈ [0.80, 1]; binomial model: each ring 0.82 |
| 5 | Poisson regression | 7.7 per 1,000 at 50; rate ratio per decade 1.554 [1.535, 1.574]; men 0.986 [0.94, 1.03]; D = 31.0 on 25 df, φ̂ = 1.22 |
| 6 | Overdispersion | φ̂ = 22.3; slope SE 0.021 (Poisson), 0.101 (quasi), 0.179 (sandwich) |
| 7 | Two-way tables | men 44.5% vs women 30.4%; X² = 92.2; OR 1.84 [1.62, 2.09], RR 1.47; dept × admission X² = 779, sex × dept 1,068 |
| 8 | Simpson's paradox | A: women 82% vs men 62%; women ahead in 4 of 6 |
| 9 | Three-way tables | OR_MH = 0.905; CMH X² = 1.52, p = 0.22; women's adjusted log-odds +0.100 (SE 0.081) vs −0.610 pooled; Breslow–Day 18.8, p = 0.002 (without A: 2.6, p = 0.63) |
| 10 | Case–control studies | Doll & Hill crude aggregate OR 14.0; matched inference requires matched-stratum data; World slopes 0.451 (all), 0.493 (cohort of 40,000), 0.411 (400 + 400); intercept shift 4.68 vs 4.63 predicted |
| 11 | Scoring predictions | AUC 0.725 (age), 0.992 (age + tests); Brier 0.00990 (training-prevalence forecast, 0.9%), 0.00983 (age), 0.01099 (odds × 4), 0.00345 (with tests) |
| 12 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: 27 January 1986. The teleconference chart; all 23 flights (Dalal, Fowlkes & Hoadley 1989; Tufte 1997).
- Why not least squares on 0/1.
- Logistic regression. Log-odds; odds ratios; latent variables (probit vs logit).
- Fitting by maximum likelihood. Newton steps as weighted regressions (IRLS, intuition; theory in Part 24).
- The Challenger fit. The profile-likelihood interval at 31°F, and the extrapolation caveat.
- Poisson regression. Rates, offsets; Bortkiewicz by corps.
- Overdispersion, first look. When Poisson SEs are too small (Board).
- Two-way tables. χ² and Fisher's exact test; odds ratios and relative risks.
- Simpson's paradox. The Berkeley admissions (Bickel, Hammel & O'Connell 1975), with mosaic plots flipping.
- Three-way tables. Cochran–Mantel–Haenszel (1959).
- Case–control studies. Why logistic slopes survive outcome-dependent sampling; Doll & Hill (1950).
- Scoring predictions. ROC/AUC; calibration; the Brier score.
- Outro.
Built: a Challenger dashboard; statkit.glm (I). Data: Challenger; Berkeley.
Build the film
python -m videos.stats.stats14.compute # the part's numbers, into .cache/stats14
python tools/build.py stats14 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats14 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats14. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats14.compute # once (a few minutes; cached in .cache/stats14)
python tools/build.py stats14 -q l # fast 480p preview
python tools/build.py stats14 # 1080p30 -> renders/stats14.mp4
python tools/qa_scene.py stats14 ChallengerFit
python tools/lecture_length.py stats14 --floor 50