SStatistics, Built

Stage III · Master's

Part 22 of 65

Likelihood in Depth

Master'sstarts at this level54 min of film15 chaptersprerequisites: Part 9, Part 10, Part 21

Why does maximum likelihood work, and what happens when the model is wrong?

In Naples in 1893 Weldon measures the foreheads of 1,000 shore crabs, finds the histogram lopsided, and asks Karl Pearson whether it is two normal curves added together; Pearson matches five moments and solves a ninth-degree polynomial by hand. EM fits the same mixture by likelihood, and the part then proves the two promises of Part 9. Consistency comes from a KL divergence: the average log likelihood converges to a curve whose unique peak is the truth. Normality comes from expanding the score, and the curvature becomes the standard error, with the observed information tracking the precision of the sample in hand better than the expected. Wald, score and likelihood-ratio tests are three readings of one curve. Then each condition is broken in turn: in the Neyman-Scott pairs the nuisance parameters multiply and the MLE of the variance converges to half the truth, the mixture likelihood is unbounded, a null sits on a boundary, and the model is simply wrong, where the estimate converges to the KL projection and its honest standard error is the sandwich. It closes with quasi- and pseudo-likelihood, the likelihood principle on two stopping rules, and a glimpse of the Fisher metric.

What you need. Taylor expansion in several variables, the law of large numbers, the central limit theorem and Slutsky's lemma as used in Stage II.

Hook
Pearson's crabs, 1894
Mathematics
MLE asymptotics, profile likelihood, Neyman–Scott, EM, misspecification and the sandwich, the likelihood principle
Built
statkit.mle

What you will be able to do

Bachelor's

  • Explain what a mixture of two normal curves is and how EM splits each crab between the two components.
  • State the two promises about maximum likelihood made in Part 9 and name the conditions they need.

Master's

  • Derive the asymptotic normality of the MLE from the expansion of the score, and compute Wald, score and likelihood-ratio statistics and the intervals each one inverts to.
  • Prove that an EM step never lowers the likelihood, and compute a profile likelihood interval.
  • Derive the sandwich covariance under misspecification and estimate it.

PhD

  • Explain the Efron-Hinkley argument for the observed information by conditioning on an ancillary, and where it stops short of a finite-sample guarantee.
  • State Birnbaum's theorem, and say which of sufficiency and conditionality a p-value that depends on the stopping rule gives up.

Practice

  • Recognize an unbounded likelihood, label switching and a boundary null in a fitted mixture, and calibrate the test by a parametric bootstrap of the same procedure.
  • Report sandwich standard errors when the variance model is in doubt, and say that they repair the precision claimed and not the model.

Contents

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

  1. 0Weldon's crabs, 1893Bachelor's3 min
  2. 1Upgrade: what Part 9 promisedBachelor's3 min
  3. 2ConsistencyMaster's3 min
  4. 3Asymptotic normalityMaster's3 min
  5. 4Observed vs expected informationPhD3 min
  6. 5Many parametersMaster's3 min
  7. 6The trinityMaster's4 min
  8. 7Neyman-ScottMaster's3 min
  9. 8EMMaster's6 min
  10. 9When likelihood misbehavesPractice5 min
  11. 10MisspecificationPractice5 min
  12. 11Quasi-, composite and pseudo-likelihoodMaster's4 min
  13. 12The likelihood principlePhD4 min
  14. 13Information geometry, a glimpsePhD3 min
  15. 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.

Weldon's crabs, 1893Bachelor's3 min

In 1893 the zoologist Walter Frank Raphael Weldon measured a thousand shore crabs from the Bay of Naples. Among other things he recorded the breadth of each crab's forehead as a fraction of its body length. The histogram came out lopsided, and Weldon wondered whether he was looking at two races of crab mixed together, perhaps one evolving away from the other. He asked his friend Karl Pearson: is this the sum of two normal curves? That question has five unknowns: the share of each race, their two means, and their two spreads.

Here are Weldon's thousand crabs, in the twenty-nine intervals Pearson printed. Their mean ratio is point six four four seven. A single normal curve with the same mean and spread, in red, fits badly: the data have a long left shoulder and a steep right side. A single normal can't be skewed; a mixture of two can.

Pearson's answer, published in 1894, was the method of moments at its most heroic. He wrote the mixture's mean and its second to fifth central moments in terms of the five unknowns, and set them equal to the data's. Eliminating four unknowns left a single polynomial of the ninth degree, which he solved by hand. It had more than one root that made sense. To choose, he computed the sixth moment of each candidate and kept the one closer to the data's.

Solving Pearson's five equations numerically, from hundreds of starting points, finds two admissible solutions; multistart search alone does not prove completeness, both with two components close together. Their sixth moments differ, and solution B is the closer to the data's. But this raises the questions of this part. Why should matching moments give good estimates at all? Which method is best? And how sure can we be of numbers like these?

Fisher formalized maximum-likelihood theory in 1922. For these grouped crab data we first use a midpoint-density approximation. The displayed EM fit is an interior local maximum, not a global maximum of the unrestricted mixture likelihood; chapter nine shows why. Forty-three percent of the crabs in a broader component centred at point six three two, the rest in a narrower one at point six five five. Its log likelihood beats both of Pearson's solutions, and beats a single normal by twenty-seven units. This part explains when maximum likelihood works, how to measure its uncertainty, how to compute it, and what happens when the model itself is wrong.

Numbers: moments A p = 0.533, B p = 0.424; sixth moments 7.88, 7.76 vs 7.45; ML log lik 2567.58

1Upgrade: what Part 9 promisedBachelor's3 min

Part 9 introduced maximum likelihood and made two promises: the maximum likelihood estimator is consistent, closing in on the truth as the sample grows, and it is approximately normal with variance one over n times the Fisher information. It quietly assumed a smooth likelihood, a fixed number of parameters, and a model that is actually true, and it proved nothing. Now we prove both promises, see exactly which conditions the proofs use, and then break each condition in turn.

Two identities carry everything. The score is the derivative of an observation's log likelihood with respect to theta. At the true theta its expectation is zero: it's the derivative of the integral of the density, which is one for every theta. Differentiate that identity again and you find that the score's variance equals minus the expected second derivative: the Fisher information, two definitions that agree. For n independent identically distributed observations the scores add: mean zero, variance n times I. Both steps need the derivative to pass through the integral, our first regularity condition.

Here is a useful checklist of sufficient regularity assumptions, not a complete theorem. We also need integrability and uniform local derivative control, nonsingular information, and a consistent interior solution. The set of possible values doesn't depend on theta; the true value is in the interior of the parameter space; the log likelihood has three derivatives, suitably bounded; the model is identifiable, so different parameters give different distributions; the number of parameters stays fixed as n grows; and the model is true. This part breaks every one of them: the first in a moment, the second, third and fourth in chapter nine, the fifth in chapter seven, the sixth in chapter ten.

A continuous analogue of Part 9's German tank problem breaks the fixed-support assumption. Independent Uniform zero theta observations have a support that depends on theta. This differs from discrete serial numbers sampled without replacement. The likelihood is theta to the minus n, but only for theta at least the largest serial number, so the maximum likelihood estimate is the largest number seen. Its error shrinks like one over n, much faster than the usual one over root n, and its scaled error is exponential, not normal. The theory of this part doesn't apply, and the root-n regular benchmark does not apply to this different model.

Numbers: six conditions; tanks: n(θ − θ̂)/θ → Exponential(1)

2ConsistencyMaster's3 min

Why should maximum likelihood find the truth? Divide the log likelihood by n: it's an average of independent terms, a random curve over theta. By the law of large numbers, at each theta under suitable integrability it converges to a fixed curve M of theta, the expected log likelihood under the true distribution. And by Jensen's inequality from Part 21, M at the truth minus M anywhere else is a Kullback–Leibler divergence, which is never negative. If the model is identifiable, the divergence is zero only at the truth, so the limiting curve has its unique peak exactly at theta zero.

Here's the picture, for a Poisson rate, using Bortkiewicz's horse kicks from Part 3: their rate, point six one, plays the truth. In gold, the limiting curve M of theta, peaked at point six one. Then the average log likelihood of samples of ten, a hundred, a thousand and ten thousand draws from one growing sample. Each is a random curve. Their peaks, the maximum likelihood estimates, sit at one point one, point six eight, point six three eight and point six one oh. As the curves settle onto the gold one, their peaks settle onto its peak. That's the whole idea of consistency.

Turning the picture into a proof needs two things. The random curves must converge uniformly over theta, not just at each point, so that no stray spike far away can win. And the limiting peak must be well separated: everywhere at least epsilon away, M is lower by a margin. Then the probability that the estimate lands more than epsilon from the truth goes to zero. Abraham Wald gave conditions for the uniform step in 1949, compactness, suitable continuity and integrable domination can provide a modern sufficient route. Wald's 1949 theorem is a foundational result; versions differ in their precise assumptions.

Notice what the argument didn't use: no normality, no smoothness, not even a derivative. It needs identifiability and a parameter space that stays fixed as n grows. Let the parameters multiply with the data and it can fail, as chapter seven shows. Under the same uniform-convergence and separated-maximum conditions, a misspecified estimate can still converge, but to the peak of the wrong M, the model's closest approximation to the truth, as chapter ten shows. And the same argument applies to other average-objective estimators when its conditions hold, which Part 47 exploits.

Numbers: peaks 1.1, 0.68, 0.638, 0.6103 → 0.61

3Asymptotic normalityMaster's3 min

Now the second promise. At a consistent interior differentiable maximum the score is zero; nonsingular information and local derivative bounds control the expansion. Since consistency puts the estimate near the truth, expand the score around the truth to first order: zero equals the score at theta zero plus the error times the score's slope. Solve for the error and scale by root n: a ratio. The numerator is a sum of independent scores, each with mean zero and variance I, divided by root n, so by the central limit theorem it's approximately normal with variance I. The denominator is an average of minus second derivatives, so by the law of large numbers it converges to I itself.

A normal divided by a constant is normal, by Slutsky's theorem: root n times the error converges to a normal with variance one over the information. In practice we plug in the estimate, which gives Part 9's approximation. The remainder we dropped in the expansion is kept small by the bound on the third derivative, the third regularity condition. With several parameters the same algebra runs with vectors and matrices: the inverse of the information matrix is the asymptotic covariance.

A demanding test: the Cauchy distribution, which has no mean and no variance, so the sample average is useless. Four thousand samples of fifty, estimating the centre. The sample median, in grey, has a standard deviation of point two three, near its theory. The maximum likelihood estimate, found by Newton's method from the median, does better: point two oh eight. The Cauchy's information is one half per observation, so the theory says point two oh, and the gold normal curve is what we see. The raw observations lack a variance, but the regular location estimator has an approximately normal sampling distribution here and asymptotic efficiency.

Part 9's Cramér–Rao bound says no unbiased estimator can have variance below one over n I. The maximum likelihood estimator reaches it in the limit: it is asymptotically efficient. For the Cauchy, the median's variance is about twenty-two percent larger, so using the median wastes about a fifth of the data. The fine print: Joseph Hodges constructed a biased estimator whose limiting variance beats the regular asymptotic benchmark at a point, at the price of doing worse nearby; Part 47 explains why such estimators are ruled out by asking for regularity.

Numbers: Cauchy n = 50: SD 0.208 (0.200) vs median 0.229 (0.222); ratio 1.22

4Observed vs expected informationPhD3 min

Chapter three's variance, one over n I, used the expected information. There's a second candidate. The expected information is the average curvature of the log likelihood over all the samples we might have seen, evaluated at the estimate. The observed information is the curvature of the log likelihood we actually have. In exponential families with their natural parameter the two are identical. But for the Cauchy the expected information is always n over two, while the observed information depends on how the sample happens to fall: tightly clustered data give a sharp peak, scattered data a flat one.

Bradley Efron and David Hinkley asked in 1978 which one we should use. Simulate eight thousand Cauchy samples of twenty, and sort them into quarters by their observed information. In blue, the actual variance of the estimate within each quarter: samples with sharper peaks really do give more accurate estimates, by a factor of more than two from the flattest quarter to the sharpest. In green, one over the observed information, averaged in each quarter: it tracks the blue closely. The expected information gives the same answer, point one, for every sample, an unconditional asymptotic approximation that misses the variation among these information strata. This simulation is not a universal finite-sample ordering of variance estimates.

Why does the observed information win? An ancillary statistic is one whose distribution doesn't depend on the parameter: by itself it says nothing about theta. For a location-equivariant estimator in a location family, the centered configuration has a parameter-free distribution and is ancillary. But it tells us how precise this particular estimate is, and given the configuration the variance is close to one over J, the observed information. Fisher argued for conditioning on ancillaries in 1934: judge an estimate by the experiment you actually did, not by an average over experiments you might have done. Chapter twelve returns to this idea.

For a regular, well-fitted likelihood with nonsingular curvature, observed information is often a useful standard-error estimate. Finite-sample conditional accuracy still needs assessment. It's what Newton's method computes anyway. Fisher scoring uses the expected information, but for canonical generalized linear models with fixed dispersion and design the two coincide. And if the model itself may be wrong, neither curvature is right, and we need chapter ten's sandwich.

Numbers: Var 0.167 → 0.070; 1/J 0.167 → 0.066; 1/(nI) = 0.10

5Many parametersMaster's3 min

With several parameters the information is a matrix: the expected curvature of the log likelihood in every direction. The estimates' covariance is approximately its inverse, and it's the inverse of the whole matrix that matters, not the reciprocal of each diagonal entry. Here's a two-parameter example: a gamma distribution, with a shape and a rate, fitted to a hundred and fifty of the World's incomes. The shape comes out at two point two eight. The two estimates are correlated point eight nine: a larger shape and a larger rate fit almost equally well, because both keep the mean, shape over rate, near the sample's.

Here is that likelihood as a landscape: contours of the log likelihood over shape and rate, from half a unit below the peak down to fifty below. It's a long, tilted ridge, chapter one's correlation made visible. A drop of about three defines an asymptotic joint ninety-five percent region for two parameters. A one point nine two drop is the one-parameter profile cutoff; its full two-dimensional contour is not a joint ninety-five percent region. In gold, the profile ridge: for each value of the shape, the rate that fits best. For the gamma it has a formula, the shape divided by the sample mean.

Walking along the ridge and recording the height gives the profile log likelihood for the shape: a one-dimensional curve that has already done its best with the rate. Cut it one point nine two below its peak, half the ninety-fifth percentile of chi-squared with one degree of freedom. The shapes above the cut form the profile likelihood interval, one point eight three to two point eight. The Wald interval, plus or minus one point nine six standard errors from the inverse information matrix, is one point eight oh to two point seven six. Close here, but the profile follows the likelihood's real, slightly skewed shape, which the Wald interval forces to be symmetric.

In general, split the parameters into psi, which we care about, and lambda, a nuisance, and maximize lambda away. Twice the drop in the profile log likelihood has, in large samples, a chi-squared distribution with as many degrees of freedom as psi has components, which is why the cut works. The profile is generally not itself a normalized sampling likelihood. Its curvature does account for nuisance estimation to first order through the information matrix's Schur complement; higher-order bias can remain. When there are many nuisance parameters that matters a great deal, and suitable modified profiles can reduce higher-order nuisance effects under their assumptions. Chapter seven shows how badly the plain version can fail.

Numbers: â = 2.28, b̂ = 0.0473, corr 0.89; profile [1.83, 2.80], Wald [1.80, 2.76]

6The trinityMaster's4 min

There are three classical ways to test a value of a parameter, and all three are readings of one curve. Here's the log likelihood for fourteen successes in twenty trials, and the hypothesis that p is a half. The likelihood-ratio test measures how far the curve falls from its peak to the hypothesis: twice the drop is three point two nine. The Wald test measures the horizontal distance from the estimate to the hypothesis, in standard errors computed at the estimate; squared, that's three point eight one. The score test looks only at the hypothesis: how steeply the curve is still rising there, scaled by the information at p one half: three point two. Under the regular null, all three have an asymptotic chi-squared distribution with one degree of freedom, and here they give p-values from point oh five one to point oh seven four, all above five percent in this example, so all three fail to reject here. Other data near a cutoff can produce different decisions.

As formulas: the Wald statistic is the squared distance weighted by the information at the estimate, so it needs only the unrestricted fit. Rao's score statistic, from 1948, is the squared score at the null divided by the null information, so it needs only the fit under the hypothesis, convenient when the full model is hard to fit. The likelihood ratio, Wilks's 1938 statistic, needs both fits, but it doesn't change if we reparametrize, say from p to log odds. For an exactly quadratic log likelihood with matching information scaling, all three coincide; their differences measure how far from quadratic it is.

Each test gives an interval, by Part 11's recipe: collect the values the test doesn't reject. Inverting the Wald test gives the Wald interval for a proportion, the one whose coverage Part 11 watched collapse near zero and one. Inverting the score test, which uses the standard error at the hypothesized value rather than at the estimate, gives Edwin Wilson's 1927 interval, the one that kept its promise. And inverting the likelihood-ratio test gives chapter five's cut at one point nine two below the peak. Three tests, three intervals, and the differences between them are the differences Part 11's Board recorded.

Sometimes the differences are dramatic. Fit logistic regressions to samples of sixty, with true slopes from zero to seven, and test whether the slope is zero. The likelihood-ratio statistic, in gold, grows steadily with the true effect, as it should. The Wald statistic, in blue, grows at first, peaks around a slope of three, and then falls: the stronger the evidence, the less significant the Wald test says it is. When the fitted probabilities approach zero and one, the estimated standard error grows faster than the estimate. Walter Hauck and Allan Donner pointed this out in 1977; it is a reason to compare likelihood-ratio and Wald inference. Software often reports Wald tests too.

For intervals the Board is more forgiving. A thousand samples of fifty with a true slope of two and a half: the Wald interval covers ninety-seven percent of the time, a little conservative but within the Board's tolerance, so kept. The profile likelihood interval covers ninety-three percent, also kept. Tests near the boundary of what the data can say are where the trinity's members part company.

Numbers: W 3.81, S 3.20, Λ 3.29; Hauck–Donner peak 3.77; Board 96.9% / 93.3%

7Neyman-ScottMaster's3 min

Jerzy Neyman and Elizabeth Scott found in 1948 how to break maximum likelihood. Observe pairs of measurements; each pair has its own mean, mu i, and every measurement the same error variance sigma squared. There are n plus one parameters, and each new pair brings a new one. It's an ordinary situation: each patient's blood pressure measured twice, or each lab's two readings of a sample. We don't care about the means, which Neyman and Scott called incidental parameters; we want sigma squared, the precision of the measurement.

Maximize the likelihood: each mean is estimated by its pair's average. Then sigma squared is estimated by the average squared deviation from those averages, which works out as the sum of squared differences within pairs divided by four n. But the expected squared difference is two sigma squared. So the estimate converges to half the true variance, no matter how many pairs we collect. Each pair spends one of its two observations estimating its own mean, and the maximum likelihood estimate never charges for it.

A simulation: three hundred data sets, each of a thousand pairs, with the true variance one. The maximum likelihood estimates cluster tightly around point five oh two, very precisely wrong. Dividing by two n instead of four n, which is what anyone using the within-pair differences directly would do, gives one point oh oh three.

Chapter five distinguished first-order nuisance adjustment from the incidental-parameter problem. Here the number of means grows with the data. Profile out each pair's mean, and the log likelihood for sigma squared is minus n log sigma squared, minus the sum of squared differences over four sigma squared. The likelihood of the differences alone, a genuine likelihood, has the same second term but only half the first. The profile's extra minus n over two log sigma squared drags the maximum towards small variances, by exactly a factor of two. Here each new nuisance mean still has only two observations, so its estimation error does not vanish and the variance bias persists. Growing dimension is not automatically fatal in every model; rates depend on how much information each nuisance parameter receives.

The cures all remove the incidental parameters before maximizing. The marginal likelihood uses only the within-pair differences, whose distribution doesn't involve the means at all; maximizing it gives the right answer. A conditional likelihood conditions on statistics that capture the nuisance parameters, as Erling Andersen did for logistic models in 1970. Restricted maximum likelihood, REML, applies the same idea to mixed models, as Part 25 will. And economists meet the problem in nonlinear short-panel fixed-effect models. Ordinary linear fixed-effect slopes need not suffer this same inconsistency.

The Board: a Wald interval for sigma squared built from the maximum likelihood estimate and the inverse-profile-curvature standard error, two hundred pairs, a thousand data sets. Coverage: zero. Not one of a thousand intervals contains the truth, because they're all centred on half of it.

Numbers: 0.502 vs 1.003; Board 0%

8EMMaster's6 min

The crabs' fit came from an algorithm built on one idea: pretend you know what you don't. We observe each crab's ratio. We don't observe which race it belongs to, if races there are. The likelihood of what we did observe is a log of a sum, one term per component, and setting its derivatives to zero gives equations nobody can solve by hand. But if the labels were known, the complete-data log likelihood would be a sum of logs: the proportion would be the share of race one, and each component's mean and spread would be the ordinary mean and spread of its own crabs.

So alternate. In the E-step, for expectation, use the current parameters to compute each crab's probability of belonging to race one: its responsibility. In the M-step, for maximization, refit as if the responsibilities were labels: the proportion is the average responsibility, and each mean and variance is a weighted mean and variance. Monitor likelihood changes, parameter changes and numerical diagnostics; a tiny likelihood increment alone need not establish parameter accuracy. Arthur Dempster, Nan Laird and Donald Rubin named the algorithm in 1977 and gave a general framework for many incomplete-data problems, although either step may still be difficult; special cases go back to the epidemiologist Anderson McKendrick in 1926 and to the Baum–Welch algorithm for hidden Markov models.

Here's the E-step at the final fit, on Weldon's histogram. Each interval's crabs are split between the races in proportion to their responsibilities: blue is the expected number from race one, red the expected number from race two. Almost every crab on the far left is blue; just left of the histogram's peak, at point six five three five, about a fifth are still blue, and in the far right tail blue creeps back, because race one is the broader. No crab is ever assigned outright; EM splits each one and fits the pieces.

Why does it work? Write the likelihood as a sum over the unseen labels, and multiply and divide by any distribution q for those labels. The log is concave, so by Jensen's inequality the log of an average is at least the average of the logs: a lower bound on the log likelihood. The bound is tight, equal, when q is the conditional distribution of the labels given the data at the current parameters, which is exactly what the E-step computes. So the E-step builds a lower bound that touches the log likelihood at the current point. Q is the expected complete-data log likelihood, and the M-step maximizes it.

Here's that picture along one coordinate, the mixing proportion, with the other four held at their estimates. The green curve is the log likelihood. Start at p equals point nine. The E-step builds the gold lower bound, touching the curve there. The M-step jumps to the bound's peak, and since the bound lies below the curve, the curve there is at least as high. Build a new bound at the new point, jump again, and again. Every step climbs. This is the minorize-maximize idea of Part 21, with the bound supplied by the missing data.

The full five-parameter run on the crabs started from p equals one half and ended at point four three. It took one thousand six hundred and twenty-two iterations. On a log scale, the gap between the current log likelihood and the attained local log-likelihood limit falls approximately along a straight line: linear convergence, the same fraction of the error gone each step. Here each step keeps ninety-nine point three six percent of the error in the parameters, so the gap, which is quadratic in the error, shrinks by about one point three percent per step. Newton's method from Part 21 would finish in a handful of steps, but unsafeguarded Newton can wander off or propose a negative variance. EM preserves nonnegative variance updates, yet can still approach a singular collapsed component. Practical software often runs EM first and finishes with Newton.

Near a regular isolated EM fixed point, the dominant linear convergence rate is an eigenvalue of the missing-information fraction matrix. Our successive-step estimate illustrates that local result. Thomas Louis turned this into a formula for standard errors in 1982: the observed information is the complete information minus the missing information. For the crabs the rate is point nine nine three six: the two races overlap so much that the labels, which would make the problem easy, are almost entirely unknown. The observed information gives a standard error for the proportion of point one five, so the local curvature approximation is forty-three percent plus or minus twenty-nine points. Weak separation and mixture irregularity limit the reliability of this Wald approximation. The means are pinned down to a few thousandths, but how the crabs divide between the races the data barely say.

Numbers: p 0.90 → 0.82 → 0.73 → 0.64; 1,622 iterations; rate 0.9936; SE(p̂) 0.150

9When likelihood misbehavesPractice5 min

The crabs' fit hides an embarrassment. Put the mean of race one exactly on one of the data values, here point six five three five, the midpoint of the busiest recorded interval. Then let its spread shrink. At first the fit gets worse, since race one no longer covers the other crabs. But a normal density at its own centre is one over sigma root two pi, which grows without limit. The gold line is the log likelihood of the fit we reported. Somewhere below a spread of ten to the minus seven, the spike passes it, and it keeps rising forever. Our midpoint approximation assigns the ninety-six crabs in this interval the same artificial exact value, so every factor of ten in sigma adds ninety-six times the log of ten. This unrestricted exact-value normal-mixture likelihood is unbounded. The true grouped-data likelihood is different.

There are four ways out. The honest one here: Weldon recorded intervals, not exact values. The likelihood of grouped data uses each interval's probability, which can never exceed one, so the spike disappears. Or forbid the spreads from being too unequal; Richard Hathaway showed in 1985 that the constrained maximum exists and is consistent. Or take the sensible local maximum, the one an appropriate algorithm may reach. Under suitable assumptions a consistent local root exists, but a reasonable start alone does not certify that we found it. Or penalize small variances, which amounts to a prior, and leads to Part 26's Bayesian view.

The second oddity. Run EM again with the starting values swapped, race one on the right. It converges to the same fit with the labels exchanged: the proportion becomes one minus itself, the means and spreads trade places, and the log likelihood is identical. A mixture of K components has K factorial identical peaks. For a single fit that's harmless. But anything that averages over fits, a bootstrap or a Markov chain sampler, can mix up labels and average race one with race two. The usual fix is an ordering constraint: call race one the one with the smaller mean.

The third oddity matters most for Weldon's real question: are there two races at all? The hypothesis of a single normal can be reached in several ways: a proportion of zero, or of one, or two identical components. Wilks's theorem, which made twice the log likelihood ratio chi-squared, needs the null value inside the parameter space, with every parameter identified. Here the null sits on the edge, and when the proportion is zero the other race's mean and spread mean nothing at all. John Hartigan showed in 1985 that the statistic doesn't settle to any chi-squared. Simpler edges have simpler answers: testing one scalar variance component at zero, with the other nuisance parameters regular, can give a fifty-fifty mixture of a point mass at zero and a chi-squared with one degree of freedom.

A bootstrap must calibrate an explicitly defined procedure. We draw two hundred samples from the fitted single normal, group every observation into intervals including overflow tails, and apply the same two-start EM improvement statistic to the real and simulated midpoint data. Each component's standard deviation is constrained to at least point zero zero two. This is not the undefined unrestricted mixture likelihood ratio. The reference histogram differs from naive chi-squared rules; special boundary theory requires additional assumptions. The gold line is its empirical ninety-fifth percentile. None of two hundred bootstrap statistics exceeds the observed value. The plus-one Monte Carlo estimate is about point zero zero five, not a proved upper bound on the true tail probability; the one-sided ninety-five percent binomial upper bound is about point zero one five. This approximate fitted-null procedure shows a strong improvement from a flexible mixture. It does not establish two biological races; one skewed population can also depart from a single normal.

Numbers: +221 per decade; swapped p = 0.567; constrained EM bootstrap 95th 7.79 vs 53.21

10MisspecificationPractice5 min

Misspecification: what happens when the model is wrong, as every model is. Suppose the data really come from some distribution g that isn't in our model at all. The average log likelihood still converges, by the law of large numbers, to the expected log density under the truth. That's minus the Kullback–Leibler divergence from the truth to the model, plus a term that doesn't depend on theta. With suitable uniform convergence, identification and a well-separated optimum, the estimate converges to theta star, the member of the model closest to the truth in Kullback–Leibler divergence: the truth's projection onto the model. When the model is right, the projection is the truth itself, and chapter two's consistency is the special case.

Here's a model that's wrong in an instructive way. Five thousand of the World's adult incomes, on a log scale. Fit a log-normal by maximum likelihood: a normal curve for log income. It looks reasonable. The median comes out right, within a hundred. The mean is a little low. But the World's incomes have a heavier upper tail than any log-normal: the fit says point oh seven percent of adults earn over three hundred thousand, and the truth is point three two percent, more than four times as many. The projection gets right what most of the data are about and wrong what few of them are about.

And the uncertainty? Chapter three's expansion still works, around theta star instead of the truth. But now two different matrices appear: A, the expected curvature, and B, the variance of the score, both computed under the true distribution. The root-n-scaled estimation error is asymptotically normal with covariance A inverse, B, A inverse; the estimate's covariance includes a further factor one over n: bread, meat, bread, the sandwich. Peter Huber derived it in 1967; Friedhelm Eicker had the regression case in 1963 and Halbert White brought it to economics in 1980. If the model is true, the information identity of chapter one says A equals B, the sandwich collapses to the inverse information, and we're back to the usual answer. Estimate A and B by their sample averages and you have asymptotic standard errors robust to distributional misspecification under the required sampling, moment and smoothness conditions.

In practice both matrices come from the fitted model. The bread is the observed information, averaged over observations. The meat is the average outer product of each observation's own score: it measures how much the scores actually vary, whatever the model claims. Combine them and divide by n. For least squares this is exactly the heteroskedasticity-robust covariance of Part 12, White's HC zero. If observations come in correlated clusters, add up the scores within each cluster before squaring: the cluster-robust sandwich, which Part 23 examines when there are few clusters.

An everyday case. Four hundred counts whose log mean rises linearly with a covariate, with a slope of point four, but generated from a negative binomial, so they're more variable than a Poisson model allows. The mean is two point one, the variance six point six, three times as large. Fit a Poisson regression anyway. The slope estimate is fine, point four seven, because the Poisson score equations only need the mean to be right. But the model-based standard error is too small: the sandwich is sixty percent larger, and a scalar quasi-Poisson adjustment is fairly close here. But our negative-binomial variance is mu plus mu squared over k, not a constant multiple of mu. A quasi-Poisson model-based SE is therefore not guaranteed valid; the sandwich estimates the required score variability.

To the Board: a thousand such data sets. Ninety-five percent intervals from the Poisson model's standard error cover the true slope seventy-seven percent of the time: broken. The same estimates with sandwich standard errors cover ninety-three percent: kept. The sandwich didn't fix the model; it stopped the model from lying about its precision.

Numbers: tail 0.07% vs 0.32%; SE 0.0333 / 0.0531 / 0.0497; Board 76.9% / 93.3%

11Quasi-, composite and pseudo-likelihoodMaster's4 min

Chapter ten fixed the standard errors after the fact. Robert Wedderburn's quasi-likelihood, from 1974, builds the doubt in from the start. Assume only how the mean depends on the covariates, and that the variance is some multiple phi of a known function of the mean. No distribution at all. Then solve the equations a likelihood's score would give: residuals, weighted by the variance, times the derivative of the mean. For counts they're exactly the Poisson equations, so the estimates are the same. Estimate phi from the Pearson residuals: two point two two for chapter ten's counts. Multiply the Poisson standard errors by its square root, and they come out close to the sandwich. The generalized estimating equations of Part 24 carry the same idea to correlated data.

Here's a model whose normalizing constant makes naive likelihood evaluation expensive: the Ising model, from physics, used in statistics for images and spatial data. Each site of a grid is plus or minus one, and the probability of a pattern grows with beta times the number of neighbouring pairs that agree. With beta at point three, a forty-eight by forty-eight lattice drawn by Gibbs sampling shows small patches. At point six, past the critical value near point four four, almost every site agrees: the lattice has magnetized.

The trouble is the normalizing constant. The probability of a pattern is the exponential of beta times its agreement score, divided by Z. Z is the sum of that exponential over every possible pattern. On our lattice that's two to the two thousand three hundred and four, about ten to the six hundred and ninety-three patterns. So the likelihood is a well-defined function whose naive enumeration is infeasible. Special zero-field two-dimensional Ising models do have exact methods; transfer-matrix, analytic and Monte Carlo approaches can exploit structure. The difficulty becomes more general with fields and irregular spatial models.

Julian Besag's way out, in 1975. A single site, given all the others, depends only on its four neighbours, and that conditional probability is a simple logistic function: the constant Z cancels. Multiply these conditionals over all sites. The product is generally not a normalized joint sampling density; the conditional factors reuse dependent sites, but it's a function of beta we can compute. Maximizing it is just a logistic regression of each site on its neighbour sum. With identifiable parameters and suitable increasing-domain and ergodicity conditions, pseudo-likelihood can be consistent, generally with an efficiency loss relative to regular full-likelihood inference, and its standard error needs chapter ten's sandwich, since the pseudo-likelihood's curvature doesn't equal its score's variance.

Does it work? Twelve independently seeded finite Gibbs runs at beta point three. Finite sweeps approximate equilibrium; this small study does not prove consistency. The pseudo-likelihood estimates average point two nine nine, with a spread of point oh one three: right on target. Each takes a fraction of a second. direct enumeration would require about ten to the six hundred and ninety-three terms. That count does not rule out structured exact methods.

Pseudo-likelihood is one member of a family Bruce Lindsay named composite likelihood in 1988: multiply together likelihoods of pieces of the data, each a genuine likelihood, ignoring their dependence. Pairwise likelihoods, for instance, use only the joint density of each pair of observations, which makes models for spatial extremes and statistical genetics feasible. Under correct component models, identification and suitable sampling regularity, estimates can be consistent. Their asymptotic covariance is a sandwich; its inverse is Godambe information. Likelihood-ratio tests need adjusting too, since the pieces' dependence breaks Wilks. The lesson of chapters ten and eleven: estimating equations can come from anywhere; the appropriate score covariance assesses their asymptotic precision. For dependent spatial sites that covariance must include dependence, not just independent-site outer products.

Numbers: φ̂ = 2.22; 10⁶⁹³ states; β̂ 0.299 ± 0.013

12The likelihood principlePhD4 min

Consider a sequence whose twelfth toss is its third tail, with nine heads in total. Is the coin biased towards heads? Alice had planned to toss twelve times. For her, the number of heads is binomial. Bob had planned to toss until the third tail. For him, the number of heads is negative binomial, with a different constant in front. As functions of theta, the two likelihoods are proportional: the same curve, rescaled.

Here is Alice's likelihood, scaled to peak at one. Bob's, dashed, lies exactly on top of it. Both peak at three quarters. The observed data have about a fifth as much likelihood under a fair coin as under the fitted probability. This is not a posterior probability that the coin is fair. If the likelihood is all the data have to say about theta, then Alice and Bob have the same evidence, and should reach the same conclusion.

Now compute p-values for a fair coin. A p-value asks about outcomes at least as extreme as the one observed, and those outcomes depend on the plan. Alice's possible results are zero to twelve heads; nine or more has probability point oh seven three. Bob's possible results are any number of heads before the third tail, with no upper limit; nine or more has probability point oh three three. At the five percent level, Alice can't reject a fair coin and Bob can, from the same tosses. The difference lies entirely in outcomes that didn't happen.

A Bayesian with Part 15's uniform prior sees no difference at all. The posterior is proportional to prior times likelihood, the constants in front cancel, and both Alice and Bob get a beta with parameters ten and four. The posterior probability that the coin favours heads is point nine five four, for both. Their ninety-five percent credible intervals are identical too, point four six to point nine one. For these theta-free stopping rules and the same fixed prior, the stopping factor cancels. Informative sampling or selection and data-dependent prior choices must be modeled.

In 1962 Allan Birnbaum turned this into a theorem that alarmed his colleagues. Start from two principles almost everyone accepts. Sufficiency: two data sets with the same sufficient statistic carry the same evidence. Conditionality: if a coin flip chose which of two experiments to run, judge the result by the experiment actually run, the idea behind chapter four's conditioning, and David Cox's 1958 example of two measuring instruments. Birnbaum showed that together they imply the likelihood principle: experiments with proportional likelihoods give the same evidence. Bayesian updating with the same fixed prior obeys it when the full sampling and stopping likelihoods are proportional. Conventional p-values and confidence procedures generally use sampling distributions beyond the observed likelihood. Their operating properties depend on the plan. And for a Bayesian, a stopping rule doesn't matter.

Jimmie Savage, discussing the paper, said the likelihood principle had striking implications for statistical inference. Savage had already published his Bayesian Foundations of Statistics in 1954. Birnbaum himself later had doubts, and Deborah Mayo argued in 2014 that the proof has a gap: the conditionality principle is being applied where it doesn't belong. Others have repaired and re-attacked the argument since; the debate is open. For this series, the practical answer is that coverage is a property of a procedure, and the procedure includes the plan. An analyst who peeks at the data and stops when the result looks good does change the Board's verdict, even when the final likelihood is the same. Part 58 builds tests that stay valid however you stop.

Numbers: p = 0.073 vs 0.033; P(θ > ½) = 0.954

13Information geometry, a glimpsePhD3 min

The Kullback–Leibler divergence between two nearby members of a family is, to second order, half a quadratic form in the information matrix. C. R. Rao took that seriously in 1945: use the information as a metric, a ruler that varies from place to place, so the family of distributions becomes a curved space. For the normal family, the squared length of a small step is d mu squared plus two d sigma squared, all over sigma squared. Because it's built from the distributions themselves, these distances don't depend on how we label the parameters.

Here's the normal family as a plane: mean across, standard deviation up. Each gold ellipse approximates a small ball in the local Fisher metric at its centre, the ones equally hard to tell apart from it with a fixed amount of data. Near the bottom, narrow normals, the ellipses are tiny: move the mean a little and the difference is obvious. Higher up, wide normals, they're large. With the mean rescaled by root two, this is exactly the hyperbolic plane of non-Euclidean geometry.

Curved spaces have curved shortest paths. Go from a narrow normal centred at minus two to the same normal centred at plus two. Sliding the mean straight across has Fisher length ten. The geodesic, the shortest path in this metric, is an arc, and its length is only about five point six. It first widens the distribution, moves it while it's wide and the move is cheap, then narrows it again: the densities in the inset.

The geometry pays off in optimization. The ordinary gradient points uphill in the coordinates we happened to choose; rescale a parameter and it points somewhere else. Shun-ichi Amari's natural gradient, from 1998, points uphill in the Fisher metric instead: multiply the gradient by the inverse information. Using the full-sample information n I with the summed log-likelihood gradient, a unit step is Fisher scoring from Part 21. The vector field transforms invariantly; a finite coordinate Euler step need not be exactly invariant under nonlinear reparametrization. Approximations to it train large neural networks and drive variational inference, which Parts 27 and 64 will meet.

And it gives Bayesians a prior. A metric has a volume element, the square root of the determinant of the information. Harold Jeffreys proposed in 1946 to use it as a prior: spread belief evenly in the geometry, not in an arbitrary parametrization, so the answer doesn't depend on the parametrization. For a binomial proportion it's the beta of one half, one half, behind Part 11's Jeffreys interval. For the joint normal mean and standard deviation, its density with respect to d mu d sigma is one over sigma squared. This prior is improper, and posterior propriety must be checked. Part 26 takes up priors in earnest.

Numbers: geodesic 5.6 vs 10.0

Recap, problems, and the road aheadAll tracks3 min

Part twenty-two in fourteen lines. Pearson split Weldon's crabs with a ninth-degree polynomial; a midpoint-density local fit improved the likelihood. Our six-item checklist summarizes assumptions; precise theorems need additional integrability and information conditions. Consistency follows from the Kullback–Leibler inequality and the argmax of a converging curve; asymptotic normality from expanding the score. Observed information tracked conditional variance well in the Cauchy example. With many parameters, profile along the ridge. Wald, score and likelihood-ratio tests read one curve three ways, and can disagree badly. Neyman and Scott's incidental parameters halve the variance forever. EM climbs a lower bound built from the missing labels, surely but slowly. Mixture likelihoods spike, switch labels, and sit on edges. Under a wrong model the estimate finds the closest wrong answer, and a sandwich estimates asymptotic precision under its own sampling and regularity assumptions. Quasi-, composite and pseudo-likelihoods replace likelihoods we can't write down. The likelihood principle asks whether unseen outcomes should matter. And the information is a ruler on the space of distributions.

Where it comes back. Part 24 builds generalized linear models on quasi-likelihood, and GEE on the sandwich. Part 25's restricted likelihood cures Neyman–Scott for mixed models. Part 26 derives Jeffreys and reference priors from the information. Part 27's variational inference is EM's cousin. Part 28's AIC is an estimate of the Kullback–Leibler divergence. Part 30's M-estimators carry the sandwich everywhere. Part 41 uses EM for missing data. And Part 47 rebuilds this part's asymptotics on Le Cam's local asymptotic normality, where Hodges's estimator finally gets its explanation.

Six problems, with full solutions in the README. The score identities for the Poisson; Neyman–Scott with m readings per group; the trinity for fourteen of twenty, by hand; EM for the mixing proportion alone, and why it climbs; the sandwich for an intercept-only Poisson model; and Alice's and Bob's p-values. Pause here if you want to try them.

The books this part follows: Pawitan's In All Likelihood, van der Vaart's Asymptotic Statistics, Cox's Principles of Statistical Inference, and McLachlan and Krishnan on EM; with the papers from Pearson's crabs to Amari's natural gradient.

Twenty-two parts of sixty-five. We know now why likelihood works, when it fails, and how to keep its standard errors honest when the model is wrong. Next, the linear model in full. In 1967 James Longley ran a small, awkward data set through the era's regression programs, and many of them printed wrong digits. Part 23: the linear model in depth.

Where it goes next. The sandwich returns clustered in Part 23 and for M-estimators in Part 30; quasi-likelihood and GEE in Part 24; REML cures Neyman-Scott in Part 25; Jeffreys's prior returns in Part 26, AIC as an estimate of KL in Part 28, EM for missing data in Part 41, and Hodges and Le Cam in Part 47.

Key results

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

Consistency through KL\(\displaystyle M(\theta)=\mathbb{E}_{\theta_0}\log f(X;\theta),\qquad\allowbreak M(\theta_0)-M(\theta)=\operatorname{KL}(f_{\theta_0}\,\|\,f_\theta)\ge 0\)
Asymptotic normality\(\displaystyle \sqrt n\,(\hat\theta-\theta_0)\xrightarrow{d}N\bigl(0,\,I(\theta_0)^{-1}\bigr)\)
The trinity\(\displaystyle W=(\hat\theta-\theta_0)^2\,nI(\hat\theta),\quad\allowbreak S=\frac{U(\theta_0)^2}{nI(\theta_0)},\quad\allowbreak \Lambda=2\bigl[\ell(\hat\theta)-\ell(\theta_0)\bigr],\quad\allowbreak \text{each}\xrightarrow{d}\chi^2_1\text{ under }H_0\)
Neyman-Scott\(\displaystyle x_{i1},x_{i2}\sim N(\mu_i,\sigma^2):\qquad\allowbreak \hat\sigma^2=\frac{1}{4n}\sum_{i=1}^n(x_{i1}-x_{i2})^2\xrightarrow{p}\frac{\sigma^2}{2}\)
EM's lower bound\(\displaystyle \ell(\theta)\ge\ell(\theta_t)+Q(\theta\mid\theta_t)-Q(\theta_t\mid\theta_t)\ \Longrightarrow\ \ell(\theta_{t+1})\ge\ell(\theta_t)\)
The sandwich\(\displaystyle \sqrt n\,(\hat\theta-\theta^*)\xrightarrow{d}N\bigl(0,\,A^{-1}BA^{-1}\bigr),\qquad\allowbreak A=-\mathbb{E}_g\nabla^2\log f(X;\theta^*),\ B=\operatorname{Var}_g\nabla\log f(X;\theta^*)\)

Try it

Lab 22 · The sandwich under a wrong variance, and Neyman-Scott

Fit a Poisson regression 600 times to Poisson counts and to negative-binomial counts with the same mean, and compare the slope's true spread with the model-based and the sandwich standard errors; then watch the MLE of a variance converge to half the truth when every pair has its own mean.

Figure produced by Lab 22: The sandwich under a wrong variance, and Neyman-Scott
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.stats.labs 22 needs numpy, scipy, matplotlib · download lab22.py · source on GitHub
Poisson counts: mean slope                      0.401   (truth 0.4)
Poisson counts: true sd of the slope            0.0375   model SE 0.0376   sandwich SE 0.0372
Poisson counts: 95% interval covers             model 95.2%   sandwich 94.7%
negative binomial counts: mean slope            0.398   (truth 0.4)
negative binomial counts: true sd of the slope  0.0585   model SE 0.0377   sandwich SE 0.0590
negative binomial counts: 95% interval covers   model 78.3%   sandwich 95.2%
Neyman-Scott, 10,000 pairs: MLE of sigma^2      0.499   (truth 1, limit 0.5)
Neyman-Scott, 10,000 pairs: divide by 2n        0.997   (truth 1)

A wrong variance leaves the slope consistent but makes the model's standard error too small, and the sandwich measures the spread the scores really have; with a new mean per pair, more data never repairs the MLE of the variance.
The code (74 lines; it asserts its own result)
"""Lab 22: fit a Poisson regression to overdispersed counts, and see which standard error tells the truth."""

import numpy as np

from videos.coursekit import labs
from explainer.stats.kit import mle

TITLE = "The sandwich under a wrong variance, and Neyman-Scott"
GOAL = ("Fit a Poisson regression 600 times to Poisson counts and to negative-binomial counts with the same mean, and "
        "compare the slope's true spread with the model-based and the sandwich standard errors; then watch the MLE of "
        "a variance converge to half the truth when every pair has its own mean.")
TASKS = [
    "Raise the negative binomial's k from 1.5 to 50. At what k do the model-based intervals cover 95% again?",
    "Use the quasi-Poisson standard error (fit['se_quasi']). Why is it close here, and for which variance is it exact?",
    "Give each group m = 5 readings instead of 2 in the Neyman-Scott check. What does the MLE converge to now?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, reps, beta, k = 400, 600, (0.5, 0.4), 1.5
    lab = labs.Lab()
    out = {}
    for name in ("Poisson", "negative binomial"):
        slopes, se_m, se_s, cov_m, cov_s = [], [], [], 0, 0
        for _ in range(reps):
            x = rng.normal(size=n)
            mu = np.exp(beta[0] + beta[1] * x)
            y = rng.poisson(mu) if name == "Poisson" else rng.negative_binomial(k, k / (k + mu))
            f = mle.poisson_regression(np.column_stack([np.ones(n), x]), y)
            b, sm, ss = f["b"][1], f["se_model"][1], f["se_sandwich"][1]
            slopes.append(b)
            se_m.append(sm)
            se_s.append(ss)
            cov_m += abs(b - beta[1]) < 1.96 * sm
            cov_s += abs(b - beta[1]) < 1.96 * ss
        r = out[name] = dict(slopes=np.array(slopes), sd=np.std(slopes), se_m=np.mean(se_m), se_s=np.mean(se_s),
                             cov_m=cov_m / reps, cov_s=cov_s / reps)
        lab.row(f"{name} counts: mean slope", f"{r['slopes'].mean():.3f}   (truth {beta[1]})")
        lab.row(f"{name} counts: true sd of the slope", f"{r['sd']:.4f}   model SE {r['se_m']:.4f}   sandwich SE {r['se_s']:.4f}")
        lab.row(f"{name} counts: 95% interval covers", f"model {r['cov_m']:.1%}   sandwich {r['cov_s']:.1%}")
    ns = [mle.neyman_scott(n_pairs, 1.0, rng) for n_pairs in (10, 30, 100, 300, 1000, 3000, 10000)]
    lab.row("Neyman-Scott, 10,000 pairs: MLE of sigma^2", f"{ns[-1]['mle']:.3f}   (truth 1, limit 0.5)")
    lab.row("Neyman-Scott, 10,000 pairs: divide by 2n", f"{ns[-1]['fixed']:.3f}   (truth 1)")
    lab.note = ("A wrong variance leaves the slope consistent but makes the model's standard error too small, and the "
                "sandwich measures the spread the scores really have; with a new mean per pair, more data never "
                "repairs the MLE of the variance.")
    p, nb = out["Poisson"], out["negative binomial"]
    assert abs(p["slopes"].mean() - beta[1]) < 0.01 and abs(nb["slopes"].mean() - beta[1]) < 0.02, "the mean model is right"
    assert abs(p["se_m"] / p["sd"] - 1) < 0.1 and abs(p["se_s"] / p["sd"] - 1) < 0.1, "A = B when the model is true"
    assert abs(p["cov_m"] - 0.95) < 0.035, "model-based intervals work for Poisson counts"
    assert nb["se_m"] / nb["sd"] < 0.75 and nb["cov_m"] < 0.87, "the model SE understates under overdispersion"
    assert abs(nb["se_s"] / nb["sd"] - 1) < 0.15 and nb["cov_s"] > 0.90, "the sandwich tracks the true spread"
    assert abs(ns[-1]["mle"] - 0.5) < 0.03 and abs(ns[-1]["fixed"] - 1) < 0.06, "Neyman-Scott: sigma^2 / 2"

    fig, ax = labs.figure(2, size=(11, 4.2))
    bins = np.linspace(beta[1] - 4 * nb["sd"], beta[1] + 4 * nb["sd"], 50)
    ax[0].hist(nb["slopes"], bins=bins, density=True, color=labs.BLUE, alpha=0.6, label="600 fitted slopes")
    for se, color, name in ((nb["se_m"], labs.RED, "model SE"), (nb["se_s"], labs.GREEN, "sandwich SE")):
        ax[0].plot(bins, np.exp(-0.5 * ((bins - beta[1]) / se) ** 2) / (se * np.sqrt(2 * np.pi)), color=color,
                   label=f"normal with the {name}")
    ax[0].set(title="Overdispersed counts: which SE matches the spread?", xlabel="fitted Poisson slope",
              ylabel="density")
    ax[0].legend(loc="upper left", fontsize=8)
    sizes = [10, 30, 100, 300, 1000, 3000, 10000]
    ax[1].semilogx(sizes, [r["mle"] for r in ns], "o-", color=labs.RED, label="MLE: divide by 4n")
    ax[1].semilogx(sizes, [r["fixed"] for r in ns], "o-", color=labs.GREEN, label="contrasts: divide by 2n")
    ax[1].axhline(1.0, color=labs.MUTED, ls="--", lw=1)
    ax[1].axhline(0.5, color=labs.MUTED, ls=":", lw=1)
    ax[1].set(title="Neyman-Scott: more pairs do not help the MLE", xlabel="number of pairs",
              ylabel="estimate of σ² (truth 1)", ylim=(0, 1.8))
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Raise the negative binomial's k from 1.5 to 50. At what k do the model-based intervals cover 95% again?
  2. Use the quasi-Poisson standard error (fit['se_quasi']). Why is it close here, and for which variance is it exact?
  3. Give each group m = 5 readings instead of 2 in the Neyman-Scott check. What does the MLE converge to now?

Problems, with solutions

Try each problem before opening its solution.

1. Poisson score identities. Poisson: the score is \(U = x/\lambda - 1\). Show \(E\,U = 0\) and \(\mathrm{Var}\,U = -E\,U' = 1/\lambda\).

Solution

log f = x log λ − λ − log x!, so U = x/λ − 1 and U' = −x/λ².

  • Mean. E U = λ/λ − 1 = 0.
  • Variance. Var U = Var(x)/λ² = 1/λ.
  • The identity. −E U' = λ/λ² = 1/λ, so Var U = −E U' = I(λ).

2. Neyman–Scott with m readings per group. Neyman–Scott with \(m\) readings per group: show \(\hat\sigma^2 \to (m - 1)\sigma^2/m\). What fixes it?

Solution

The MLE of each μᵢ is the group mean x̄ᵢ, and σ̂² = (1/(nm)) Σᵢ Σⱼ (xᵢⱼ − x̄ᵢ)². Each group's sum of squares has expectation (m − 1)σ², so E σ̂² = (m − 1)σ²/m. Being an average of n independent terms, σ̂² converges to that, not to σ². Dividing by n(m − 1) instead fixes it, and is exactly what the marginal likelihood of the within-group contrasts (or REML) gives. The bias vanishes only as m → ∞, not as n → ∞.

3. The trinity by hand. Fourteen successes in twenty, \(H_0\colon p = 0.5\): check \(W = 3.81\), \(S = 3.20\), \(\Lambda = 3.29\).

Solution

p̂ = 0.7, n = 20, p₀ = 0.5.

  • Wald. W = (0.7 − 0.5)² / (0.7 × 0.3/20) = 0.04/0.0105 = 3.81.
  • Score. U(p₀) = (14 − 10)/(p₀(1 − p₀)) and nI(p₀) = 20/0.25, so S = (14 − 10)²/(20 × 0.25) = 16/5 = 3.20.
  • Likelihood ratio. Λ = 2[14 log(0.7/0.5) + 6 log(0.3/0.5)] = 2[4.711 − 3.065] = 3.29.

4. EM for the mixing proportion alone. EM for \(p\) alone, the components known: show \(p_{t+1} = \bar r(p_t)\) and that \(\ell(p_{t+1}) \ge \ell(p_t)\).

Solution

With the components φ₁, φ₂ known, the E-step gives rᵢ = pφ₁(xᵢ)/(pφ₁(xᵢ) + (1 − p)φ₂(xᵢ)). The expected complete-data log likelihood is Q(p) = Σ[rᵢ log p + (1 − rᵢ) log(1 − p)] + const, maximized at p = Σrᵢ/n = r̄(pₜ). By Jensen, ℓ(p) ≥ ℓ(pₜ) + Q(p | pₜ) − Q(pₜ | pₜ), with equality at pₜ. Since pₜ₊₁ maximizes Q, Q(pₜ₊₁ | pₜ) ≥ Q(pₜ | pₜ), so ℓ(pₜ₊₁) ≥ ℓ(pₜ).

5. The sandwich for an intercept-only Poisson model. Intercept-only Poisson fitted to any counts: the sandwich SE of \(\log\hat\mu\) is \(\sqrt{s^2/(n\bar y^2)}\).

Solution

With log μ = β, the score is Uᵢ = yᵢ − e^β and the MLE is e^β̂ = ȳ.

  • The bread. A = Σ e^β = nȳ.
  • The meat. B = Σ(yᵢ − ȳ)² = ns², where s² = Σ(yᵢ − ȳ)²/n.
  • The sandwich. Var(β̂) ≈ B/A² = ns²/(nȳ)² = s²/(nȳ²), so SE = √(s²/(nȳ²)).

The model-based SE is √(1/(nȳ)), and they agree exactly when s² = ȳ, that is when the counts show Poisson dispersion.

6. Alice and Bob. Alice and Bob: verify \(P(X \ge 9) = 0.073\) (binomial) and \(0.033\) (heads before the 3rd tail).

Solution
  • Alice. Under the fair coin, X ~ Binomial(12, ½), and P(X ≥ 9) = (220 + 66 + 12 + 1)/4096 = 299/4096 = 0.073.
  • Bob. The number of heads H before the 3rd tail has P(H = h) = C(h + 2, 2)/2^{h+3}. Then P(H ≥ 9) = 1 − Σ_{h=0}^{8} C(h + 2, 2)/2^{h+3} = 134/4096 = 0.0327. Equivalently, it is the probability of at most two tails in the first eleven tosses: (1 + 11 + 55)/2048 = 67/2048.

Notes and sources

Where it comes back

Idea Returns in
clustered sandwiches; models as approximations 23
GLMs, quasi-likelihood, GEE 24
REML: Neyman–Scott cured 25
Jeffreys and reference priors 26
variational inference, EM's cousin 27
AIC as an estimate of KL 28
M-estimators and the sandwich 30
EM for missing data 41
LAN, Hodges and Le Cam 47
the Coverage Board every part; 65

Glossary

  • Score; Fisher information; information identity: ∂ log f/∂θ; its variance; Var U = −E U'.
  • Regularity conditions: a sufficient checklist includes fixed support, interior truth, suitable integrable local derivative envelopes, identifiability, nonsingular information, fixed dimension and a true model; consistency and uniformity assumptions must also be verified in the applicable theorem.
  • Consistency; argmax theorem: θ̂ → θ₀; the peak of a converging curve converges to the limit's peak.
  • Kullback–Leibler divergence: E_g log(g/f) ≥ 0, zero only when f = g.
  • Asymptotic normality; efficiency: √n(θ̂ − θ₀) → N(0, I⁻¹); attaining the Cramér–Rao bound in the limit.
  • Observed vs expected information: −ℓ''(θ̂) for this sample; nI(θ̂), its average over samples.
  • Ancillary statistic; conditionality: a statistic whose distribution is free of θ; judging by the experiment actually done.
  • Information matrix; profile likelihood; nuisance parameter: curvature in every direction; ℓ maximized over the nuisance; a parameter we must estimate but do not care about.
  • Wald, score (Rao) and likelihood-ratio (Wilks) tests: distance in SEs at θ̂; slope at θ₀; height drop.
  • Hauck–Donner effect: the Wald statistic falling as the evidence grows.
  • Incidental parameters; Neyman–Scott problem: parameters whose number grows with n; the inconsistent MLE they cause.
  • Marginal, conditional and restricted (REML) likelihood: appropriate nuisance-free sampling likelihoods; profile likelihood is generally not itself a sampling density.
  • EM algorithm; responsibility; missing-information principle: alternate expectation and maximization; the posterior probability of a label; I_obs = I_complete − I_missing.
  • Unbounded likelihood; label switching; boundary parameter: a likelihood with no maximum; K! identical peaks; a null on the edge of the space, where Wilks fails.
  • Parametric bootstrap: simulating from the fitted null model to get a reference distribution.
  • Misspecification; KL projection; sandwich (Huber–White): a model without the truth; its closest member; A⁻¹BA⁻¹/n for the estimator under IID regularity.
  • Quasi-likelihood; dispersion φ: estimating equations from a mean and variance function; the variance multiple.
  • Composite and pseudo-likelihood; Godambe information: products of likelihoods of pieces; Besag's product of conditionals; the sandwich that measures them.
  • Ising model; normalizing constant: a lattice of ±1 spins; the sum Z that makes probabilities add to one.
  • Likelihood principle; sufficiency principle; stopping rule: proportional likelihoods give the same evidence; equal sufficient statistics do; when to stop collecting data.
  • Fisher metric; geodesic; natural gradient; Jeffreys prior: the information as a ruler; the shortest path; the gradient in that ruler; √det I.

Sources

  • History.
    • W. F. R. Weldon, Proc. Roy. Soc. 54 (1893); K. Pearson, Phil. Trans. A 185 (1894).
    • R. A. Fisher, Phil. Trans. A 222 (1922); Proc. Roy. Soc. A 144 (1934).
    • A. Wald, Ann. Math. Stat. 20 (1949); J. Neyman & E. Scott, Econometrica 16 (1948).
    • C. R. Rao, Bull. Calcutta Math. Soc. 37 (1945); Proc. Camb. Phil. Soc. 44 (1948).
  • Methods.
    • B. Efron & D. Hinkley, Biometrika 65 (1978); W. Hauck & A. Donner, JASA 72 (1977).
    • D. R. Cox & N. Reid, JRSS B 49 (1987); E. B. Andersen, JRSS B 32 (1970).
    • A. Dempster, N. Laird & D. Rubin, JRSS B 39 (1977); T. Louis, JRSS B 44 (1982).
    • R. Redner & H. Walker, SIAM Review 26 (1984); R. Hathaway, Ann. Stat. 13 (1985); J. Hartigan (1985); S. Self & K.-Y. Liang, JASA 82 (1987); J. Chen, X. Tan & R. Zhang, Stat. Sinica 18 (2008).
    • P. Huber (1967), 5th Berkeley Symposium; H. White, Econometrica 48 (1980) and 50 (1982).
    • R. Wedderburn, Biometrika 61 (1974); J. Besag, The Statistician 24 (1975); B. Lindsay, Contemp. Math. 80 (1988); C. Varin, N. Reid & D. Firth, Stat. Sinica 21 (2011).
    • A. Birnbaum, JASA 57 (1962); D. Mayo, Stat. Sci. 29 (2014); M. Evans, EJS 7 (2013).
    • S. Amari, Neural Computation 10 (1998); H. Jeffreys, Proc. Roy. Soc. A 186 (1946).
  • Books.
    • Y. Pawitan, In All Likelihood (2001).
    • A. W. van der Vaart, Asymptotic Statistics (1998).
    • D. R. Cox, Principles of Statistical Inference (2006).
    • G. McLachlan & T. Krishnan, The EM Algorithm and Extensions (2nd ed., 2008).
About this partfrom its README

Part 22 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the second part of Stage III, Master's. Part 9 introduced maximum likelihood and made two promises: the estimator is consistent, and approximately normal with variance 1/(nI). This part proves both, says exactly what they need, and shows what happens when each condition fails: when the parameters multiply, when the likelihood has no maximum, when the truth sits on an edge, and when the model is simply wrong.

It opens in Naples in 1893. Walter Frank Raphael Weldon measured the forehead breadth of 1,000 shore crabs, found the histogram lopsided, and asked Karl Pearson whether it was two normal curves added together. Pearson matched five moments and solved a ninth-degree polynomial by hand. Our multistart numerical search finds two admissible moment solutions, A (p = 0.533) and B (p = 0.424). B's sixth moment, 7.76 × 10⁻¹⁰, is closer to the data's 7.45, so B is the one Pearson's rule would keep. An interior local EM fit to a midpoint-density approximation puts 43% of the crabs at 0.6317 (SD 0.0183) and 57% at 0.6546 (SD 0.0126). The unrestricted exact-value mixture likelihood has no global maximum; the grouped interval-probability likelihood is a different, bounded problem. This local fit's log likelihood is 2567.58, against 2567.49 for moments B and 2540.97 for a single normal.

From there the part covers:

  • Consistency (Wald 1949).
    • The average log likelihood converges to M(θ) = E log f(X; θ), and M(θ₀) − M(θ) is a KL divergence, so θ₀ is M's unique peak.
    • Average log-likelihood curves for one growing stream of Poisson counts at Bortkiewicz's rate 0.61 peak at 1.1, 0.68, 0.638 and 0.6103 for n = 10, 100, 1,000 and 10,000.
    • Uniform convergence plus a well-separated peak gives consistency.
  • Asymptotic normality.
    • Expand the score: the CLT for the numerator, the LLN for the denominator, Slutsky.
    • For the Cauchy (no mean, no variance), 4,000 samples of 50: the MLE's SD is 0.208 against a theory of 0.200; the median's is 0.229 against 0.222.
    • The variance ratio is 1.22. Cramér–Rao, and Hodges's fine print.
  • Observed vs expected information (Efron & Hinkley 1978).
    • 8,000 Cauchy samples of 20, sorted into quarters by observed information J.
    • the safeguarded numerical location fit's Monte Carlo variance falls from 0.167 to 0.070, and 1/J tracks it (0.167 to 0.066). The expected information says 0.10 for every sample.
    • Ancillaries from location-equivariant estimates and conditional precision; observed information does not universally dominate in finite samples.
  • Many parameters.
    • A gamma fitted to 150 of the World's incomes: shape 2.28, rate 0.0473, correlation 0.89.
    • The likelihood landscape, analytic nuisance ridge and profile likelihood. The joint two-parameter 95% drop is about 3.0; the one-target profile cutoff is 1.92.
    • Profile interval [1.83, 2.80] vs Wald [1.80, 2.76]; modified profiles. Profiling already accounts for nuisance uncertainty to first order; higher-order bias can remain.
  • The trinity.
    • Wald, score and LR as three readings of one curve. For 14 of 20 against p = ½: W = 3.81, S = 3.20, Λ = 3.29, with p-values 0.051 to 0.074: all fail to reject at 5% in this example.
    • Inverting them gives the Wald, Wilson and LR intervals.
    • Hauck–Donner in logistic regression (n = 60): the Wald |z| peaks at 3.77 and falls back to 3.05 as the true slope rises to 7, while √Λ climbs to 7.87.
  • Neyman–Scott (1948).
    • Pairs with their own means: the MLE of σ² converges to σ²/2.
    • 300 data sets of 1,000 pairs give 0.502 (truth 1); dividing by 2n gives 1.003.
    • Why this incidental-parameter profile fails; contrast/marginal and appropriate conditional likelihoods, REML. The Board uses inverse-profile-curvature SE sigma-squared-hat / sqrt(n). Growing nuisance dimension is not automatically inconsistent in every model.
  • EM (Dempster, Laird & Rubin 1977).
    • E- and M-steps for the crabs; each crab split by its responsibility.
    • Jensen's lower bound, drawn along p: 0.90 → 0.82 → 0.73 → 0.64 → 0.57 → … → 0.43.
    • 1,622 iterations, linear convergence at rate 0.9936.
    • The missing-information principle and SEs from an implemented Louis information identity: SE(p̂) = 0.150, so p̂ = 0.43 ± 0.29.
  • When likelihood misbehaves.
    • Under the midpoint-density approximation, put μ₁ on one assigned midpoint and shrink σ₁: the log likelihood passes the reported local fit's near σ₁ = 10⁻⁷ and rises 221 per decade (96 interval counts are assigned that artificial exact value). Actual grouped probabilities remain bounded. Cures.
    • Label switching: the swapped start converges to p = 0.567 with the labels exchanged.
    • Boundary nulls. A parametric bootstrap calibrates a specified two-start EM improvement statistic with component SDs constrained to at least 0.002, using the same procedure on observed and null data. Its 200 refits give a 95th percentile of 7.79 against the crabs' 53.21. Zero exceedances give a plus-one Monte Carlo estimate 1/201 = 0.00498, not an upper bound; the one-sided 95% binomial upper limit is 0.0149. The unrestricted global density-mixture LR is undefined, so this procedure is explicitly distinguished from it.
  • Misspecification (Huber 1967; White 1982).
    • The KL projection: a log-normal fitted to 5,000 World incomes gets the median right (39.0k vs 38.9k) and the top tail wrong (0.07% over 300k vs 0.32%).
    • The sandwich derived and estimated.
    • Poisson regression of negative-binomial counts (mean 2.11, variance 6.60): the slope estimate is 0.472 (truth 0.4), but the model SE is 0.0333 against a sandwich SE of 0.0531 and a quasi-Poisson SE of 0.0497. The negative-binomial variance is mu + mu²/k, so constant-dispersion quasi-Poisson SEs are only an approximate comparison here, not guaranteed valid.
    • Two Board rows.
  • Quasi-, composite and pseudo-likelihood.
    • Wedderburn's quasi-likelihood, with φ̂ = 2.22.
    • The Ising model on a 48 × 48 lattice: naive enumeration of Z sums over 2²³⁰⁴ ≈ 10⁶⁹³ patterns. Special zero-field two-dimensional models have exact methods; the state count alone does not prove computational impossibility.
    • Besag's pseudo-likelihood on 12 lattices at β = 0.3: mean 0.299, SD 0.013. Consistency needs identification, spatial asymptotics and ergodicity; finite Gibbs runs only approximate equilibrium. Composite covariance is a sandwich; its inverse is Godambe information and dependent-site scores need spatial covariance estimation.
  • The likelihood principle (Birnbaum 1962).
    • Nine heads and three tails under two plans. Same likelihood, but the binomial p-value is 0.073 and the negative-binomial one is 0.033.
    • With the same fixed prior and these theta-free stopping rules, Beta(10, 4) for both: P(θ > ½) = 0.954. The shared sequence must have its third tail on toss 12. Informative sampling/selection needs modeling.
    • Sufficiency plus conditionality; Savage, Mayo, and the Board's stake in stopping rules.
  • Information geometry.
    • Rao's metric; the normal family as a hyperbolic plane.
    • The geodesic from N(−2, 0.4²) to N(2, 0.4²) has Fisher length 5.6, against 10.0 for sliding the mean.
    • The natural gradient with full-sample information nI (unit step gives Fisher scoring) and Jeffreys's prior. Coordinate Euler steps are only locally invariant; drawn ellipses approximate small metric balls. Joint normal Jeffreys density is 1/sigma² in dmu dsigma and is improper.

Every number on screen is computed in compute.py:

  • Weldon's crabs are the Museum's;
  • incomes come from the World;
  • the rest are seeded simulations or worked examples.

Built in this part:

  • statkit.mle (explainer/stats/kit/mle.py), checked in tests/test_stats_kit_mle.py:
    • numerical Hessians;
    • the two-normal mixture likelihood, EM with its rate, and Pearson's moment equations (multistart solutions and the sixth moment);
    • the binomial trinity, logistic Wald/LR tests and profile intervals;
    • the gamma profile;
    • Neyman–Scott;
    • Poisson regression with model, sandwich and quasi-Poisson SEs;
    • the Cauchy MLE and observed information;
    • Ising Gibbs sampling and Besag's pseudo-likelihood.
  • The likelihood landscape (LikelihoodLandscape in explainer/stats/viz.py): a Landscape whose contours are drawn at fixed drops below the peak, with its peak, profile ridge and profile curve.
  • The Museum: Weldon's crabs as Pearson printed them (CRAB_UPPER, CRAB_COUNT, crabs()), checked against the pearson data of the CRAN package mixdist.

The Coverage Board gains five rows:

Method Setting Reps Achieved Verdict
Wald CI, logistic slope β = 2.5, n = 50 1,000 96.9% kept
profile-likelihood CI β = 2.5, n = 50 1,000 93.3% kept
MLE of σ², Wald CI Neyman–Scott, 200 pairs 1,000 0.0% broken
Poisson model SE overdispersed counts, n = 400 1,000 76.9% broken
sandwich SE overdispersed counts, n = 400 1,000 93.3% kept
Chapter notes
# Chapter Numbers
0 Weldon's crabs, 1893 moments A p = 0.533, B p = 0.424; sixth moments 7.88, 7.76 vs 7.45; ML log lik 2567.58
1 Upgrade: what Part 9 promised six conditions; tanks: n(θ − θ̂)/θ → Exponential(1)
2 Consistency peaks 1.1, 0.68, 0.638, 0.6103 → 0.61
3 Asymptotic normality Cauchy n = 50: SD 0.208 (0.200) vs median 0.229 (0.222); ratio 1.22
4 Observed vs expected information Var 0.167 → 0.070; 1/J 0.167 → 0.066; 1/(nI) = 0.10
5 Many parameters â = 2.28, b̂ = 0.0473, corr 0.89; profile [1.83, 2.80], Wald [1.80, 2.76]
6 The trinity W 3.81, S 3.20, Λ 3.29; Hauck–Donner peak 3.77; Board 96.9% / 93.3%
7 Neyman–Scott 0.502 vs 1.003; Board 0%
8 EM p 0.90 → 0.82 → 0.73 → 0.64; 1,622 iterations; rate 0.9936; SE(p̂) 0.150
9 When likelihood misbehaves +221 per decade; swapped p = 0.567; constrained EM bootstrap 95th 7.79 vs 53.21
10 Misspecification tail 0.07% vs 0.32%; SE 0.0333 / 0.0531 / 0.0497; Board 76.9% / 93.3%
11 Quasi-, composite and pseudo-likelihood φ̂ = 2.22; 10⁶⁹³ states; β̂ 0.299 ± 0.013
12 The likelihood principle p = 0.073 vs 0.033; P(θ > ½) = 0.954
13 Information geometry, a glimpse geodesic 5.6 vs 10.0
14 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Weldon's crabs (1893); Pearson's nonic (1894).
  2. Upgrade card (Part 9). Consistency and asymptotic normality, now proved in the regular case.
  3. Consistency (Wald 1949). KL ≥ 0; the argmax of a random curve.
  4. Asymptotic normality. Expand the score; CLT plus LLN; √n(θ̂ − θ) → N(0, I⁻¹).
  5. Observed vs expected information (Efron & Hinkley 1978).
  6. Many parameters. The information matrix; profile likelihood along the ridge (LikelihoodLandscape).
  7. The trinity. Wald, score and LR on one curve; Hauck–Donner (Board).
  8. Neyman–Scott (1948). Incidental parameters: σ̂² → σ²/2.
  9. EM (Dempster, Laird & Rubin 1977). Jensen's lower bound; monotonicity proved; Louis (1982) SEs; the crabs refit.
  10. When likelihood misbehaves. Unbounded mixture likelihoods; boundary parameters; label switching.
  11. Misspecification (Huber 1967; White 1982). The KL projection; the sandwich, derived (Board).
  12. Quasi-, composite and pseudo-likelihood (Besag 1975).
  13. The likelihood principle (Birnbaum 1962). Binomial vs negative-binomial stopping.
  14. Information geometry, a glimpse. The Fisher metric; the natural gradient.
  15. Outro.

Built: statkit.mle. Data: Weldon/Pearson.

Build the film

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

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

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