Borrowing Strength
How do you estimate many related things at once?
After their first 45 at-bats of 1970, eighteen major-league hitters each have a batting average, and Efron and Morris ask how to predict the rest of the season. Shrinking every average towards the common mean, by James and Stein's rule, cuts the total squared error by a factor of 3.5. The part explains why: the squared length of a noisy vector is too large on average, and Stein's lemma turns that into a risk below the MLE's for every true mean vector once there are three or more. Read as empirical Bayes, the rule estimates a normal prior from the data, and Tweedie's formula corrects the winner's curse. The same idea with a model is the random effect: variance components, the linear mixed model, Henderson's equations and the BLUP, whose shrinkage factor depends on each group's size, with REML repairing the bias of ML in the variances. The part then applies it to growth curves, crossed raters, the choice between fixed and random effects, GLMMs and the World's hospital league table, small areas, meta-analysis and the Rasch model.
What you need. The multivariate normal and quadratic forms (Part 4), and conjugate normal updating as in Part 15.
- Hook
- Efron–Morris baseball, 1975
- Mathematics
- James–Stein via SURE, empirical Bayes, random effects, BLUP, REML, GLMMs, small areas, meta-analysis
- Built
- statkit.mixed; a league table
What you will be able to do
Bachelor's
- Explain regression to the mean in a table of early-season averages, and why shrinking each towards the group mean predicts better in total.
Master's
- Derive the James-Stein risk from Stein's lemma and SURE, and show the rule is empirical Bayes under a normal prior.
- Write a linear mixed model as V = ZGZ' + R, derive the BLUP of a random intercept and its shrinkage factor, and fit it by REML.
- Compute a random-effects meta-analysis with DerSimonian-Laird and Hartung-Knapp intervals.
PhD
- Derive the half-and-half chi-squared mixture for a likelihood-ratio test of one variance on its boundary, and state the conditions under which it fails.
- State what the James-Stein guarantee covers (total expected squared error, known equal variances, p at least 3) and what it does not (any single coordinate).
Practice
- Choose between fixed and random effects with the within and between slopes, Mundlak's model and a Hausman test.
- Report shrunk estimates for league tables and small areas with intervals for ranks, and say which units gain and which lose from the pooling.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 6 min · Master's 50 min · PhD 54 min · Practice 18 min.
- 0Eighteen hitters, 1970Bachelor's3 min
- 1James-SteinMaster's4 min
- 2Empirical BayesMaster's4 min
- 3Random effectsMaster's3 min
- 4The linear mixed modelMaster's4 min
- 5ML vs REMLMaster's3 min
- 6InferencePhD4 min
- 7Longitudinal dataMaster's3 min
- 8Crossed and nested effectsMaster's4 min
- 9Fixed vs randomPractice4 min
- 10GLMMsMaster's5 min
- 11Small areasPractice4 min
- 12Meta-analysisPractice4 min
- 13Item response theoryMaster's3 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.
Eighteen hitters, 1970Bachelor's3 min
In 1975 Bradley Efron and Carl Morris took eighteen major-league baseball players after their first forty-five times at bat in the 1970 season, and asked how well each player's average so far predicts his average for the rest of the season. Roberto Clemente had eighteen hits in forty-five, a batting average of point four oh oh. Is he really a point four oh oh hitter? Nobody had hit that well over a whole season for almost thirty years.
Here are all eighteen early averages, from Clemente's point four oh oh down to Max Alvis's point one five six. And here is what each player actually hit over the rest of the season, between seventy and nearly six hundred more at-bats. The held-out season averages, themselves noisy, are bunched more tightly: the hot starts cooled and the cold starts warmed. Forty-five at-bats is a small sample, and sampling noise contributes substantially to their spread.
Our calculation first uses an arcsine transformation, with approximately unit sampling variance, and targets its grand mean. The dashed line is that target transformed back to batting averages. James–Stein retains about a fifth of each distance on the transformed scale, before we transform back. The amount is estimated from the spread of these eighteen observations. The normal-theory guarantee is approximate for these binomial data; the next plot evaluates held-out prediction directly.
Now compare with the rest of the season. Using each player's own average, the total squared error is point oh seven five. With James–Stein it is point oh two two: three and a half times smaller, and closer for fifteen of the eighteen players. Shrinking every estimate towards the others was better than trusting each one.
It sounds paradoxical. Each player's true ability is about that player alone, and his own hits are the direct evidence. Yet a joint estimate of Clemente's ability uses Max Alvis's hits too. For independent normal observations with known equal variance and at least three means, Stein proved the separate estimates inadmissible under expected total squared error. The theorem holds for every fixed vector of means; it does not require a common population. A population model gives a useful interpretation of borrowing strength in this baseball example. That is the idea of this part: borrowing strength.
Numbers: SSE 0.0753 vs 0.0215 (3.5×); closer for 15 of 18; B̂ 0.791
1James-SteinMaster's4 min
The setting: p means, each measured once with normal error of variance one. Judge an estimator by its risk, the expected total squared error. The obvious estimator, X itself, which is also the maximum likelihood estimate, has risk exactly p. Willard James and Charles Stein's estimator multiplies X by one minus p minus two over the squared length of X: the farther the data from zero, the less it shrinks. Shrinking towards the grand mean instead, as Efron and Morris did, costs one degree of freedom: p minus three. Strict improvement for this estimated target requires at least four means.
The squared length of X has expectation theta's squared length plus p: each coordinate contributes one unit of noise. It is the squared length that is too large by p, not the length itself. The best constant multiple of X uses the ratio of theta's squared length to that squared length plus p. Plugging in an estimate suggests shrinkage, but this heuristic is not the proof for an adaptive rule. The rigorous argument next gives p minus two and requires at least three dimensions.
The proof rests on Stein's lemma, an integration by parts against the normal density: the covariance of an error with a smooth function of X equals the expected derivative of that function. Write an estimator as X plus a sufficiently regular correction g, with integrable derivatives and risk. Expand the squared error and apply the lemma to the cross term: the risk is p plus the expected squared correction plus twice its expected divergence. Everything inside that expectation is computable from the data, so it is an unbiased estimate of the risk, Stein's unbiased risk estimate, SURE.
For James–Stein, the correction is minus p minus two over the squared length, times X. Its divergence works out to minus p minus two squared over the squared length. So SURE is p minus p minus two squared over the squared length of X. Taking expectations, the risk is p minus a positive quantity, for every theta whatsoever. The maximum likelihood estimate is beaten everywhere: it is inadmissible. The argument needs p minus two to be positive, which is why it starts at three.
Here are the risks, simulated for ten means, against how far the true means are from the shrinkage target. The maximum likelihood estimate's risk is ten, everywhere. James–Stein's is two when the truth is at the target, an eighty percent saving, and the positive-part version, which never shrinks past zero, does better still. As the truth moves away the advantage fades, but it never turns into a loss. Choose the target well, near where the means really are, and the saving is large.
Three cautions. The guarantee is for the total error: some individual players, the truly exceptional ones, can be estimated worse. James–Stein is itself inadmissible, since the positive part beats it. Any fixed target works, but a good one works much better. Why it works at all is clearest from the empirical Bayes view of the next chapter, and Part 45 develops the theory of admissibility in general.
Numbers: risk 2.02 (positive part 1.28) vs 10 at θ = 0
2Empirical BayesMaster's4 min
Part 15 showed that with a normal prior, the posterior mean pulls the observation towards the prior mean, by an amount set by the relative variances. It assumed the prior was known, or chosen. But when we face many parallel problems at once, eighteen hitters, four hundred schools, two hundred towns, the spread of the estimates themselves tells us what the prior must be. Estimating it from the data is empirical Bayes.
Suppose the true abilities come from a normal population with mean mu and variance tau squared, and each observation adds unit-variance noise. Bayes' posterior mean is mu plus one minus B times the distance from mu, with B equal to one over one plus tau squared. We don't know mu or tau squared, but the observations, averaged over the population, are normal with mean mu and variance one plus tau squared, so the data reveal both. For p greater than three, the untruncated ratio p minus three over the centered sum of squares is unbiased for B. Truncating it changes that property.
Plug that estimate into Bayes' rule and out comes exactly the James–Stein estimator shrinking towards the grand mean. Efron and Morris made this connection in 1973: Stein's mysterious estimator is Bayes with a prior estimated from the data. When the estimates are much more spread out than noise alone would make them, the prior is wide and they are left almost alone; when they spread no more than noise would, they are pulled almost all the way in. The eighteen early batting averages spread out only a little more than luck alone allows, so James–Stein kept just a fifth of each player's transformed-scale distance from the middle.
Herbert Robbins went further in 1956: the prior needn't be normal. With any prior, the data have a marginal density, the noise smeared over the prior. A remarkable identity, which Efron called Tweedie's formula, says the posterior mean is the observation plus the noise variance times the slope of the log marginal density. So it needs only the density of the data, which many parallel observations can help estimate, although derivatives in the tails remain difficult. Or estimate the prior itself, by Jack Kiefer and Jacob Wolfowitz's nonparametric maximum likelihood, Here we approximate it using finite iterations of EM on a fixed grid. This is not a certificate of the unrestricted optimum.
An example in the spirit of genomics: a thousand z-scores, ninety percent from true nulls and ten percent from real effects of various sizes. The nonparametric maximum likelihood prior, estimated from the z-scores alone, puts eighty-nine percent of its mass near zero, and much of the remainder in two fitted clumps. The generating nonnull effects were normal with standard deviation three, not concentrated at those two points.
Now select the ten largest z-scores, the discoveries. Their average is five point six one. But the true effects behind them average only five point oh seven: they were selected partly for being lucky. This is the winner's curse, and it's why the first report of a large effect is so often followed by smaller ones. Tweedie's formula, using the estimated prior, pulls the selected estimates back to an average of four point eight four. Because the correction comes from the whole distribution, it applies even after selection.
Numbers: NPMLE 89% at 0; top ten 5.61 / 5.07 / 4.84
3Random effectsMaster's3 min
The simplest model with a random effect: each pupil's score is an overall mean, plus a school effect shared by everyone in the school, plus the pupil's own deviation. The school effects are treated as random, a sample from a population of schools with variance tau squared. The total variance splits into the two components, as Ronald Fisher first did in 1918 for the inheritance of human traits. Their ratio is the intraclass correlation: the correlation between two pupils of the same school, Part 23's rho.
Six of the World's schools. Within each, pupils' scores spread widely. The school means differ from one another and from the unweighted average of all four hundred school means, but by much less than pupils differ within a school.
Fit the model to all twenty-four thousand pupils in the World's four hundred schools. The variance between schools is about seventeen hundred, a standard deviation of forty-two points. The variance within schools is about seventy-nine hundred, a standard deviation of eighty-nine. So eighteen percent of the variation in scores lies between schools. The World built school effects with a standard deviation of thirty-five; the intercept-only fitted component also includes differences in intake and programme assignment. It is a descriptive component, not an estimate of only the built-in school disturbance.
The oldest estimates come from Part 13's analysis of variance. The mean square within groups estimates sigma squared. The mean square between groups estimates sigma squared plus m times tau squared, because group means carry the school variance and a share of pupil noise. Subtract and divide by m, a method of moments. It has two flaws: it can come out negative, and when groups have different sizes there are many competing versions. Likelihood methods, the next two chapters, resolve both.
For the unweighted pupil mean under a common-ICC model, unequal cluster sizes matter. The exact design factor uses m star: the sum of squared school sizes divided by the total number of pupils. It reduces to the common size when schools are equal. The display substitutes the actual sizes and fitted ICC. The effective sample size shown applies to this mean under that covariance model; it is not a universal information count for every coefficient. A between-school variance is still learned from the four hundred schools, which is why few-school inference needs care.
Numbers: τ̂² 1,732, σ̂² 7,872, ICC 0.180; mean-specific unequal-size deff 11.84
4The linear mixed modelMaster's4 min
In general a linear mixed model has fixed effects beta, with design X, and random effects b, with design Z. The random effects are normal with covariance G, and the errors normal with covariance R, independent of b, usually sigma squared times the identity: Nan Laird and James Ware's formulation of 1982. Averaging the random effects away, the data have covariance V, Z G Z transpose plus R. So the fixed effects are estimated by Part 23's generalized least squares with that V, once G and R have been estimated.
Charles Henderson, a dairy geneticist ranking bulls by their daughters' milk yields, found a neater route in 1950: the mixed-model equations. They come from maximizing the joint density over beta and b, holding G and R fixed. Estimate covariance parameters separately by marginal likelihood or REML, which is least squares with a ridge penalty G inverse on the random effects, Part 19's ridge with the penalty estimated from the data. Their solution gives the GLS estimate of beta and, for each group, the best linear unbiased predictor of its random effect, the BLUP.
For a random intercept, the BLUP is simply each school's mean residual, shrunk. The shrinkage factor is the between-school variance over itself plus the variance of a school mean: signal over signal plus noise. A school with few pupils is pulled almost all the way back to the average school, and a school with many keeps its own estimate. This is James–Stein again, with a shrinkage that differs by school according to how much data it has: partial pooling.
Fit the World's forty sampled schools with the programme and home background as fixed effects and a random intercept for each school. The programme's coefficient has a standard error of twelve, against least squares' three point eight: the programme varies only between schools, so its information is in the forty schools, as Part 23 found with cluster-robust errors. Home background varies mostly within schools, and its standard error hardly changes. These model-based errors require suitable mean and covariance assumptions. This working mean omits school context; chapter nine investigates that omission.
Each school's mean residual, its empirical BLUP, and the centered realized school-plus-context deviation. With fifty to eighty-two pupils per school, the shrinkage factors are about point nine, so the BLUPs move only a little. Even so they are closer to the truth on average, a mean squared error of ninety-three against a hundred and one. Under the model, noisier group means can benefit more from shrinkage. An individual realized effect can still move in the wrong direction.
For a pupil in an observed school, add the school's empirical BLUP to the fixed-effect prediction. For a new pupil in an independent new school, prediction variance includes both school and pupil variation, plus fixed-effect uncertainty. A new school mean would instead average its pupil noise. The simple shrinkage error variance displayed assumes the fixed mean and variance components are known. Estimating beta adds uncertainty; estimating the variance components adds more. With estimated components these are empirical BLUPs. Their optimality relies on the stated mean and covariance assumptions.
Numbers: programme SE 3.8 → 12.1; MSE 101 → 93
5ML vs REMLMaster's3 min
Maximum likelihood versus REML. Maximum likelihood can substantially underestimate variance after fitting a mean. For one sample, dividing by n instead of n minus one underestimates by a factor of n minus one over n, because the mean was estimated. In regression the factor is n minus p over n. In a mixed model, the maximum likelihood estimate of the group variance makes the same mistake: it profiles over the fixed effects without a degrees-of-freedom correction. This resembles the nuisance-parameter problem, though a fixed number of coefficients is not the growing-parameter Neyman–Scott setting. Since the group variance is learned from the groups, the bias can be large with few groups; boundaries can also bias REML.
The cure is Part 22's: remove the nuisance parameters first. Take combinations of the data that cancel the fixed effects, error contrasts. Their distribution depends only on the variances. Its log likelihood, restricted maximum likelihood, is the ordinary log likelihood at the GLS estimate minus half the log determinant of X transpose V inverse X, as Desmond Patterson and Robin Thompson showed in 1971. For one sample it gives exactly the n minus one divisor.
Three hundred seeded data sets at each group count compare ML and REML. This illustration uses a normal-plus-Bernoulli random-intercept mixture with the variance marked in gold, so the Gaussian likelihood is a working model. With five groups, ML averages about point one four three. REML averages point two eight nine, closer to the true point two seven two five in this experiment. REML is not exactly unbiased for every component, especially at a boundary. ML is numerically near zero in about twenty-eight percent of samples. With forty groups the averages nearly agree. Compare different fixed-effect specifications using ML, since their restricted likelihoods use different contrasts.
So: REML for variance components, the default in most software. Maximum likelihood when comparing models with different fixed effects, by likelihood ratio or AIC, because restricted likelihoods with different fixed effects are built from different contrasts. Given the variances, both give the same GLS estimates. And REML has a Bayesian reading: it is proportional, for fixed X and a fixed normalization, to integrating beta against a flat prior. Its arbitrary improper-prior constant prevents comparing different fixed-effect spaces.
Numbers: 5 groups: 0.143 vs 0.289 (truth 0.2725); 28% zeros
6InferencePhD4 min
Inference for mixed models. The standard error of a fixed effect depends on estimated variance components, so the ratio of estimate to standard error isn't normal; it's roughly a t with some degrees of freedom nu. Franklin Satterthwaite's 1946 recipe chooses nu so that the estimated variance has the right mean and variance for a chi-squared, computing the latter by the delta method. For a balanced design and an effect that varies between groups, it gives the number of groups minus the rank of the between-group fixed-effect design. Within-group predictors need not each cost a group degree of freedom. Michael Kenward and James Roger's refinement also adjusts the covariance estimate and the F scaling as well as approximating degrees of freedom.
The Board: eight schools of twenty-five pupils, four with a treatment, and the treatment effect estimated by a mixed model. With the normal distribution's one point nine six, the intervals cover eighty-nine percent of the time: broken. With Satterthwaite's t, about six degrees of freedom here, they cover ninety-four: kept. Two hundred pupils, but only eight schools.
Testing whether a variance component is zero puts the hypothesis on the edge of the parameter space, the situation of Part 22's chapter nine. Under the null, the estimate is exactly zero about half the time, whenever the data happen to look less clustered than independent noise. With one added variance, other nuisance parameters identifiable and interior, and many independent groups, the limiting ratio is zero half the time and chi-squared with one degree of freedom otherwise: a fifty-fifty mixture, as Steven Self and Kung-Yee Liang showed in 1987. For a positive statistic halve the chi-squared upper-tail p-value; at zero use p equal to one. The asymptotic five-percent critical value is two point seven one rather than three point eight four.
A thousand simulated data sets with no group effect at all. In fifty-eight percent the likelihood ratio is numerically near zero, a little more than half, as is usual in small samples. The continuous part is compared with the asymptotic half-chi-squared density; the finite-sample fit need not be exact. The textbook cut-off of three point eight four rejects only two percent of the time, far too rarely; the mixture's two point seven one rejects three point three percent, closer to the nominal five. A null simulation can improve finite-sample calibration. Plug-in parametric bootstrap is generally approximate; exact simulation requires a known or pivotal null law.
For the variance components themselves, use Part 22's profile likelihood: maximize over everything else for each value of tau. The displayed usual profile interval uses the regular interior chi-squared cutoff. Boundary calibration can differ; this is not universally exact ninety-five-percent coverage. A Wald interval, estimate plus or minus two standard errors, is symmetric and with few groups can run below zero, which is meaningless for a standard deviation. The profile interval is asymmetric, longer on the high side, and when the data are compatible with no group variation it says so by reaching zero.
So: for fixed effects, use Satterthwaite or Kenward–Roger t intervals rather than z. For the variance components themselves, use profile-likelihood intervals or the bootstrap, since their sampling distributions are skewed. To test a variance at zero, use the mixture or a parametric bootstrap. And with very few groups, every approximation strains; a Bayesian analysis with a sensible prior on the variance, Part 26's subject, can help, with prior sensitivity especially important when there are very few groups.
Numbers: Board 89 / 94%; zeros 57.8%; rejects 2.2% vs 3.3%
7Longitudinal dataMaster's3 min
Repeated measurements of the same people over time are clusters too. Sixty children, each measured at ages four, six, eight, ten and twelve. Each line is one child. They start at different heights and grow at different speeds, and the five measurements of one child are far from independent. These children are a seeded simulation, so we know the truth the model should recover.
The natural model gives each child a random intercept and a random slope: their own height at age eight, and their own growth rate. The two random effects have a covariance matrix G, which allows tall children to grow faster or slower. The implied variance of a height is a quadratic in age. Its minimum depends on the intercept-slope covariance, and need not occur at age eight. Centring age at eight makes the intercept the height at eight; with age uncentred, the intercept would be a height at birth, far outside the data, and its covariance with the slope would have a different interpretation. Centering changes this covariance; it does not make every association an artefact.
Two fits. With only random intercepts, children grow five point six seven centimetres a year with a standard error of point oh four five. Adding random slopes leaves the estimate the same but nearly doubles the standard error to point oh eight: the intercept-only model treated sixty children's slopes as if they were all the same, and claimed precision it didn't have. The likelihood ratio, a hundred and forty-nine, leaves no doubt that slopes vary, and the estimated spreads match the simulation's five and a half centimetres and point six centimetres a year.
For individual children, the model's predictions are BLUP lines. Five children: dashed, each child's own least squares line, solid, their BLUP lines, and in white the average child. With five accurate measurements per child the BLUPs barely differ from each child's own fit. With two noisy measurements per child, as in many real studies, the BLUP lines would be pulled much more towards the average, and their slopes far more trustworthy than a two-point line.
Random effects are one way to model the covariance of repeated measures. A random intercept alone implies compound symmetry, one correlation between any two times. An autoregressive structure, Part 17's, makes nearby times more alike than distant ones. An unstructured covariance lets every variance and covariance be free, which is feasible when there are few time points. And a great practical virtue: children who miss a visit still contribute everything they have, Under missing at random, distinct missingness parameters and a correctly specified joint outcome model, likelihood can ignore the missingness mechanism. Informative visits can violate these conditions.
Numbers: 5.67 cm/yr; SE 0.045 → 0.081; LR 149
8Crossed and nested effectsMaster's4 min
Clusters can sit inside clusters. The World's schools are in towns, so a pupil's score can have a town effect, a school-within-town effect, and the pupil's own. Each level has its own variance. Two pupils in the same town share the town variance; two in the same school share both. The design is nested: every school belongs to exactly one town, so a school's label only means something within its town.
This display compares two separate working fits: a pupil-level school-intercept model, and an unweighted model of school means grouped by town. It is a two-stage approximation, not a joint three-level likelihood. The pupil-model residual variance is large. The school-mean model also has substantial residual variation, including pupil-mean noise. Its town component is about forty-nine. No explicit town effect was generated, but a positive fitted component can occur. We have not computed a calibrated town-variance test, so these estimates alone do not establish significance.
The classic teaching example, from Andrew Gelman and Jennifer Hill's book: radon gas measured in nine hundred and nineteen Minnesota homes in eighty-five counties. Each house was measured in the basement or on the first floor, a predictor at the house level. Each county has a soil uranium reading, a predictor at the county level, which models the county effects themselves. A county with two homes is then pulled not to the state average but to the radon level its uranium predicts. Group-level predictors make the target of shrinkage smarter, as chapter eleven will use for towns.
Other factors cross instead of nesting. An exam essay's grade depends on the essay's quality and on the severity of whoever reads it. Both essays and raters are samples from larger populations, so both effects are random. The factors are crossed: any rater could read any essay. The covariance no longer splits into blocks, one per group, so the fit needs general sparse algebra, which is what lme4 does; statkit's version is dense, for a few thousand rows.
A simulation: sixty essays and eight raters, each essay read by two raters chosen at random. An essay that draws two harsh raters gets a low mean for reasons that have nothing to do with the essay. Because the raters overlap across essays, the crossed model can separate the two, and it recovers each rater's severity. The variances: one point five seven for essays, point one seven for raters, point two two for the noise.
How well does each method recover the essays' true quality? The raw mean of two grades has a mean squared error of point two oh. Shrinking the means, with essays random but raters ignored, brings it to point one seven, though the ranking cannot change. The crossed model, which also corrects for who did the reading, brings it to point one two and improves the ranking. The same model adjusts for referees in peer review and for judges in competitions.
In practice these models are written in a compact formula language. A random intercept for each school is one plus bar school, in brackets. A random intercept and slope in age for each child puts age before the bar. Schools nested in towns are written town slash school, and crossed essays and raters are simply two separate terms. This is the notation of Douglas Bates's lme4 package for R, now copied by most other software.
Numbers: two-stage town variance 49; raters r = 0.98; MSE 0.203 / 0.167 / 0.124
9Fixed vs randomPractice4 min
Economists and statisticians argued about this for decades. A fixed-effects model gives every school its own intercept, a dummy variable each, which is the same as subtracting each school's mean from everything. A random-effects model draws the intercepts from a normal distribution, and, crucially, assumes they are independent of the predictors. Fixed effects use only variation within schools, so it removes additive, constant school intercepts. A common slope and strict conditional mean-zero pupil errors are still needed; causality needs further identification. Random effects use the within and between variation together, weighted, and are more efficient, if their assumption holds.
Here is why it matters. Each grey dot is one of the World's schools: its pupils' average home background against its average score. The unweighted descriptive between-school slope is about forty points per unit of background. Within a school, comparing pupils with each other, the slope is twenty-nine. The World built it that way: a school full of advantaged pupils does better than their individual backgrounds predict, a contextual effect. So the school effects are correlated with SES, and the random-effects assumption fails.
Yair Mundlak's 1978 resolution: keep the random effects, but add each school's mean of the predictor as a further predictor. Then the coefficient on the pupil's own SES is exactly the fixed-effects estimate here, with common within-school variance and the relevant group means included, and the coefficient on the school mean is the contextual effect, the between slope minus the within slope. Testing it probes a linear conditional-mean association with those group means. A zero coefficient cannot establish independence or rule out omitted nonlinear context. One model gives both answers, and keeps random effects' ability to predict for a new school.
The numbers. Random effects say twenty-nine point four, fixed effects twenty-nine point two. Close, because with sixty pupils a school the shrinkage factor is near one and random effects already lean mostly on the within-school comparison. Mundlak's model reproduces the fixed-effects slope exactly, and estimates a contextual effect of ten point six with a standard error of four. The World uses thirty within school and fifteen for latent school SES. Our estimated contextual regressor is the observed sample mean, so the targets are only approximately the same. The contextual effect is the noisier number, because it is learned from four hundred schools, not twenty-four thousand pupils.
Jerry Hausman's test of 1978 compares the two estimates directly: their squared difference, over the difference of their variances. That denominator is right because, when random effects are valid and efficient, the efficient estimator is uncorrelated with its difference from any other consistent one. Here the gap is only point two three, but the two estimates are so precise and so similar that the gap's own noise is smaller still: H is six point five six. A p-value of point oh one: reject, the school effects are correlated with SES, as built.
So the choice is not about whether schools are, philosophically, random. It is about the assumption that the school effects are unrelated to the predictors. If you want a within-school effect controlling additive constant school effects under strict exogeneity, use fixed effects, or Mundlak. If you want to predict for a new school, or to estimate an effect of something that varies only between schools, like the programme, you need additional restrictions or a design for between-school comparisons. Random effects are one option; school fixed effects absorb that programme variable. Mundlak's model delivers both. And Part 37 returns to fixed effects as a causal design for panel data.
Numbers: between 39.8, within 29.2; context 10.6 (4.1); Hausman 6.56, p 0.010
10GLMMsMaster's5 min
Generalized linear mixed models. Put a random effect inside Part 24's logistic regression: each school shifts the log odds of passing by its own amount. The likelihood averages each school's probability of its pupils' results over the distribution of its effect, and unlike the linear case the integral has no closed form, one for every school. Norman Breslow and David Clayton's penalized quasi-likelihood of 1993 linearizes and iterates, but it can be substantially biased for binary data with small clusters; the direction need not be the same for every parameter, so modern software integrates directly.
Each school's integrand is a bump in its random effect; here a small school of four pupils who all passed, whose bump is lopsided. The Laplace approximation of Part 22 replaces it with a normal curve at its peak, matched in curvature, and integrates that exactly. Adaptive Gauss–Hermite quadrature, from José Pinheiro and Douglas Bates, places a few nodes around the same peak with the same scale, and adds up the integrand at them with weights. With one node it is the Laplace approximation; increasing the node count improves the approximation only when numerical checks confirm stability. Ten nodes are not a universal accuracy guarantee.
Part 24's forty schools again, with passing meaning a score above five fifty. The Laplace fit gives a programme effect of point four three eight on the log odds, a school standard deviation of point seven oh. Ten-node quadrature agrees to the third decimal: with sixty pupils per school, each integrand is nearly normal already. With five pupils per school, they would differ. Part 24's GEE estimates were smaller, point four oh five, and that is not an error: it answers a different question.
The mixed model's coefficients are conditional: they describe a pupil's odds within a given school. Each grey curve is a school. Green is the typical school. Averaging the curves over all schools gives the yellow curve, a population-averaged probability. GEE fits a working marginal mean; a logistic-normal mixture need not be exactly logistic, and an average of steep logistic curves is a flatter one; the picture uses a large school spread to make the flattening visible. Its slope is smaller by about the square root of one plus point three four six times the school variance, a result of Scott Zeger, Kung-Yee Liang and Paul Albert. The predicted and observed ratios happen to be close here. Noncollapsibility, mean-model approximation and different working targets all matter; this is not an exact conversion or a causal policy effect.
Shrinkage matters most where rankings carry consequences. The World's sixty hospitals each perform an operation between seventeen and nearly nine hundred times a year, and newspapers rank them by death rate. The average is four point one percent. David Spiegelhalter's funnel plot draws the range an average hospital would show by chance, wide for small hospitals and narrow for large ones. The five worst hospitals by raw rate, in red, are led by two tiny ones, nineteen operations each, where three deaths make a rate of sixteen percent and two make eleven. Both sit inside the outer funnel: the normal reference is compatible with chance. It is only an approximation, especially for such small expected counts.
Fit a random-intercept logistic model with no predictors and rank the hospitals by their shrunk rates. The raw table's five worst include one hospital truly among the ten worst; the shrunk table's include two, and every one of its five has at least two hundred operations, where a high rate is evidence. The tiny hospitals drop out: two deaths in nineteen operations is not evidence of a bad hospital by itself: small samples are noisy, and these results do not rule out a truly high underlying risk. Over all sixty, these rates, obtained by transforming conditional modes rather than posterior mean probabilities, are about seven times closer to the truth in mean squared error. But look at the ranks: even shrunk, their correlation with the true ranking is only point three eight. With true differences this small, a league table is mostly noise, as Harvey Goldstein and David Spiegelhalter warned in 1996; report intervals for ranks, not ranks.
Numbers: 0.438 (0.248), s 0.705; ratio 1.082 vs 1.083; league 1 vs 2 of 5; MSE ÷7.4; ranks 0.21 / 0.38
11Small areasPractice4 min
A national survey is designed for national answers, but governments want local ones. A survey of two thousand of the World's adults asks their income; what is the mean income of each of its two hundred towns? The typical town has four respondents, eighteen have none, twenty-four have one. The direct estimates, each town's sample mean, range from eleven thousand to a hundred and thirty-three thousand, while the true town means lie between forty-six and sixty-one. Robert Fay and Roger Herriot faced exactly this in 1979, estimating income for tens of thousands of small American places, where federal revenue sharing depended on the answer.
Fay and Herriot's model works with the town means themselves. Each direct estimate is the truth plus sampling error with a variance we can estimate, smaller for towns with more respondents. The true means follow a regression on what is known about every town, here its region, plus a town effect with variance A. The result is James–Stein once more: each town's estimate is a weighted average of its own direct estimate and the regression's synthetic prediction, with weight gamma, A over A plus the town's sampling variance. N. G. N. Prasad and J. N. K. Rao derived an approximate MSE including estimation of beta and A, treating the sampling variances as known. Here those variances are estimated from pooled incomes, requiring further allowance; normality is also a working approximation for towns with only two respondents.
The hundred and fifty-eight towns with at least two respondents, placed by their sample size. The direct estimates' errors fan out, tens of thousands for towns with a handful of people. The EBLUPs' errors hug zero. The estimated town variance A is only nine, a standard deviation of three thousand, tiny next to a sample mean of four incomes, so the typical town gets a weight of point oh three on its own data: almost all synthetic. Only the largest town, with three hundred and eighty-five respondents, is trusted mostly on its own.
Against the World's true town means: the direct estimates have a mean squared error of three hundred and eighty-three, nearly twenty times the others. The purely synthetic regional prediction scores twenty point one, and the Fay–Herriot EBLUP twenty point six, close in this single realization. We have not computed uncertainty for this MSE comparison. Here the regions explain the towns well, so there is little left to learn from a town's own few respondents. The EBLUP is insurance: when a town is unusual and well sampled, it follows the town's own data, which a synthetic estimate never can. And because it is data-driven, the same formula decides how much to trust each town.
This is how official statistics are made locally. The US Census Bureau's small-area income and poverty estimates for every state and county, which feed the allocation of federal school funding, use a family of small-area methods related to this framework. State, county and school-district estimates do not all use one identical Fay–Herriot model. Their linking covariates are tax records, benefit counts and the last census. Benchmarking can constrain population-weighted area means to a reliable national total; simply adding unweighted town means would not give that total. George Battese, Rachel Harter and Wayne Fuller's unit-level version models individuals rather than area means, as this part's mixed models do. It is Part 18's survey sampling, joined to this part's shrinkage.
Numbers: MSE 383 / 20.1 / 20.6; Â 9.0; γ median 0.03
12Meta-analysisPractice4 min
Meta-analysis combines studies, each reporting an estimate and its standard error. If every study estimates the same effect, the best combination weights each by its inverse variance. But studies differ in their populations and protocols, so their true effects vary around a mean with variance tau squared: the random-effects model, which is Fay–Herriot with studies in place of towns. Rebecca DerSimonian and Nan Laird's 1986 estimator of tau squared matches Cochran's heterogeneity statistic Q to its expectation, a method of moments.
A forest plot of five simulated trials, each square sized by its weight. One study points the other way. The common-effect estimate is point one one four with a narrow interval. Allowing heterogeneity, the random-effects estimate is point one three seven, and its DerSimonian–Laird interval, from minus point one three to point four, is far wider: the trials disagree more than their standard errors allow. The Hartung–Knapp interval, coming next, is wider still. The simulation's true mean effect is point three, inside both random-effects intervals but outside the common-effect one.
Cochran's Q sums the weighted squared deviations from the common estimate: seventeen, against four expected if all the studies shared one effect. The DerSimonian–Laird estimate of tau is point two six, against a true point one five: from five studies, tau is barely estimable. I squared estimates the relative contribution of between-study heterogeneity to study-estimate variation, seventy-seven percent here. It is not a share of individual-outcome variance. And the most useful summary for practice is often the prediction interval: where the effect in the next study, or the next hospital, might fall under the same exchangeable study model. With five studies, this plug-in prediction interval is a rough approximation.
The random-effects model also says what each study's own effect probably was. Each is shrunk towards the overall mean by its own factor, the heterogeneity over itself plus the study's sampling variance, here between point six three and point eight five. Precise studies move little, and the study that pointed the other way is pulled the furthest: Efron and Morris's hitters, as clinical trials.
The DerSimonian–Laird interval is a z interval with the estimated weights. Its trouble is chapter six's: with few studies, tau squared is noisy, and the interval treats it as known. Joachim Hartung and Guido Knapp's interval rescales the standard error by how much the studies actually scatter around the estimate, and uses a t with K minus one degrees of freedom. It is chapter six's lesson for studies. Unmodified Hartung–Knapp can still be narrower than a z interval when residual heterogeneity is small; it does not guarantee coverage in every setting.
The Board: a thousand meta-analyses of five studies each, with real heterogeneity. The DerSimonian–Laird interval, still the default in much software, covers the true mean effect eighty-nine percent of the time: broken. Hartung–Knapp's covers ninety-four: kept. Methodologists, Cochrane's among them, now advise against relying on DerSimonian–Laird alone when the studies are few.
Two cautions. Studies that found nothing are less often published, so the literature overstates effects. Under a common effect and suitable sampling conditions a funnel plot should be roughly symmetric. Asymmetry can reflect selection, heterogeneity or other small-study effects; it does not diagnose publication bias alone. And combining biased studies only produces a precise biased answer. The model also shrinks each study's own effect towards the mean, as Efron and Morris shrank the hitters. Part 26 begins with exactly such a meta-analysis, the eight schools, done the Bayesian way.
Numbers: 0.137 [−0.13, 0.40] vs [−0.22, 0.50]; I² 0.77; Board 89.3 / 94.1%
13Item response theoryMaster's3 min
Rasch's model gives the log odds of a correct answer as ability minus item difficulty. Responses are assumed locally independent given ability. With normal random abilities and fixed items, this is a logistic mixed model. Conditional on the fixed item parameters, a person's raw score is sufficient for ability. Comparing raw scores directly requires the same item set; this does not make scores from arbitrary exam forms interchangeable. Specific objectivity concerns conditional model comparisons. The two-parameter model also lets items differ in discrimination.
A simulated exam of fifteen questions, each with its item characteristic curve: the chance of a correct answer as ability rises. Easy questions in blue, hard ones in red. An item's difficulty is the ability at which its curve crosses one half. In Rasch's model the curves are parallel, shifted copies of one logistic.
Two hundred simulated test-takers answer all fifteen. The fitted difficulties fall on the diagonal, a correlation of point nine eight seven with the truth, with standard errors near point one eight from two hundred answers each. The spread of ability is estimated at point nine nine, against a true one.
And the persons. In gold, each person's true ability against their raw score. In green, the fitted conditional mode of ability: a function of the raw score for this same complete item set, holding the fitted difficulties fixed. Its correlation with the truth is point eight six: fifteen questions measure ability only roughly, which is why the gold cloud is so wide at each score. And the random-effects estimate is shrunk: a perfect score doesn't mean infinite ability, which is what fixed-effects maximum likelihood would say.
How precisely does the exam measure? Each item's Fisher information about ability is p times one minus p, largest for people for whom the item is a coin flip. The test's information is the sum, peaking at about two point nine in the middle of the difficulties. With known item difficulties, its inverse square root is an asymptotic likelihood standard error, not the posterior uncertainty of our shrunk ability modes: about point five nine at best, with less information at extremes, where all items can be too easy or too hard. Test designers shape this curve by choosing items.
Item response models score international surveys like PISA and admissions tests like the GRE. Computerized adaptive tests choose each next question to be the most informative at the current ability estimate, so fewer questions are needed. And equating puts different versions of an exam on one scale through shared items. Part 64 uses the same model to rate AI systems by the benchmark questions they answer, separating how hard a question is from how good a system is.
Numbers: r 0.987; σ̂ 0.99; information 2.9; ability r 0.86
Recap, problems, and the road aheadAll tracks3 min
Part twenty-five in fourteen lines. Shrinking eighteen hitters' averages towards each other cut the error three and a half times. For known equal-variance normal observations and at least three means, James–Stein improves expected total risk, and SURE estimates its risk. It is empirical Bayes, and Tweedie's formula corrects the winner's curse without assuming a normal prior. Variance components split the World's scores: eighteen percent between schools. The linear mixed model is GLS with an estimated covariance, and Henderson's equations give its BLUPs. REML adjusts for estimated fixed effects and can reduce variance-component bias; it is not universally unbiased. Satterthwaite's t restored coverage to ninety-four percent, and a regular one-component boundary test uses a limiting fifty-fifty mixture. Random slopes model growth. Nested and crossed effects corrected the essays for their raters. Mundlak's model and Hausman's test handle school effects correlated with SES. Mixed logistic models give conditional effects, and shrinkage reduces rate error in this example while the hospital rankings remain uncertain. Fay–Herriot cut small-area error from three hundred and eighty-three to twenty-one. Hartung–Knapp kept meta-analysis coverage at ninety-four percent. And an exam is a mixed model, Rasch's.
Where it comes back. Part 26 makes the hierarchy fully Bayesian with the eight schools, and Part 27 computes it, meeting Neal's funnel, the shape of a variance near zero. Part 28 asks how to choose among mixed models. Part 33 reads false discovery rates as empirical Bayes. Part 37 uses fixed effects for panel data. Part 39's spatial models are random effects that vary smoothly over a map. Part 40's frailties are random effects in survival. And Part 45 proves the theory of admissibility that Stein's paradox began.
Six problems, with full solutions in the README. Stein's lemma and SURE; why James–Stein's shrinkage estimates the empirical Bayes factor; the BLUP of a random intercept; REML's n minus one; the boundary mixture and its cut-off; and Mundlak's equivalence with fixed effects. Pause here if you want to try them.
The books this part follows: Efron's Large-Scale Inference, Gelman and Hill's multilevel models, Pinheiro and Bates on mixed-effects models, and Rao and Molina on small areas; with the papers from Stein to Efron's Tweedie's formula.
Twenty-five parts of sixty-five. Many related estimates are now made together, each borrowing strength from the rest. But the shrinkage target and its variance were estimated, then treated as known. In 1981 Donald Rubin analysed coaching programmes in eight schools, and treated the variance itself as uncertain, with a prior. Part 26: Bayesian data analysis.
Where it goes next. The prior becomes explicit in the hierarchical Bayes of Part 26 (the eight schools) and its MCMC in Part 27; false discovery rates return as empirical Bayes in Part 33, fixed effects for panels in Part 37, frailty in Part 40, admissibility is proved in Part 45, and item response theory grades AI benchmarks in Part 64.
Key results
The part's results in one place, for revision.
Try it
Lab 25 · James-Stein on the hitters, and its risk for every theta
Recompute the film's baseball numbers with the series' library, then simulate James-Stein in ten dimensions at true mean vectors of growing length and compare its risk with p - (p - 2)^2 E(1/|X|^2).
python -m videos.stats.labs 25
needs numpy, scipy, matplotlib · download lab25.py ·
source on GitHubhitters: shrinkage factor B 0.791 (the film: 0.791)
hitters: total squared error, own average 0.0753 (the film: 0.0753)
hitters: total squared error, James-Stein 0.0215 (the film: 0.0215), 3.5 times smaller
hitters: James-Stein closer for 15 of 18
p = 10, |theta| = 0: risk of James-Stein 1.994 (formula 2.000; MLE 10.03)
p = 10, |theta| = 3: risk of James-Stein 5.980 (formula 5.986; MLE 9.97)
p = 10, |theta| = 12: risk of James-Stein 9.572 (formula 9.574; MLE 9.99)
p = 10, theta = 0: positive part 1.264
James-Stein's total risk is below the MLE's p at every theta, by most when the means are close together, and the positive part improves on it again; the gain is in the total, not in each coordinate.
The code (81 lines; it asserts its own result)
"""Lab 25: shrink Efron and Morris's eighteen hitters, and check James-Stein's risk against its formula."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
from explainer.stats import museum
from explainer.stats.kit import shrink
TITLE = "James-Stein on the hitters, and its risk for every theta"
GOAL = ("Recompute the film's baseball numbers with the series' library, then simulate James-Stein in ten dimensions "
"at true mean vectors of growing length and compare its risk with p - (p - 2)^2 E(1/|X|^2).")
TASKS = [
"Set p = 2 in the risk study. What does the formula give, and why does the estimator stop helping?",
"Shrink the hitters towards 0 instead of their mean (target=0.0 on the transformed scale). What happens to B?",
"Put all of theta's length in one coordinate. The total risk is unchanged; what happens to that coordinate's own?",
]
def exact_risk(p, norm2):
"""p - (p - 2)^2 E(1/|X|^2): |X|^2 is noncentral chi-squared, a Poisson(norm2 / 2) mixture of chi-squared(p + 2K)."""
k = np.arange(0, int(norm2 / 2 + 12 * np.sqrt(norm2 / 2 + 1) + 40))
return p - (p - 2) ** 2 * float(np.sum(stats.poisson.pmf(k, norm2 / 2) / (p - 2 + 2 * k)))
def run(seed=0):
rng = np.random.default_rng(seed)
names, hits, _, rest = museum.efron_morris()
y = hits / 45
x = np.sqrt(45) * np.arcsin(2 * y - 1) # close to unit variance on this scale
js = shrink.james_stein(x, 1.0)
est = (np.sin(js["theta"] / np.sqrt(45)) + 1) / 2
sse_raw, sse_js = float(np.sum((y - rest) ** 2)), float(np.sum((est - rest) ** 2))
closer = int(np.sum(np.abs(est - rest) < np.abs(y - rest)))
p, lengths = 10, np.array([0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0])
mc, mc_plus, mle, theory = [], [], [], []
for r in lengths:
theta = np.full(p, r / np.sqrt(p))
out = shrink.js_risk_exact(theta, R=40000, rng=rng)
mc.append(out["js"])
mc_plus.append(out["js_plus"])
mle.append(out["mle"])
theory.append(exact_risk(p, r * r))
mc, mc_plus, mle, theory = map(np.array, (mc, mc_plus, mle, theory))
lab = labs.Lab()
lab.row("hitters: shrinkage factor B", f"{js['B']:.3f} (the film: 0.791)")
lab.row("hitters: total squared error, own average", f"{sse_raw:.4f} (the film: 0.0753)")
lab.row("hitters: total squared error, James-Stein", f"{sse_js:.4f} (the film: 0.0215), {sse_raw / sse_js:.1f} times smaller")
lab.row("hitters: James-Stein closer for", f"{closer} of 18")
for i in (0, 3, 7):
lab.row(f"p = 10, |theta| = {lengths[i]:g}: risk of James-Stein", f"{mc[i]:.3f} (formula {theory[i]:.3f}; MLE {mle[i]:.2f})")
lab.row("p = 10, theta = 0: positive part", f"{mc_plus[0]:.3f}")
lab.note = ("James-Stein's total risk is below the MLE's p at every theta, by most when the means are close "
"together, and the positive part improves on it again; the gain is in the total, not in each coordinate.")
assert abs(js["B"] - 0.791) < 0.001 and abs(sse_raw - 0.0753) < 1e-4 and abs(sse_js - 0.0215) < 1e-4 and closer == 15
assert abs(theory[0] - 2.0) < 1e-9, "at theta = 0 the risk is p - (p - 2) = 2"
assert np.all(np.abs(mc - theory) < 0.12), "Monte Carlo risk matches p - (p-2)^2 E(1/|X|^2)"
assert np.all(theory < p) and np.all(np.diff(theory) > 0), "below the MLE's risk everywhere, rising towards it"
assert np.all(mc_plus <= mc + 1e-9) and mc_plus[0] < mc[0] - 0.4, "the positive part dominates"
fig, ax = labs.figure(2, size=(11, 4.4))
order = np.argsort(y)
for i in order:
ax[0].plot([y[i], est[i], rest[i]], [2, 1, 0], color=labs.MUTED, lw=0.8, alpha=0.8)
ax[0].scatter(y, np.full(18, 2), color=labs.BLUE, s=22, zorder=3)
ax[0].scatter(est, np.full(18, 1), color=labs.GOLD, s=22, zorder=3)
ax[0].scatter(rest, np.full(18, 0), color=labs.GREEN, s=22, zorder=3)
ax[0].set_yticks([0, 1, 2], ["rest of season", "James-Stein", "first 45 at-bats"])
ax[0].set(title="Eighteen hitters, 1970", xlabel="batting average", ylim=(-0.4, 2.4))
grid = np.linspace(0, 12, 80)
ax[1].plot(grid, [exact_risk(p, r * r) for r in grid], color=labs.GOLD, label="James-Stein: formula")
ax[1].scatter(lengths, mc, color=labs.GOLD, s=26, zorder=3, label="James-Stein: 40,000 draws")
ax[1].plot(lengths, mc_plus, "o--", color=labs.GREEN, ms=4, lw=1.2, label="positive part: 40,000 draws")
ax[1].axhline(p, color=labs.RED, label="MLE: p = 10")
ax[1].set(title="Risk in ten dimensions", xlabel="length of the true mean vector |θ|", ylabel="expected total squared error",
ylim=(0, 11.5))
ax[1].legend(loc="lower right")
lab.fig = fig
return lab
Now change it
- Set p = 2 in the risk study. What does the formula give, and why does the estimator stop helping?
- Shrink the hitters towards 0 instead of their mean (target=0.0 on the transformed scale). What happens to B?
- Put all of theta's length in one coordinate. The total risk is unchanged; what happens to that coordinate's own?
Problems, with solutions
Try each problem before opening its solution.
1. Stein's lemma and SURE. Prove Stein's lemma \(E(X - \theta)h(X) = E\,h'(X)\) for \(X \sim N(\theta, 1)\), and use it to derive SURE for \(X + g(X)\).
Solution
For X ~ N(θ, 1) and differentiable h with E|h′| < ∞, integrate by parts, using (x − θ)φ(x − θ) = −dφ(x − θ)/dx: E(X − θ)h(X) = ∫ h(x)(x − θ)φ(x − θ)dx = ∫ h′(x)φ(x − θ)dx = E h′(X). For θ̂ = X + g(X) in p dimensions: E‖θ̂ − θ‖² = E‖X − θ‖² + 2E(X − θ)′g + E‖g‖² = p + 2E Σ ∂ᵢgᵢ + E‖g‖², applying the lemma coordinate by coordinate. So SURE = p + ‖g‖² + 2∇·g is unbiased for the risk.
For James–Stein, g = −(p − 2)X/‖X‖², with ∇·g = −(p − 2)²/‖X‖² and ‖g‖² = (p − 2)²/‖X‖². So SURE = p − (p − 2)²/‖X‖² < p.
2. James–Stein as empirical Bayes. Show that \(E\{(p - 2)/\|X\|^2\} = 1/(1 + \tau^2)\) when \(X_i \sim N(0, 1 + \tau^2)\) independently, \(p \ge 3\).
Solution
Under the model each Xᵢ ~ N(0, 1 + τ²) independently, so S = ‖X‖² = (1 + τ²)W with W ~ χ²_p. For p ≥ 3, E(1/W) = 1/(p − 2). Then E{(p − 2)/S} = (p − 2)/{(1 + τ²)(p − 2)} = 1/(1 + τ²) = B. Plugging this unbiased estimate of B into the Bayes rule (1 − B)X gives James–Stein. (Shrinking towards x̄ spends a degree of freedom: p − 3 and Σ(xᵢ − x̄)² ~ (1 + τ²)χ²_{p−1}.)
3. The BLUP of a random intercept. Random intercept: show that the BLUP is \(\hat u_g = \lambda_g(\bar y_g - \bar x_g^\top\hat\beta)\), \(\lambda_g = \tau^2/(\tau^2 + \sigma^2/n_g)\).
Solution
For school g, y_g = X_gβ + 1u_g + e_g, with V_g = σ²I + τ²11′. Henderson's formula gives û_g = τ²1′V_g⁻¹(y_g − X_gβ̂). By Sherman–Morrison, V_g⁻¹ = σ⁻²{I − τ²11′/(σ² + n_gτ²)}. Then 1′V_g⁻¹ = σ⁻²{1 − n_gτ²/(σ² + n_gτ²)}1′ = 1′/(σ² + n_gτ²). So û_g = τ² n_g(ȳ_g − x̄_g′β̂)/(σ² + n_gτ²) = λ_g(ȳ_g − x̄_g′β̂), with λ_g = τ²/(τ² + σ²/n_g).
4. REML for one sample. One sample: show that REML gives \(\hat\sigma^2 = \sum(y_i - \bar y)^2/(n - 1)\).
Solution
With X = 1 and V = σ²I: ℓ_R = −½{n log σ² + Σ(yᵢ − ȳ)²/σ² + log(n/σ²)} + const = −½{(n − 1) log σ² + Σ(yᵢ − ȳ)²/σ²} + const. Setting the derivative to zero gives σ̂² = Σ(yᵢ − ȳ)²/(n − 1).
5. The boundary mixture. For one variance with regular identifiable nuisance parameters and many groups, show that the limiting LR law at \(\tau^2=0\) is \(\tfrac12\chi^2_0 + \tfrac12\chi^2_1\) in large samples; what is the 5% cut-off?
Solution
Asymptotically the unconstrained estimate of τ² is normal around 0 under H₀. With probability ½ it is negative; then the constrained MLE is 0 and the LR statistic is 0. Otherwise the constraint is inactive and the statistic is the square of the standardized estimate, χ²₁. So P(LR > c) = ½P(χ²₁ > c). Setting this to 0.05 gives P(χ²₁ > c) = 0.10, so c = 2.71.
6. Mundlak and fixed effects. Mundlak: under common within-group variance, show that adding all group predictor means gives the within slope.
Solution
Write x_gi = x̄_g + (x_gi − x̄_g). The model y = μ + βx + γx̄ + u + e is the same as y = μ + β(x − x̄) + (β + γ)x̄ + u + e. The regressors x − x̄ and x̄ are orthogonal: within each school, x − x̄ sums to 0 and x̄ is constant. With all relevant group means included and common within-group variance, V_g⁻¹ = a I + b_g 11′ with the same a across groups. The rank-one term annihilates x − x̄, giving the unweighted within estimator. Varying a across groups instead gives a weighted within estimator. Here γ = β_B − β_W uses the corresponding GLS between coefficient, not an arbitrary unweighted descriptive regression.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| hierarchical Bayes: the eight schools | 26 |
| MCMC for hierarchical models; Neal's funnel | 27 |
| choosing among mixed models | 28 |
| false discovery rates as empirical Bayes | 33 |
| fixed effects for panels | 37 |
| spatial random effects | 39 |
| frailty models | 40 |
| admissibility, proved | 45 |
| item response theory for AI benchmarks | 64 |
| the Coverage Board | every part; 65 |
Glossary
- Shrinkage; borrowing strength; partial pooling: pulling separate estimates towards a common value, by an amount the data choose.
- James–Stein estimator; positive part; inadmissible: (1 − (p − 2)/‖X‖²)X; the version that never shrinks past the target; beaten everywhere by another estimator.
- Stein's lemma; SURE: E(X − θ)h(X) = E h′(X); an unbiased estimate of an estimator's risk.
- Empirical Bayes; NPMLE; Tweedie's formula; winner's curse: a prior estimated from many parallel problems; the nonparametric MLE of that prior; E(θ | x) from the marginal density; selected estimates overstate their truths.
- Random effect; variance component; ICC; design effect: a group effect drawn from a population; its variance; the share of variance between groups; the variance inflation of a clustered mean.
- Linear mixed model; Henderson's equations; BLUP: y = Xβ + Zb + ε; the penalized normal equations; the best linear unbiased predictor of b.
- REML; error contrasts: the likelihood of combinations of y free of β; it accounts for fitted fixed effects and can reduce bias, without making every constrained component unbiased.
- Satterthwaite / Kenward–Roger degrees of freedom: approximate t reference distributions for mixed-model contrasts.
- Boundary; chi-bar-squared mixture: a null on the edge of the parameter space; ½χ²₀ + ½χ²₁ for one variance.
- Random slopes; growth curve; compound symmetry; AR(1); unstructured: group-specific slopes; trajectories over time; covariance patterns for repeated measures.
- Nested; crossed: each lower unit in one higher unit; factors that cut across each other.
- Fixed effects; within estimator; contextual effect; Mundlak device; Hausman test: group dummies; demeaned regression; between minus within; adding group means of x; comparing FE and RE.
- GLMM; Laplace approximation; adaptive Gauss–Hermite; PQL; conditional vs marginal effect: random effects inside a link; approximating each group's integral; linearized quasi-likelihood; group-specific against population-averaged coefficients.
- Funnel plot; league table: rates against volume with chance limits; a ranking of units.
- Small-area estimation; Fay–Herriot; EBLUP; synthetic estimator: local estimates from thin samples; the area-level model; the shrunk combination; the regression prediction alone.
- Meta-analysis; common and random effects; DerSimonian–Laird; Q; I²; Hartung–Knapp; prediction interval: combining studies; one effect or a distribution of effects; the moment estimator of τ²; the heterogeneity statistic and its share; the t interval with a rescaled SE; where the next study's effect will fall.
- Rasch model; item response theory; 2PL; test information: logit P = θ − b; models for exam responses; item-specific slopes; Σ p(1 − p), whose root inverse is the SE.
Sources
- History.
- C. Stein, Proc. Third Berkeley Symp. 1 (1956); W. James & C. Stein, Proc. Fourth Berkeley Symp. 1 (1961).
- B. Efron & C. Morris, JASA 68 (1973) and 70 (1975); Scientific American 236 (1977).
- H. Robbins, Proc. Third Berkeley Symp. 1 (1956); R. A. Fisher, Trans. R. Soc. Edinburgh 52 (1918).
- C. Henderson, Ann. Math. Stat. 21 (1950); Biometrics 31 (1975).
- Methods.
- C. Stein, Ann. Stat. 9 (1981); B. Efron, JASA 106 (2011); J. Kiefer & J. Wolfowitz, Ann. Math. Stat. 27 (1956).
- H. D. Patterson & R. Thompson, Biometrika 58 (1971); N. Laird & J. Ware, Biometrics 38 (1982).
- F. Satterthwaite, Biometrics Bulletin 2 (1946); M. Kenward & J. Roger, Biometrics 53 (1997); S. Self & K.-Y. Liang, JASA 82 (1987).
- Y. Mundlak, Econometrica 46 (1978); J. Hausman, Econometrica 46 (1978).
- N. Breslow & D. Clayton, JASA 88 (1993); J. Pinheiro & D. Bates, JCGS 4 (1995); S. Zeger, K.-Y. Liang & P. Albert, Biometrics 44 (1988).
- D. Spiegelhalter, Statistics in Medicine 24 (2005), funnel plots; H. Goldstein & D. Spiegelhalter, JRSS A 159 (1996), league tables.
- R. Fay & R. Herriot, JASA 74 (1979); N. G. N. Prasad & J. N. K. Rao, JASA 85 (1990); G. Battese, R. Harter & W. Fuller, JASA 83 (1988).
- R. DerSimonian & N. Laird, Controlled Clinical Trials 7 (1986); W. Cochran, Biometrics 10 (1954); J. Higgins & S. Thompson, Stat. Med. 21 (2002); J. Higgins, S. Thompson & D. Spiegelhalter, JRSS A 172 (2009); J. Hartung & G. Knapp, Stat. Med. 20 (2001).
- G. Rasch, Probabilistic Models for Some Intelligence and Attainment Tests (1960); A. Birnbaum, in Lord & Novick (1968).
- D. Bates, M. Mächler, B. Bolker & S. Walker, J. Stat. Software 67 (2015).
- Books.
- B. Efron, Large-Scale Inference (2010).
- A. Gelman & J. Hill, Data Analysis Using Regression and Multilevel/Hierarchical Models (2007).
- J. Pinheiro & D. Bates, Mixed-Effects Models in S and S-PLUS (2000).
- J. N. K. Rao & I. Molina, Small Area Estimation (2nd ed., 2015).
About this partfrom its README
Part 25 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the fifth part of Stage III, Master's. Part 15 shrank one estimate towards a prior someone chose. This part estimates many related things at once and lets the data choose the prior. James–Stein, empirical Bayes, random effects and REML turn out to be one idea seen four ways: borrowing strength.
It opens with Bradley Efron and Carl Morris's eighteen major-league hitters after their first 45 at-bats of 1970 (recomputed from their table):
- Each player's own average has a total squared error of 0.0753 against his average over the rest of the season.
- James–Stein keeps 21% of each distance on an approximately unit-variance arcsine scale (B̂ = 0.791; back-transformed target .263). Its held-out probability-scale SSE is 0.0215: 3.5 times smaller, and closer for 15 of the 18.
From there the part covers:
- James–Stein.
- The estimator; why the squared length of X is too large on average (E‖X‖² = ‖θ‖² + p).
- Stein's lemma and SURE, derived, giving risk p − (p − 2)²E‖X‖⁻² < p for every θ.
- Simulated risk for p = 10: 2.02 at θ = 0 (positive part 1.28) against the MLE's 10, rising towards 10 as ‖θ‖ grows.
- The positive-part estimator, the choice of target, and admissibility (Part 45).
- Empirical Bayes.
- The upgrade card from Part 15.
- For p > 3 the untruncated ratio (p − 3)/Σ(xᵢ − x̄)² is unbiased for B under the normal hierarchy, so James–Stein is empirical Bayes (Efron & Morris 1973).
- Robbins (1956); Tweedie's formula E(θ | x) = x + σ² d log f(x)/dx (Efron 2011).
- 1,000 z-scores, 90% true nulls. A finite-grid EM approximation puts 89% near 0 with fitted nonnull clumps. The generating prior is 0.9 δ₀ + 0.1 N(0, 3²).
- The ten largest z average 5.61; their true effects average 5.07 (the winner's curse); Tweedie's estimates average 4.84.
- Random effects.
- Variance components (Fisher 1918); the ICC; the ANOVA estimator and its flaws.
- All 24,157 of the World's pupils: τ̂² = 1,732 (SD 42), σ̂² = 7,872 (SD 89), ICC 0.180.
- For unequal fixed school sizes, m* = Σm²/Σm = 61.089. The fitted common-ICC design effect for the unweighted pupil mean is 11.839, giving effective n = 2,040 for this mean.
- The linear mixed model.
-
V = ZGZ′ + R and GLS; Henderson's mixed-model equations as a ridge penalty; the BLUP and its shrinkage factor.
-
40 schools:
Estimate Programme SE SES SE OLS, pupils independent 33.9 3.8 29.0 1.84 mixed model, REML 32.5 12.1 27.1 1.91 -
Shrinkage factors 0.90–0.94 with 50–82 pupils a school. The one-fit MSE against centered realized school-plus-context deviations falls from 101 to 93.
-
Prediction for a new pupil in a new school. The simple (1 − λ)τ² error variance assumes beta and covariance components known; estimating them adds uncertainty.
-
- ML vs REML.
-
The downward bias of ML; error contrasts and the restricted likelihood (Patterson & Thompson 1971).
-
300 data sets per setting, normal-plus-Bernoulli intercept mixture variance 0.2725; Gaussian working likelihood:
Groups ML REML ML gives τ̂² < 10⁻⁶ 5 0.143 0.289 28% 10 0.206 0.282 40 0.245 0.263 -
When to use which.
-
- Inference.
- Satterthwaite and Kenward–Roger degrees of freedom; two Board rows.
- The boundary: ½χ²₀ + ½χ²₁ (Self & Liang 1987). In 1,000 null data sets the LR is numerically near 0 (tolerance 10⁻⁶) in 57.8%. The χ²₁ cut-off 3.84 rejects 2.2%; the mixture's 2.71 rejects 3.3%.
- Profile-likelihood intervals for variances; advice.
- Longitudinal data.
- 60 simulated children measured at 4, 6, 8, 10 and 12; random intercepts and slopes (Laird & Ware 1982).
- Growth 5.67 cm a year. Its SE is 0.045 with random intercepts only and 0.081 with random slopes. LR 149.
- Spreads 5.2 and 0.59, against the simulation's 5.5 and 0.6.
- BLUP lines; compound symmetry, AR(1), unstructured covariances; missing visits under MAR.
- Nested and crossed.
- Separate two-stage fits give town variance 49 and school-mean residual variance 1,820. These are not a joint three-level decomposition; residuals include pupil-mean noise. No calibrated town-variance test was computed.
- Gelman & Hill's radon and group-level predictors.
- Essays crossed with raters, each essay read by 2 of 8 raters. Rater severities are recovered (correlation 0.98).
- Essay MSE: raw mean 0.203, essays random only 0.167, crossed 0.124.
- lme4's formula notation.
- Fixed or random.
- Within against between: 400 schools' between slope is 39.8, the within slope 29.2.
- Mundlak's model (1978): under common within-group variance with all relevant group means included, the within coefficient equals fixed effects; the contextual effect is 10.6 (SE 4.1), against the World's 30 and 15.
- Hausman (1978): H = 6.56, p = 0.010.
- When to use which.
- GLMMs.
- The integral; PQL (Breslow & Clayton 1993); Laplace and adaptive Gauss–Hermite, drawn on one school.
- 40 schools, passing 550: programme 0.438 (SE 0.248), school SD 0.705 by Laplace; AGQ(10) agrees to three decimals.
- GEE's marginal 0.405. The ratio 1.082 against √(1 + 0.346 s²) = 1.083.
- The World's hospital league table. 60 hospitals with 17–877 operations, average death rate 4.1%. The raw top five are led by two hospitals of 19 operations (15.8% and 10.5%), and 1 of the five is truly among the ten worst. The shrunk top five all have 205 or more operations, and 2 are truly among the worst. The shrunk rates' MSE is 7.4 times smaller, yet rank correlations with the truth are only 0.21 (raw) and 0.38 (shrunk): report intervals for ranks (Goldstein & Spiegelhalter 1996).
- Small areas.
- A survey of 2,000 adults for 200 towns (median 4 respondents). Direct means range from 11 to 133 thousand while the truths lie between 46 and 61.
- Fay–Herriot (1979); the EBLUP; Prasad–Rao MSE. Â = 9.0; γ median 0.03, largest 0.76 (385 respondents).
- MSE: direct 383, synthetic 20.1, EBLUP 20.6.
- SAIPE, benchmarking, unit-level models.
- Meta-analysis.
- Common and random effects; DerSimonian–Laird (1986).
- Five simulated trials: common effect 0.114 ± 0.124. Random effects 0.137, DL [−0.13, 0.40], HK [−0.22, 0.50]; the truth is 0.3.
- Q = 17.1 on 4 df; τ̂ = 0.26 (truth 0.15); I² = 0.77; prediction intervals.
- Shrunk study effects (factors 0.63–0.85); Hartung–Knapp; two Board rows; publication bias.
- Item response theory.
- Rasch (1960) as a GLMM; given fixed item parameters and local independence, the same-item raw score is sufficient; 2PL.
- 200 persons × 15 items: difficulties correlate 0.987 with the truth (SE about 0.18); σ̂ = 0.99.
- Known-item information peaks at 2.9 (asymptotic likelihood SE 0.59). Fitted conditional ability modes use same-item raw scores, correlating 0.86 with the truth.
- PISA, adaptive testing, equating, AI benchmarks (Part 64).
Every number on screen is computed in compute.py:
- the hitters are the Museum's;
- schools, towns, incomes and hospitals are the World's;
- the rest are seeded simulations.
Built in this part:
statkit.shrink(explainer/stats/kit/shrink.py):- James–Stein (towards 0 or the mean, positive part), SURE and Monte Carlo risk (the legacy helper name includes “exact”);
- normal empirical Bayes;
- the NPMLE of a prior by EM on a grid, and Tweedie's formula;
- Fay–Herriot;
- random-effects meta-analysis (DL, I², Hartung–Knapp).
statkit.mixed(explainer/stats/kit/mixed.py), checked against statsmodels intests/test_stats_kit_mixed.py:lmm: random intercepts and slopes by ML or REML, with per-group Woodbury algebra, BLUPs and ICC;satterthwaitedegrees of freedom;vc_lmm: variance components for crossed or nested factors;glmm_logit: Laplace and adaptive Gauss–Hermite.
- The shrinkage plot (
ShrinkagePlotinexplainer/stats/viz.py): raw estimates, shrunk estimates and truths on three lines, with arrows between them. - The World: the
hospitalsblock, 60 hospitals' volumes, true death probabilities and deaths. - The Museum:
EFRON_MORRISandefron_morris().
The Coverage Board gains four rows:
| Method | Setting | Reps | Achieved | Verdict |
|---|---|---|---|---|
| DerSimonian–Laird, z | 5 studies, τ = 0.15 | 1,000 | 89.3% | broken |
| Hartung–Knapp, t₄ | 5 studies, τ = 0.15 | 1,000 | 94.1% | kept |
| mixed model, z interval | 8 schools, effect between schools | 400 | 89.0% | broken |
| mixed model, Satterthwaite t | 8 schools, effect between schools | 400 | 94.0% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Eighteen hitters, 1970 | SSE 0.0753 vs 0.0215 (3.5×); closer for 15 of 18; B̂ 0.791 |
| 1 | James–Stein | risk 2.02 (positive part 1.28) vs 10 at θ = 0 |
| 2 | Empirical Bayes | NPMLE 89% at 0; top ten 5.61 / 5.07 / 4.84 |
| 3 | Random effects | τ̂² 1,732, σ̂² 7,872, ICC 0.180; mean-specific unequal-size deff 11.84 |
| 4 | The linear mixed model | programme SE 3.8 → 12.1; MSE 101 → 93 |
| 5 | ML vs REML | 5 groups: 0.143 vs 0.289 (truth 0.2725); 28% zeros |
| 6 | Inference | Board 89 / 94%; zeros 57.8%; rejects 2.2% vs 3.3% |
| 7 | Longitudinal data | 5.67 cm/yr; SE 0.045 → 0.081; LR 149 |
| 8 | Nested and crossed | two-stage town variance 49; raters r = 0.98; MSE 0.203 / 0.167 / 0.124 |
| 9 | Fixed or random? | between 39.8, within 29.2; context 10.6 (4.1); Hausman 6.56, p 0.010 |
| 10 | GLMMs | 0.438 (0.248), s 0.705; ratio 1.082 vs 1.083; league 1 vs 2 of 5; MSE ÷7.4; ranks 0.21 / 0.38 |
| 11 | Small areas | MSE 383 / 20.1 / 20.6; Â 9.0; γ median 0.03 |
| 12 | Meta-analysis | 0.137 [−0.13, 0.40] vs [−0.22, 0.50]; I² 0.77; Board 89.3 / 94.1% |
| 13 | Item response theory | r 0.987; σ̂ 0.99; information 2.9; ability r 0.86 |
| 14 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Efron & Morris (1975). 18 hitters after 45 at-bats; James–Stein wins (recomputed).
- James–Stein (1961). The estimator; its risk via Stein's lemma and SURE, derived; positive part; Part 45 proves the admissibility theory.
- Empirical Bayes (Robbins 1956; Efron & Morris 1973). James–Stein as estimated normal priors; Tweedie's formula and the winner's curse (Efron 2011).
- Random effects. Variance components (Fisher 1918); ICC; design effects.
- The linear mixed model. V = ZGZᵀ + R; GLS; BLUP via Henderson's equations (derived).
- ML vs REML (Patterson & Thompson 1971).
- Inference. Satterthwaite, Kenward–Roger; boundary tests ½χ²₀ + ½χ²₁ (Self & Liang 1987).
- Longitudinal data. Random slopes (Laird & Ware 1982); growth curves; covariance structures.
- Crossed and nested effects. The radon example (Gelman & Hill).
- Fixed vs random. Hausman (1978); Mundlak (1978).
- GLMMs. Laplace and Gauss–Hermite; PQL bias; conditional vs marginal odds ratios.
- Small areas. Fay–Herriot (1979); EBLUP.
- Meta-analysis. DerSimonian–Laird; τ² and I²; Hartung–Knapp (Board).
- Item response theory. Rasch as a GLMM (Part 64).
- Outro.
Built: statkit.mixed and statkit.shrink; the World's hospital league table. Data: Efron & Morris.
Build the film
python -m videos.stats.stats25.compute # the part's numbers, into .cache/stats25
python tools/build.py stats25 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats25 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats25. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats25.compute # once (a few minutes; cached in .cache/stats25)
python tools/build.py stats25 -q l # fast 480p preview
python tools/build.py stats25 # 1080p30 -> renders/stats25.mp4
python tools/qa_scene.py stats25 GLMM
python tools/lecture_length.py stats25 --floor 50