The Comprehensive Exam
A client writes with two questions and a deadline: can you do the master's?
The World's ministry of health writes with two questions and six weeks. The first is a trial to design: would community health workers lower blood pressure by 4 mm Hg? Households in a town contaminate one another, so towns are randomized, the pilot gives an intraclass correlation of 0.034, and a design effect of 3.70 turns 267 adults per arm into 21 towns per arm; simulation shows the individual-level analysis rejecting a true null 30% of the time. The second is a survey to analyse: users of a salt substitute have pressure 6.7 mm Hg higher, because the people told their pressure was high are the ones who bought it. A causal graph picks the adjustment set and rules out the mediator and the collider, multiple imputation fills the withheld incomes, AIPW gives minus 2.22, and a robustness value says how strong a hidden confounder would have to be. Then the comprehensive exam: twelve problems from Stage III, each posed, paused and solved, from a Poisson sandwich to a Kaplan-Meier curve. The MSc goes on the Transcript.
What you need. All of Stage III (Parts 21-41); the two cases draw on Parts 13, 35, 36 and 41.
- Hook
- the consulting client
- Mathematics
- worked comprehensive-exam problems; two consulting cases from design to report
- Built
- the MSc problem bank
What you will be able to do
Bachelor's
- Explain why a trial of a community programme randomizes towns rather than households.
- State an estimand in words before choosing a design.
Master's
- Estimate an intraclass correlation from a one-way ANOVA and size a cluster-randomized trial with its design effect.
- Choose an adjustment set from a causal graph, impute a missing confounder and estimate an effect by AIPW with Rubin's rules.
- Solve the twelve exam problems, from a sandwich standard error to a Greenwood interval, without notes.
PhD
- Derive REML's variance estimate from the likelihood of error contrasts, and explain why AIC is not consistent for a nested true model while BIC is.
Practice
- Test an analysis plan by simulation before the data arrive: its type I error and its power.
- Write a one-page report with the estimate, its interval, a robustness value with a benchmark, and what the design cannot support.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 12 min · Master's 61 min · PhD 61 min · Practice 26 min.
- 0A letter from the ministryBachelor's3 min
- 1Case 1: what to randomizeBachelor's5 min
- 2Case 1: how many townsPractice5 min
- 3Case 1: the analysis planPractice5 min
- 4Case 2: the survey and its graphMaster's4 min
- 5Case 2: imputation and AIPWMaster's5 min
- 6Case 2: sensitivity and the reportPractice4 min
- 7Exam I: likelihoodMaster's6 min
- 8Exam II: Bayes and model choiceMaster's7 min
- 9Exam III: smoothing, robustness, sparsityMaster's6 min
- 10Exam IV: discoveries, guarantees, survivalMaster's7 min
- The MSc, and the road aheadAll tracks4 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. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
A letter from the ministryBachelor's3 min
This part closes the master's degree, and like the last part of the bachelor's, it introduces no new method. It begins with a letter. The World's ministry of health has two decisions to make before its budget closes, in six weeks. Both are about blood pressure, the island's largest cause of early death. They have some data, not as clean as they would like, and they want help. A statistician's working life is made of letters like this one, and the master's is the degree that says you can answer them.
The first question is about the future. The ministry wants to send community health workers into its towns, to visit households, check pressures and give advice. Before paying for all two hundred towns, it will test the idea. How should the test be done, and how many towns does it need? There is a pilot survey: thirty adults measured in each town. The second question is about the past. A salt substitute, with some of the sodium replaced by potassium, went on sale a year ago. A survey of three thousand adults finds that the people who use it have pressures six point seven millimetres higher than those who don't. The newspapers want it withdrawn. Should it be?
Consulting is as old as the profession. In 1919, Ronald Fisher was hired for six months by the Rothamsted Experimental Station, to see what could be learned from sixty-six years of records of its wheat field. He stayed fourteen years, and in answering the station's questions he invented much of the design of experiments. He also left the consultant's motto. To consult the statistician after an experiment is finished is often merely to ask him to conduct a post mortem examination. He can perhaps say what the experiment died of. Our two questions are the two sides of that remark: one arrives before the study, and one after.
After the two consulting cases comes the comprehensive exam itself. Each problem is posed on a card like this one, with the parts of the course it draws on. The clock is your time to try it: pause the video, work it out on paper, then watch the solution. The first case is a trial to design, and draws on Parts thirteen, twenty-five and thirty-five. The second is a survey to analyse, and draws on Parts thirty-six and forty-one. Then come twelve problems, one from each corner of the master's, and every number on screen is recomputed by our own code, with full solutions in the README.
Numbers: two questions, six weeks
1Case 1: what to randomizeBachelor's5 min
The first case: a trial to design. What should be randomized? First, the question has to become an estimand. Write Y i j of z for the pressure of adult i in town j a year from now, with the programme, z equal to one, or without it. The ministry would roll the programme out town by town, so the natural target is the town-average effect: over the island's towns, the change in a town's mean pressure. One could instead weight towns by population, which asks about the average person; with towns as unequal as the World's, the two can differ, and the protocol must say which. And the ministry's economists supply the most important number in any sample size calculation: the smallest effect worth detecting. A fall of four millimetres would pay for the health workers in strokes avoided. That is the planning threshold for this illustrative cost model, not a universal cutoff for useful effects.
Next, what to randomize. The cheapest-looking design randomizes households within each town: half get visits, half don't, and every town contributes both. But health workers talk to neighbours, neighbours talk to each other, and a town's shops and clinics change for everyone. Under this beneficial spillover story, controls also receive some benefit and the direct contrast is diluted. Interference need not always bias a contrast towards zero. In the language of Part thirty-five, the no-interference assumption fails inside a town. So we randomize whole towns to estimate the effect of this delivery policy, assuming negligible spillovers between towns: some with the programme and some without. That choice costs precision, as we will see, but it buys an answer to the question actually asked.
Randomizing towns is an old idea in heart disease prevention. In 1978 Jerome Cornfield, who had helped build the case that smoking causes lung cancer, wrote a short paper on randomizing by group, prompted by the community trials of the time. Its last sentence is the most quoted in the field. Randomization by group accompanied by an analysis appropriate to randomization by individual is an exercise in self-deception, however, and should be discouraged. We will measure exactly how much self-deception.
How much do towns differ? The ministry's pilot measured thirty adults in each of the two hundred towns. Here are the two hundred town means. Within a town, pressures vary with a standard deviation of about millimetres. If towns did not differ at all, the mean of thirty would vary with standard deviation sixteen over root thirty, about three: the grey curve. The real town means are more spread out, with standard deviation . The extra spread is the towns' own differences: water, diet, the clinic down the road.
The one-way analysis of variance of Part twenty-five turns that spread into a number. The mean square between towns, thirty times the variance of the town means, is ; the mean square within is . The between mean square estimates the within variance plus m times the between variance, so the between-town variance is their difference over thirty: . The intraclass correlation is the towns' share of the total variance: . Two adults from the same town are correlated about three hundredths. Resampling whole towns gives a ninety percent interval from to . A small number, and a poorly known one.
Which value should the plan use? The pilot says , but its interval reaches . A design should survive the bad end of what we don't know, because an underpowered trial wastes everything spent on it. And a year passes between the pilot and the trial, during which towns change in their own ways, which adds variance between towns. So we plan with an intraclass correlation of , a total standard deviation of sixteen and a half, and the ministry's four millimetres. Only the World knows the truth, and it rewards the caution: in the pilot year, and in the year of the trial, almost exactly the planning value. The pilot's estimate alone would have left the trial short of towns.
Numbers: pilot ICC 0.034 [0.020, 0.048]; truth 0.046, then 0.054
2Case 1: how many townsPractice5 min
Start as if adults were independent, as in Part thirteen. With n adults per arm, the difference in means is normal around the true effect, with variance two sigma squared over n. We want an eighty percent chance of a significant result at the five percent level when the effect is the ministry's four millimetres. The usual planning approximation keeps the rejection tail in the direction of the effect; the opposite tail is negligible here. For a reduction in pressure the relevant tail is negative, with delta denoting its magnitude. Setting it to eighty percent and solving gives the familiar formula: two times one point nine six plus point eight four, squared, times sigma squared, over delta squared. With sigma sixteen and a half, that is adults per arm. If only adults were what we randomized.
Now the towns. A town's mean pressure is the overall mean, plus the effect if the town is treated, plus the town's own deviation b j, with variance rho sigma squared, plus the average of its adults' deviations. Its variance is rho sigma squared plus one minus rho, sigma squared over m: sigma squared over m, times one plus m minus one times rho. The factor in brackets is Kish's design effect from Part eighteen. With fifty adults per town and rho of , it is . Fifty correlated adults carry the information of about thirteen and a half independent ones. A small correlation, multiplied by a large town, is a large cost.
So inflate the independent answer by the design effect: times is about adults per arm. At fifty adults a town, that is towns, so . With so few units, the analysis will use a t distribution with two k minus two degrees of freedom rather than a normal, and Richard Hayes and Lawrence Moulton's rule of thumb adds one town per arm to pay for it. The plan: towns in each arm, of the island's two hundred, and adults measured at the end.
Could we buy fewer towns by measuring more adults in each? Here is the number of towns needed per arm against the number of adults per town, on a log scale. More adults help at first, then hardly at all. The curve can never fall below this floor: even with infinitely many adults, each town's mean still carries its own deviation, and towns per arm is the limiting normal-approximation count for this unadjusted equal-size design. Baseline adjustment or a different target can change it. In the table, ten adults per town needs eighty-two towns; fifty needs forty-two; five hundred still needs thirty-four, and seventeen thousand measurements. In a cluster trial, adults are cheap, and towns are the sample size.
The answer is only as good as rho. Here is the number of towns per arm against the intraclass correlation, with the pilot's interval shaded. Plan with the pilot's estimate and you would recruit towns per arm. Plan with our more cautious value and you recruit twenty, before the extra one for the t. Every hundredth of correlation costs about two and a half towns per arm before rounding: the unrounded design effect is linear in rho. An exam answer that reports one sample size, without this line, is half an answer.
Finally, the power curve itself, computed honestly: cluster means, and a noncentral t with two k minus two degrees of freedom. At twenty-one towns per arm, the power is , as planned. In red, the power one would claim by treating every adult as independent. At eight towns per arm, that calculation promises percent power; the power under this Gaussian cluster model is percent. This is the self-deception Cornfield warned of, and it happens at the planning stage, before a single adult is measured.
Numbers: 267 per arm × DE 3.70 → 21 towns per arm, 42 in all
3Case 1: the analysis planPractice5 min
The analysis plan, written before any data exist. The protocol has six lines. First, draw the forty-two towns at random from the two hundred, to support inference about the island's town-average effect, provided recruitment and follow-up preserve that sampling design. Second, randomize twenty-one of them to the programme and twenty-one to control, by computer, after the towns have agreed to take part, so that no town can choose its arm. Third, after a year, measure fifty adults drawn at random from each town's register, by examiners who do not know the town's arm. Fourth, the primary analysis: regress the town means on arm and on the pilot's town mean, with a t on thirty-nine degrees of freedom. Fifth, secondary analyses: a mixed model on the adults, and the person-weighted effect. And sixth, register all of this before randomization, and report the intraclass correlation whatever the result, so the next planner has a better number than ours.
Why adjust for the pilot? The primary model regresses each town's mean on its arm and on its own pilot mean, centred. The pilot mean carries the town's lasting deviation, the b j that made the design effect so expensive. How much of it? The pilot's town mean is a noisy reading of b j with reliability about a half, by the pilot's own estimates: the between-town variance over itself plus the within variance over thirty. Under our specified Gaussian town model this ANCOVA has unbiased coefficients and valid t inference. Randomization alone does not make arbitrary regression adjustment exactly unbiased in finite samples, and covariates need not always improve precision. Because it is named in the protocol, there is no fishing.
A plan should be tested before it is used, and the World lets us test it: four thousand trials drawn from the towns' law, each analysed three ways. Faint bars are trials with no effect at all; solid bars, trials with the four millimetre effect. Analysing adults as if independent declares a significant effect in percent of trials where there is none: six times the promised five. Both cluster-level analyses hold their five percent. And the adjustment pays: power rises from percent to , because the standard deviation of the estimate falls from to . With the pilot in the model, a smaller trial might have achieved the target power under this simulated law; a separate size calculation is needed before choosing that smaller count. We keep forty-two: the pilot's ICC was uncertain, and so is its covariate's strength.
Now the ministry runs the trial, in the World. Here are its two hundred towns. Forty-two are drawn at random. A computer assigns twenty-one to the programme and twenty-one to control. A year later, fifty adults in each town have their pressure measured.
Here is the result. Each dot is a town: its pilot mean across, its mean a year later up. Programme towns in green, controls in blue. The pre-specified analysis fits two parallel lines; the gap between them is the effect, millimetres, with a ninety-five percent interval from to . The unadjusted cluster t finds , with an interval that crosses zero: the same data, less precisely used. The individual-level analysis reports the same estimate as the cluster t with an interval less than half as wide, a precision the design never had. The World's true effect is minus four. This particular trial estimated a smaller reduction than the truth; only the honest analyses say how short it might be.
The report follows the CONSORT statement's extension for cluster trials, which asks for the flow of towns and adults through every stage, the intraclass correlation, and an analysis that accounts for clustering. It should also say what the trial did not learn: one year, one island, and blood pressure rather than the strokes the ministry actually cares about. Trials like this are real. A major example, published in 2021, randomized six hundred Chinese villages, and its subject is the second case.
Numbers: type I error 30% vs 5.3%; power 82% → 95%; trial −3.13 [−5.99, −0.27]
4Case 2: the survey and its graphMaster's4 min
The second case: an observational survey, and the graph that has to come before any estimate.
The ministry's survey reached adults a year after the substitute went on sale; of them use it. Their mean pressure is , against for everyone else. A difference of millimetres, with a ninety percent interval from to : far from zero, and in the wrong direction. The headline writes itself. Our job is to ask what the difference means.
Who are the users? Compare them with everyone else. They are older, by about years; heavier; slightly richer; and percent of them had been told by a doctor that their pressure was high, against percent of non-users. The standardized differences in the last column are large on several measured covariates. A standardized difference of a tenth is a descriptive convention, not a test of exchangeability. This is confounding by indication: the substitute was taken up by exactly the people whose pressure was already high, often on their doctor's advice. The raw comparison mixes the substitute's effect with the reason for using it.
Before any estimate, a graph, written from what is known about blood pressure rather than read off the data. Age and sex, BMI and income each affect both whether someone switches and their pressure. Age and BMI also make a diagnosis of high pressure likelier, and the diagnosis affects both switching and pressure, through medicines and advice. The substitute works through potassium: users excrete thirty millimoles a day more, and potassium lowers pressure. And the survey also recorded whether each person visited a clinic this year, which both switching and high pressure make likelier.
The back-door criterion of Part thirty-six finds the adjustment set. Every path that enters the substitute through an arrowhead is a back door. Switching, back to diagnosis, forward to pressure. Switching, back to age, through diagnosis, to pressure; switching, back to income, to pressure; and so on. Conditioning on age and sex, BMI, income and diagnosis blocks every one, and none of those is a descendant of switching, so the set satisfies the criterion: the effect is identified, if the graph is right.
The graph also says what not to adjust for, and the survey offers two tempting variables. Potassium lies on the causal path: adjusting for it compares users and non-users with the same potassium, which asks what the substitute does apart from its mechanism. The answer, nothing, is not the question. The clinic visit is a collider: both switching and high pressure cause it. Conditioning on it opens a path that was closed. Among people who visited a clinic, users had a reason to be there that non-users lacked, so the non-users who visited were the ones with high pressure, and the comparison is distorted. An exam answer that adjusts for everything in the data set fails here twice.
Here are the four answers, each with a ninety percent interval. Adjusting for nothing, plus . Adjusting for the back-door set, minus : the sign has flipped. Adding potassium, the mediator, the effect disappears: . Adding the clinic visit, the collider, it is exaggerated to minus . Three analyses of the same survey, three different stories, and the graph states the causal assumptions needed to interpret them. A graph and a fitted regression cannot verify those assumptions. Income, meanwhile, is missing for more than a third of the sample; these regressions used imputed values, which is the next chapter.
Numbers: +6.7 raw; −2.33 adjusted; +0.09 with the mediator; −4.18 with the collider
5Case 2: imputation and AIPWMaster's5 min
The estimate: imputation for the holes, then a doubly robust estimator. Income, one of the four confounders, was withheld by percent of the people surveyed. Here are the first twenty-eight rows. The young withhold it far more often: percent of those under forty, percent of those over sixty. Users, perhaps more engaged with the survey's subject, withhold it half as often as non-users. And those with higher pressure answer more often too. Every one of these drivers is in the data. If, given them, withholding has nothing more to do with income itself, the holes are missing at random, Part forty-one's assumption, and they can be filled honestly.
The easy fix is to drop everyone with a hole. But here whether income is seen depends on pressure, the outcome, and Part forty-one showed what that does: a complete-case analysis selects on the outcome, and its estimates are biased. In this one survey, the complete-case estimate happens to be ; whether that is luck or method, one survey cannot say. The Board will.
So impute. The imputation model predicts log income from everything else, including the treatment and the outcome, and their product, to retain associations relevant to the analysis. This product does not by itself establish congeniality with AIPW; the normal imputation model remains a working assumption. Leaving the outcome out would pull every imputed income's association with pressure towards zero. Each imputation is proper: draw the regression's parameters from their posterior, then each missing value. Forty completed data sets, each analysed by the estimator we are about to build. Rubin's rules combine them. The fraction of missing information is : although more than a third of incomes are missing, they cost only about an eighth of the information about the effect, because income is only one confounder and the others predict it.
In each completed data set, fit a logistic model for switching given the four confounders. Here are the fitted propensities from one of them: users above the line, non-users below. Users sit further right, as they should, but the two distributions show observed overlap across much of the range, from to . These fitted probabilities diagnose practical overlap in this completed sample; they do not prove population positivity. We clip fitted propensities to point zero one and point nine nine, which bounds weights but can add bias.
The check of Part thirty-six: standardized differences before weighting, in red. Age differs by standard deviations, diagnosis by . Weight each user by one over their propensity and each non-user by one over its complement, and recompute. Every difference falls inside the shaded band; the largest is . The weighted users and non-users look alike on the displayed covariate means. This does not establish balance of every distribution or remove hidden confounding.
The estimator is the augmented inverse probability weighted estimator of Part thirty-six. For each person, the outcome models' predicted difference, corrected by each arm's weighted residual. The estimate is the average, and its standard error comes from the spread of the individual terms, the influence function. It is consistent if either the outcome regressions or the propensity model is right, under the causal identification and overlap assumptions. Before missingness, the uptake law is logistic in these covariates; estimated and clipped propensities after working-model imputation need not equal that true law. Consistency does not alone guarantee this influence-function standard error under arbitrary misspecification. Pooled over the forty imputations: millimetres, standard error , ninety percent interval from to . Under the stated causal and missing-data assumptions, the estimated reduction is about two millimetres. Rubin pooling here is a working inference procedure whose calibration is examined on the Board, not an automatic doubly robust missing-data guarantee.
Numbers: 37% missing, FMI 0.13; AIPW −2.22 [−3.42, −1.01]
6Case 2: sensitivity and the reportPractice4 min
How wrong could we be, and what do we tell the minister? The estimate rests on one assumption the data cannot check: that the graph has every common cause of switching and pressure. Part thirty-six's robustness value asks how strong a missing one would have to be. Start from one seeded completed dataset and its adjusted regression, using classical OLS standard errors for the partial-variance identities. This is a sensitivity illustration for that OLS coefficient, not pooled MI-AIPW inference: , with a t statistic of on almost three thousand degrees of freedom. Divide the t by the root of the degrees of freedom. Carlos Cinelli and Chad Hazlett's robustness value is then : a hidden confounder explaining percent of the residual variance of both switching and pressure would erase the effect. One explaining percent of each would make it no longer significant at five percent.
Draw it. Across, how much of switching a hidden confounder explains; up, how much of pressure. In the red region, the adjusted effect would be zero or positive. The robustness value is where the boundary crosses the diagonal. Is that a lot? Compare a confounder we did measure, the strongest: having been told one's pressure is high. It explains percent of switching and percent of pressure. A hidden factor twice as strong as a doctor's diagnosis would not erase the effect. Three times as strong would. Whether such a factor exists is a question for physicians and sociologists, not for the data; the analysis can only say how strong it would have to be.
Observational evidence is strongest when it agrees with experiments, and here there is a real one. Bruce Neal and colleagues' Salt Substitute and Stroke Study, published in 2021, randomized six hundred villages in rural China, with about twenty-one thousand adults at high risk, to a salt substitute of three quarters sodium chloride and one quarter potassium chloride, or to ordinary salt, for about five years. Pressure fell by about three point three millimetres in the substitute villages, and strokes by fourteen percent, with fewer deaths. It is a cluster-randomized trial, Case one's design, and it supports the same direction of effect in its own high-risk rural Chinese population. Transporting its magnitude to the island requires further assumptions.
And then the page the minister will actually read. It leads with the finding, in the minister's units: among comparable adults, using the substitute lowered pressure by about millimetres, with an interval from to . It explains, in one sentence, why the newspapers saw the opposite. It states the assumptions in plain words, and a separate OLS sensitivity illustration. It does not quantify sensitivity to the missing-at-random assumption or directly bound the pooled AIPW effect. It says what independent evidence agrees. And it ends with advice the data support: keep the substitute on sale, promote it, and recommend clinical review for kidney disease or potassium-raising medicines because extra potassium can cause hyperkalaemia. No p-values, no Greek; every number in it traceable to the analysis.
The World can tell us what no real consultant ever learns. The substitute lowers everyone's pressure by exactly three millimetres. Our estimate, , has an interval that covers it. Had every income been known, the same estimator would have given ; the remaining gap can reflect sampling variation and fitted-model approximation, which the interval was built to allow for. The headline's comparison had the wrong sign, and a narrow interval around it.
Numbers: RV 0.074; benchmark (0.040, 0.033); the trial's −3.3
7Exam I: likelihoodMaster's6 min
The exam begins, with three problems on likelihood. Problem one. Twelve adults report how many times they visited a doctor last year: four zeros, a one, two twos, a four, five, six, nine and eleven. Model the counts as independent Poisson with mean lambda. Find the maximum likelihood estimate, its standard error from the Fisher information, and the sandwich standard error. Which would you report, and why? Pause the video and try it.
The log-likelihood is the sum of y times log lambda, minus n lambda, and the score sets its derivative to zero. So the estimate is the sample mean, forty over twelve, ; the information is n over lambda. The model-based standard error is the root of lambda hat over n: . The sandwich of Part twenty-two replaces the model's variance of the score with its empirical variance: A inverse B A inverse, which here reduces to the root of the sum of squared deviations, over n. It is , almost twice as large.
Which to report? A Poisson's variance equals its mean, but these twelve counts have mean and variance . They are overdispersed, so the model-based standard error, which trusts the Poisson's variance, is too small by about half. For a mean, the sandwich needs independent sampling and finite variance for its asymptotic calibration. With only twelve observations it can still be inaccurate. Report it with that limitation, or fit a negative binomial as in Part twenty-four. In the World's whole adult population, the variance of visits is times the mean, so this was no fluke of twelve people.
Problem two. In 1935 Chester Bliss exposed batches of flour beetles to eight doses of carbon disulphide and counted how many were killed. Fit a logistic regression of the kill rate on the log dose by iteratively reweighted least squares. Starting from beta equal to zero, give the weights, the working response, and the first step. Pause and try it.
At beta equal to zero, every fitted probability is a half, so each dose's weight is its number of beetles times a half times a half: n i over four. The working response is the linear predictor, zero, plus the residual divided by the variance function: four times the observed kill rate minus a half. Then one weighted least squares fit: the two by two matrix X transpose W X, and the vector X transpose W z. Solving gives the first step: an intercept of and a slope of . Newton's method for the logistic likelihood is exactly this, repeated.
Here are Bliss's eight doses and their kill rates, with the curve after each step. The first step already has the right shape; the log-likelihood jumps from to . By the fourth step the estimates agree to two decimals, and by the sixth to eight: an intercept of and a slope of . Newton's quadratic convergence, as Part twenty-one promised. The dose that kills half, minus the intercept over the slope, is on the log scale: about milligrams per litre.
Problem three. In the linear model with normal errors of variance sigma squared and a design of full rank p, show that maximum likelihood estimates sigma squared by the residual sum of squares over n, and restricted maximum likelihood by the residual sum of squares over n minus p. Then compute both for Longley's sixteen years of employment data, with seven coefficients. Pause and try it.
Maximize over beta first: at the least squares fit, the log-likelihood is minus n over two log sigma squared, minus the residual sum of squares over two sigma squared, maximized at RSS over n. Its expectation is n minus p over n times sigma squared, too small, because the fitted beta has used up p of the n dimensions. REML uses only the n minus p error contrasts: project y onto an orthonormal basis K of the space orthogonal to X's columns. These contrasts do not involve beta at all, are normal with variance sigma squared, and their squared length is the residual sum of squares. Their likelihood has n minus p in place of n, and its maximum is RSS over n minus p, unbiased.
For Longley's data the residual sum of squares is about thousand. The ordinary likelihood peaks at that over sixteen, thousand; the restricted likelihood at that over nine, thousand. With seven coefficients and only sixteen years, maximum likelihood is forty-four percent too low. Simulating twenty thousand data sets from Longley's own design, with sigma squared at the REML value, the ML estimates average nine sixteenths of the truth and the REML estimates average the truth. In mixed models REML also removes fixed-effect dimensions, but it does not generally make every variance-component estimator exactly unbiased.
Numbers: SEs 0.527 vs 1.036; β = (−60.72, 34.27); σ² 52,277 vs 92,936
8Exam II: Bayes and model choiceMaster's7 min
Three problems on Bayesian models, their computation, and choosing between models. Problem four. Rubin's eight schools: the estimated effects of coaching on a test in eight schools, each with its standard error. Model each estimate as normal around the school's true effect theta j, the true effects as normal around mu with spread tau, and put flat priors on mu and tau. Find the marginal posterior of tau up to a constant, and the posterior mean of school A's effect, whose estimate was twenty-eight points. Pause and try it.
Integrate out each school's true effect: given mu and tau, each estimate is normal around mu with variance sigma j squared plus tau squared. Integrate out mu under its flat prior, completing the square, and the marginal posterior of tau is the root of V mu, times the product of the normal densities evaluated at mu hat. Here mu hat of tau is the precision-weighted mean of the estimates and V mu its variance. Given tau, each school's effect is shrunk from its own estimate towards mu hat by the factor B j, its sampling variance over its total variance. Integrating over the full positive half-line for tau gives the answer; the density plot displays only zero to thirty.
The full posterior of tau piles up near zero but has a long tail: its median is , and ninety percent of it lies below . There is substantial density near zero, although the continuous prior assigns zero probability to an exactly common effect. Averaging the shrinkage over that posterior, school A's twenty-eight becomes . Shrinkage is towards a tau-dependent precision-weighted mean, not one fixed pooled target. For comparison, complete pooling gives , the noisier ones further, and the order is almost unchanged. It is the compromise of Parts twenty-five and twenty-six, between treating the schools as unrelated and treating them as identical, with the data choosing where to stand.
Problem five. Four random-walk Metropolis chains target an equal mixture of two normals, centred at minus three and plus three. They start at minus six, minus two, two and six, with proposals of standard deviation point four. After two thousand iterations, discarding the first half, R hat is , the bulk effective sample size is , and percent of proposals were accepted. What do these numbers say, what went wrong, and what would you change? Pause and try it.
R hat compares the variance between chains with the variance within them; when the chains have all forgotten their starts and explore the same distribution, it is one. At one point four five, far above the modern threshold of one point oh one, the chains are describing different distributions. An effective sample size of eight says the four thousand retained draws carry the information of eight independent ones. And an acceptance rate near ninety percent is the clue: the steps are so small that almost every one is accepted, and mode crossing becomes very slow. A high acceptance rate alone does not diagnose all samplers.
The traces show it. On the left, two chains live near minus three and two near plus three, and crossings are rare or absent in the displayed run. On the right, the same chains with proposals ten times wider: about percent are accepted, every chain visits both modes many times, R hat is and the effective sample size . One caution belongs in every answer: R hat can only compare what the chains found. Had all four started near plus three, the slow sampler could report an apparently satisfactory R hat while missing half the distribution. Overdispersed starts, as here, are what exposed it.
Problem six. Polynomials of degree one to five are fitted to New York's daily ozone against temperature, on days. Each has k parameters, counting the variance, and a maximized log-likelihood, in the table. Which degree does AIC choose, and which does BIC? And if the truth were a quadratic, how often would each criterion choose it as the sample grows? Pause and try it.
AIC is minus twice the log-likelihood plus two per parameter; BIC charges log n per parameter, here . AIC is smallest at degree : the cubic and quartic terms together lower minus twice the log-likelihood by , more than the four they cost. BIC is smallest at degree : at nearly five per parameter, only the quadratic term pays its way. The criteria disagree, and both are doing what they were built to do.
The second half is theory, checked by simulation: a true quadratic, candidates of degree one to six, six hundred data sets at each sample size. AIC's chance of choosing the truth rises and then levels off near , because a needless term is added whenever its likelihood-ratio statistic, chi-squared on one degree of freedom, exceeds two, whose asymptotic null tail probability is percent under the regular one-extra-term null approximation. This is not an exact probability at every finite sample size or the overall selection probability among six candidates. BIC's penalty grows with log n, so that chance goes to zero, and BIC finds the truth with probability tending to one. BIC is consistent in this fixed, regular candidate set containing the truth. AIC targets predictive risk under its asymptotic conditions; it does not universally predict better than BIC. Name the goal before naming the criterion.
Numbers: A: 28 → 11.4; R̂ 1.45 → 1.01; AIC 4 vs BIC 2
9Exam III: smoothing, robustness, sparsityMaster's6 min
Three problems from the middle of the master's: smoothing, robustness and sparsity. Problem seven. Old Faithful's waiting times between eruptions have a standard deviation of minutes and an interquartile range of twenty-four. Compute Silverman's rule-of-thumb bandwidth for a Gaussian kernel density estimate. Least-squares cross-validation chooses . Which would you use, and why do the two differ? Pause and try it.
Silverman's rule is nought point nine times the smaller of the standard deviation and the interquartile range over one point three four nine, times n to the minus a fifth. The interquartile range over one point three four nine is , so the standard deviation is the smaller. The rule gives minutes. Cross-validation instead minimizes an estimate whose expectation is expected integrated squared error minus the fixed integral of the true density squared, computed by leaving each point out, and it picks : a third less smoothing.
On the histogram, the rule's estimate in teal and cross-validation's in gold. Both find two modes, near fifty-five and eighty minutes, and cross-validation's are sharper. Triple the bandwidth and the shape is wrong. They differ because the point nine rule is a robust rule of thumb; the Gaussian normal-reference AMISE constant is about one point zero six. For these two well-separated modes, and a density with two well-separated modes has far more curvature than a normal with the same spread, so it needs less smoothing. Use cross-validation, or the Sheather–Jones plug-in of Part twenty-nine, and when the choice matters, show the reader both.
Problem eight. Derive the influence function of the variance, written as a functional: the integral of x minus the mean, squared, against the distribution F. Simon Newcomb's sixty-six timings of light from 1882 include one value of minus forty-four. What does the influence function say about it? And compare the mean, the median and Huber's M-estimate of the centre. Pause and try it.
Contaminate F with a little mass epsilon at the point x; the mean moves by epsilon times x minus mu. The variance of the mixture is one minus epsilon times the spread of F around the moved mean, plus epsilon times the new point's squared distance. Differentiate at epsilon equal to zero. The first term gives minus sigma squared; the cross term is zero, because deviations from the mean integrate to zero; the last gives x minus mu squared. So the influence function is x minus mu squared, minus sigma squared: unbounded, and growing like the square of the distance. One wild point can move the variance as far as it likes.
At Newcomb's minus forty-four, the variance's influence function is about . Divided by sixty-six, its first-order influence predicts roughly seventy-three variance units. The exact deletion effect differs because the mean and denominator also change: with it, without. For the centre, here are the sensitivity curves: the effect of adding one more timing anywhere. The mean's is a straight line, unbounded, the median's a bounded step, and Huber's estimate is bounded and piecewise smooth. Its efficiency depends on the tuning, scale and population model. The mean is , Huber's estimate . The modern value of the speed of light corresponds to thirty-three: the bias in Newcomb's data was systematic, and robustness to extreme points alone cannot identify or correct a shared systematic offset.
Problem nine. The lasso, with the squared error scaled by one over two n, is fitted to Stamey's prostate cancer data: men in the training set, eight standardized predictors, and lambda equal to point one. A colleague reports the coefficients on the card. State the Karush–Kuhn–Tucker conditions, check them, and say whether this is the lasso solution. Pause and try it.
Let g j be each predictor's inner product with the residual, over n. At the lasso solution, every predictor in the model has g j equal to lambda times the sign of its coefficient: the subgradient of the absolute value. Every predictor out of the model has g j between minus lambda and lambda. For the colleague's answer, log cancer volume has g of , not point one, and the worst violation among the nonzero coefficients is . It is not the solution. It is the least squares fit soft-thresholded once, which would be right only if the predictors were uncorrelated, and here two of them correlate at .
In red, the colleague's g values against the line at lambda: some nonzero coefficients sit above it, some below, and none exactly on it. In green, coordinate descent's answer. Every predictor in its model satisfies the signed KKT equality to numerical tolerance: . Every predictor left out sits below it, the largest at . Because the lasso is convex, these conditions are not just necessary but sufficient: passing their signed conditions to solver tolerance certifies numerical optimality to that tolerance. A KKT check is the cheapest proof in statistics, and an examiner's favourite.
Numbers: h 3.99 vs 2.65; IF 4,816; KKT 0.182 off
10Exam IV: discoveries, guarantees, survivalMaster's7 min
The last three problems: many tests at once, a prediction interval with a guarantee, and a survival curve.
Problem ten. Twelve hypotheses give the p-values on the card, already sorted. Apply the Benjamini–Hochberg procedure at a false discovery rate of ten percent. How many discoveries are there, and how many would Bonferroni allow at the same level? And what exactly does the procedure promise? Pause and try it.
Compare the i-th smallest p-value with i over twelve times point one, i over a hundred and twenty, and find the largest i where it falls below. The eighth, , is below eight over a hundred and twenty, about point oh six seven; the ninth, , is above its line, and so are all the rest. So BH rejects the eight smallest, here all eight are also below their own lines. In other examples the step-up rule can include earlier p-values that exceed their individual lines: the procedure steps up from the last crossing. Bonferroni's threshold, point one over twelve, allows only . The promise is about an average: over repeated use, the expected share of false discoveries among the discoveries is at most ten percent, for valid null p-values under independence or the specific PRDS positive-dependence condition. Arbitrary positive correlations are not enough. It says nothing about which of the eight are false, and nothing about this particular list.
The picture is a sorted list of p-values against a line of slope q over m: everything up to the last point under the line is a discovery. The same rule on the prostate microarray of Part thirty-three, with genes: BH at ten percent finds genes, Bonferroni only . With thousands of tests, the difference between controlling the chance of any error and the rate of errors is the difference between a list worth following up and almost nothing.
Problem eleven. A model fitted on one part of the data leaves nine absolute residuals on a separate calibration set: the numbers on the card. Give the split-conformal eighty percent prediction interval for a new point whose prediction is ten, and prove that it covers at least eighty percent of the time. What does the guarantee assume, and what does it not give? Pause and try it.
With n equal to nine and alpha point two, take k as the ceiling of ten times point eight: . Sort the residuals; the th smallest is . The interval is ten plus or minus : from to . The proof: if the new point and the calibration points are exchangeable, conditional on the separate training sample, its rank is uniform when scores are distinct or ties are randomly broken; ties only make the usual nonrandomized bound conservative, so it is at or below the th with probability at least over ten. The guarantee assumes only exchangeability, not a correct model; but it is marginal, an average over new points, not a promise for each kind of point.
The same recipe on New York's ozone: a line in temperature fitted to thirty-seven days, residuals on others, and k equal to the ceiling of thirty-eight times point nine, . The band is the line plus or minus parts per billion; at eighty-five degrees, about plus or minus . On the thirty-seven held-out days it covered every one. But a constant width is a poor fit to ozone, whose spread grows with temperature: too wide on cool days and close to failing on hot ones, so its coverage is far from even across temperatures. Conformalized quantile regression lets width follow the spread. Both rank guarantees still require exchangeable calibration and future scores conditional on separate training. Seasonal and serial dependence in these air-quality days makes this an illustration, not a verified time-series guarantee.
Problem twelve. The six-MP arm of Freireich's 1963 leukaemia trial: twenty-one patients, with their weeks in remission, a plus marking those still in remission when last seen. Compute the Kaplan–Meier estimate up to week thirteen, its Greenwood standard error at week thirteen, and a log-log ninety-five percent interval. Pause and try it.
Only the times with a relapse change the curve. At week six, twenty-one are at risk and three relapse: the curve falls to eighteen over twenty-one, . The patient censored at six leaves the risk set without a step, so at week seven seventeen are at risk, and one relapses. At ten, fifteen at risk; at thirteen, twelve, after the censorings at nine, ten and eleven. The estimate at thirteen is . Greenwood's formula: the square of the estimate times the sum of d over n times n minus d, which gives a standard error of . The log-log interval transforms, builds a symmetric interval, and transforms back, so it stays inside zero and one: from to .
Here is the whole curve, with its pointwise band, and censored patients marked by ticks. Independent censoring is required; these are pointwise approximate intervals. Beside it, the placebo arm, in which every patient had an observed relapse, most within a few weeks. The median remission is weeks on six-MP against on placebo, and the ordinary unstratified log-rank statistic of Part forty is on one degree of freedom. This was an early randomized matched-pair leukaemia trial, and its curves are still the textbook example: the reason survival analysis needed Kaplan, Meier and Greenwood.
Numbers: BH 8 vs 4, genes 59 vs 7; 10 ± 4.4; Ŝ(13) = 0.690 ± 0.107
The MSc, and the road aheadAll tracks4 min
Part forty-two in twelve lines. Randomize the unit that receives the intervention, here towns. Estimate the intraclass correlation from a pilot by one-way analysis of variance, and plan with the cautious end of its interval. The design effect, one plus m minus one rho, makes towns the real sample size. Write the analysis down before randomizing, at the level of the cluster, adjusted for baseline. In observational data, confounding by indication can flip the sign of an effect. Draw the graph, and adjust for neither mediators nor colliders. Impute with the outcome in the model, then use a doubly robust estimator. Measure how strong a hidden confounder would have to be, compare it with the measured ones, and write one page. And the exam: the sandwich, IRLS, REML and partial pooling; R hat, effective sample sizes, AIC and BIC; bandwidths, influence functions and KKT checks; Benjamini–Hochberg, conformal intervals and Kaplan–Meier.
That completes the third stage, the master's. Optimization and likelihood, linear and generalized linear models, hierarchical and Bayesian models and their computation; choosing models, smoothing, robustness, many variables, sparsity, many tests and prediction with guarantees; experiments and causes, natural experiments, time series, space, survival, and the data we did not see. And an exam: two clients and twelve problems, every one solved. That completes this course's master's-level stage; it is not an accredited degree.
A promise for the next stage. Many standard errors in this exam leaned on asymptotics: the sandwich, the influence-function standard error of AIPW, and normal approximations behind several intervals. The Gaussian regression t intervals and split-conformal rank bound have different, explicit finite-sample justifications. We took on trust that the limits exist and that the approximations hold. The PhD core proves it, starting from the foundations: measure-theoretic probability, martingales, the theory of estimation and of testing, and asymptotic statistics.
Where it comes back. Part forty-three asks what a random variable really is and why the laws of large numbers hold. Part forty-seven proves the sandwich's asymptotics. Part forty-nine shows when the augmented estimator attains the efficiency bound, including correct nuisance limits and regularity conditions. Part fifty-five is the next exam, the qualifying exam of the PhD. And Part fifty-eight revisits trial design, with experiments that can be watched and stopped at any time.
Six more problems for the problem bank, with full solutions in the README alongside the twelve from the exam. The variance of a cluster trial; a collider's bias; the sandwich under a correct model; IRLS as Newton's method; the lasso with orthonormal columns; and the proof that Benjamini–Hochberg controls the false discovery rate. Pause here if you want to try them.
The books behind this part: Hayes and Moulton, and Donner and Klar, on cluster trials; Cox and Donnelly's principles of applied statistics, and Hernán and Robins on causal inference; Gelman and colleagues, and Wasserman, and Cox and Hinkley's book of problems, for the exam; and the CONSORT statement; with the papers from Bliss and Fisher to the salt substitute trial.
Forty-two parts of sixty-five, and the second milestone. The master's is complete. The PhD core begins with the oldest question we have postponed: what exactly is a random variable, and why do the limit theorems we have leaned on since Part six actually hold? Part forty-three: measure-theoretic probability.
Where it goes next. Stage IV begins: Part 43 rebuilds probability on measure theory, and the PhD core (Parts 43-55) proves what the exam's problems only used, ending in the qualifying exam of Part 55.
Key results
The part's results in one place, for revision.
Try it
Lab 42 · A cluster trial analysed two ways
Simulate 1,500 trials of 42 towns of 50 adults (town effects of sd 3.8 mm Hg, adults of sd 16, so an intraclass correlation of 0.054), randomize 21 towns to treatment, and compare the individual-level and the cluster-level analyses: their type I error with no effect, and the cluster analysis's power for a fall of 4 mm Hg, each against its formula.
python -m videos.stats.labs 42
needs numpy, scipy, matplotlib · download lab42.py ·
source on GitHubintraclass correlation 0.053 estimated on average (truth 0.054)
design effect 1 + (m - 1) rho 3.63
type I error, adults as independent 31.3% (formula 30.3%; nominal 5%)
type I error, town means 4.7% (nominal 5%)
power for -4 mm Hg, town means 81.8% (noncentral t 81.5%)
Adults in one town share its effect, so 2,100 adults carry the information of about 2,100 / DE: the individual-level analysis rejects a true null about six times too often, and the analysis of town means has the size and the power the plan promised.
The code (84 lines; it asserts its own result)
"""Lab 42: test Case 1's analysis plan by simulation: randomize towns, then analyse adults or towns."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
from explainer.stats.kit import causal, ols
TITLE = "A cluster trial analysed two ways"
GOAL = ("Simulate 1,500 trials of 42 towns of 50 adults (town effects of sd 3.8 mm Hg, adults of sd 16, so an "
"intraclass correlation of 0.054), randomize 21 towns to treatment, and compare the individual-level and "
"the cluster-level analyses: their type I error with no effect, and the cluster analysis's power for a fall "
"of 4 mm Hg, each against its formula.")
TASKS = [
"Use 8 towns per arm of 130 adults (about the same number of adults). What is the real power of the cluster analysis?",
"Set the town sd to 0 (no clustering). Do the two analyses now agree, and which has more power?",
"Add each town's pilot mean (its town effect plus noise of sd 16/sqrt(30)) as a covariate in a cluster-level regression and measure the gain in power.",
]
K, M, SD_TOWN, SD_ADULT, DELTA = 21, 50, float(np.hypot(3.5, 1.5)), 16.0, -4.0
def run(seed=0):
rng = np.random.default_rng(seed)
reps, towns = 1500, 2 * K
cluster = np.repeat(np.arange(towns), M)
rho = SD_TOWN ** 2 / (SD_TOWN ** 2 + SD_ADULT ** 2)
de = causal.design_effect(M, rho)
tcrit = stats.t.ppf(0.975, towns - 2)
z_naive, t_clu, t_clu_alt, icc_hat = (np.empty(reps) for _ in range(4))
for r in range(reps):
y = 130 + np.repeat(SD_TOWN * rng.standard_normal(towns), M) + SD_ADULT * rng.standard_normal(towns * M)
zc = np.zeros(towns, bool)
zc[rng.choice(towns, K, replace=False)] = True
null = causal.cluster_diff(y, zc, cluster)
alt = causal.cluster_diff(y + DELTA * zc[cluster], zc, cluster)
z_naive[r] = null["naive"]["est"] / null["naive"]["se"]
t_clu[r] = null["cluster"]["est"] / null["cluster"]["se"]
t_clu_alt[r] = alt["cluster"]["est"] / alt["cluster"]["se"]
icc_hat[r] = ols.icc(y, cluster)
size_naive, size_clu = np.mean(np.abs(z_naive) > 1.96), np.mean(np.abs(t_clu) > tcrit)
power = np.mean(np.abs(t_clu_alt) > tcrit)
size_theory = 2 * stats.norm.cdf(-1.96 / np.sqrt(de)) # the naive SE is too small by the factor sqrt(DE)
se_clu = np.sqrt(2 * (SD_TOWN ** 2 + SD_ADULT ** 2 / M) / K)
power_theory = stats.nct.sf(tcrit, towns - 2, abs(DELTA) / se_clu) + stats.nct.cdf(-tcrit, towns - 2, abs(DELTA) / se_clu)
lab = labs.Lab()
lab.row("intraclass correlation", f"{icc_hat.mean():.3f} estimated on average (truth {rho:.3f})")
lab.row("design effect 1 + (m - 1) rho", f"{de:.2f}")
lab.row("type I error, adults as independent", f"{size_naive:.1%} (formula {size_theory:.1%}; nominal 5%)")
lab.row("type I error, town means", f"{size_clu:.1%} (nominal 5%)")
lab.row("power for -4 mm Hg, town means", f"{power:.1%} (noncentral t {power_theory:.1%})")
lab.note = ("Adults in one town share its effect, so 2,100 adults carry the information of about 2,100 / DE: "
"the individual-level analysis rejects a true null about six times too often, and the analysis of "
"town means has the size and the power the plan promised.")
assert abs(icc_hat.mean() - rho) < 0.006, "the ANOVA estimator recovers the ICC"
assert abs(size_naive - size_theory) < 0.04 and size_naive > 0.2, "the naive size is 2 Phi(-1.96 / sqrt(DE))"
assert abs(size_clu - 0.05) < 0.02, "the cluster-level t test has size 5%"
assert abs(power - power_theory) < 0.04, "its power matches the noncentral t"
fig, ax = labs.figure(2, size=(11, 4.2))
bins = np.linspace(-6, 6, 61)
grid = np.linspace(-6, 6, 300)
ax[0].hist(z_naive, bins=bins, density=True, color=labs.RED, alpha=0.55, label="adults as independent")
ax[0].hist(t_clu, bins=bins, density=True, color=labs.GREEN, alpha=0.55, label="town means")
ax[0].plot(grid, stats.norm.pdf(grid), color=labs.INK, lw=1.2, label="standard normal")
for c in (-1.96, 1.96):
ax[0].axvline(c, color=labs.MUTED, ls="--", lw=1)
ax[0].set(title="Test statistics when the programme does nothing", xlabel="estimate / its standard error", ylabel="density")
ax[0].legend()
m = np.arange(5, 501)
base = 2 * (1.96 + 0.84) ** 2 * SD_ADULT ** 2 * (1 + (SD_TOWN / SD_ADULT) ** 2) / DELTA ** 2 # adults per arm if independent
need = base * (1 + (m - 1) * rho) / m
ax[1].plot(m, need, color=labs.GOLD, label="towns per arm for 80% power")
ax[1].axhline(base * rho, color=labs.MUTED, ls="--", lw=1, label=f"floor as m grows: {base * rho:.1f}")
ax[1].plot([M], [base * (1 + (M - 1) * rho) / M], "o", color=labs.BLUE, label=f"m = {M}: {base * (1 + (M - 1) * rho) / M:.1f}")
ax[1].set(title="More adults per town cannot replace towns", xlabel="adults measured per town (m)",
ylabel="towns per arm", xscale="log", ylim=(0, 80))
ax[1].set_xticks([5, 10, 20, 50, 100, 200, 500])
ax[1].set_xticklabels(["5", "10", "20", "50", "100", "200", "500"])
ax[1].minorticks_off()
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Use 8 towns per arm of 130 adults (about the same number of adults). What is the real power of the cluster analysis?
- Set the town sd to 0 (no clustering). Do the two analyses now agree, and which has more power?
- Add each town's pilot mean (its town effect plus noise of sd 16/sqrt(30)) as a covariate in a cluster-level regression and measure the gain in power.
Problems, with solutions
Try each problem before opening its solution.
-
A Poisson MLE and its sandwich (Parts 22, 24).
Solution
- Data: 0, 0, 0, 0, 1, 2, 2, 4, 5, 6, 9, 11.
- The MLE: ℓ(λ) = Σyᵢ log λ − nλ, and the score Σyᵢ/λ − n = 0 gives λ̂ = ȳ = 40/12 = 3.333.
- The model-based SE: I(λ) = n/λ, so SE = √(λ̂/n) = 0.527.
- The sandwich: per observation, the score is uᵢ = yᵢ/λ − 1 and the Hessian −yᵢ/λ². So A = n/λ̂ and B = Σ(yᵢ − λ̂)²/λ̂², and A⁻¹BA⁻¹ = Σ(yᵢ − ȳ)²/n² = 154.67/144, giving SE = 1.036.
- Report the sandwich: s² = 14.1 against ȳ = 3.33. In the World the variance is 5.8 times the mean, and the model-based interval covers 50%.
-
One IRLS step (Parts 21, 24). At β = 0 every μᵢ = ½.
Solution
- The weights are wᵢ = nᵢμᵢ(1 − μᵢ) = nᵢ/4; the working response is zᵢ = ηᵢ + (p̂ᵢ − μᵢ)/(μᵢ(1 − μᵢ)) = 4(p̂ᵢ − ½).
- Bliss's data give X'WX = [[120.25, 215.71], [215.71, 387.43]] and X'Wz = (50.50, 100.79).
- So β⁽¹⁾ = (−37.86, 21.34), and ℓ rises from −333.40 to −200.01.
- Converged (six steps to eight decimals): β̂ = (−60.72, 34.27), SEs (5.18, 2.91). The LD50 is 60.72/34.27 = 1.7717 on the log10 scale, about 59.1 mg/l.
-
ML and REML (Parts 23, 25).
Solution
- ML: profiling out β gives ℓ = −(n/2) log σ² − RSS/(2σ²), maximized at RSS/n. Because E[RSS] = (n − p)σ², this is biased by (n − p)/n.
- REML: let K be n × (n − p) with orthonormal columns orthogonal to X. Then K'y ~ N(0, σ²I), free of β, with ‖K'y‖² = y'(I − H)y = RSS. Its likelihood −((n − p)/2) log σ² − RSS/(2σ²) is maximized at RSS/(n − p).
- Longley: RSS = 836,424, so ML gives 52,277 and REML 92,936 (ratio 9/16). Twenty thousand simulations average 52,287 and 92,955 at σ² = 92,936.
-
The eight schools (Parts 25, 26).
Solution
- Integrating out θⱼ gives yⱼ | μ, τ ~ N(μ, σⱼ² + τ²).
- With a flat prior on μ, p(τ | y) ∝ V_μ^{1/2} Πⱼ (σⱼ² + τ²)^{−1/2} exp(−(yⱼ − μ̂_τ)²/(2(σⱼ² + τ²))), where μ̂_τ = Σwⱼyⱼ/Σwⱼ, wⱼ = 1/(σⱼ² + τ²) and V_μ = 1/Σwⱼ.
- E[θⱼ | τ, y] = (1 − Bⱼ)yⱼ + Bⱼμ̂_τ, with Bⱼ = σⱼ²/(σⱼ² + τ²).
- Adaptive quadrature over τ ∈ [0, ∞), with flat priors on μ and τ ≥ 0, gives median τ = 5.24 and 90th percentile 13.73. School A goes from 28 to 11.40. The plot shows [0, 30], excluding 0.501% of posterior mass from its display only. The pooled mean is 7.7 (SE 4.1).
-
MCMC diagnostics (Part 27). Split R̂ = √(((n − 1)/n W + B/n)/W), rank-normalized (Vehtari et al. 2021).
Solution
- Badly tuned: 1.45 ≫ 1.01 says the chains disagree. A bulk ESS of 8 says 4,000 draws carry the information of eight. 87% acceptance says the steps are too small to cross between the modes at ±3.
- Fix: proposal SD 4. Acceptance is then 40%, R̂ 1.006 and bulk ESS 458.
- Caveat: R̂ compares only what the chains found. Had all four started in one mode, it would have looked perfect, so use overdispersed starts.
-
AIC against BIC (Part 28). Ozone on temperature, n = 111, degree d with k = d + 2 parameters:
Solution
d log-lik AIC BIC 1 −508.89 1023.78 1031.90 2 −502.62 1013.24 1024.08 3 −501.98 1013.95 1027.50 4 −498.73 1009.46 1025.72 5 −498.60 1011.21 1030.17 - AIC chooses 4; BIC (log 111 = 4.71 per parameter) chooses 2.
- For nested models AIC adds a needless term whenever its χ²₁ statistic exceeds 2. That has probability 0.157 at every n, so AIC is not consistent: it chooses a true quadratic about 74% of the time as n grows.
- BIC's penalty log n → ∞ drives that probability to zero (0.99 at n = 2,560).
-
Silverman's rule (Part 29).
Solution
- h = 0.9 min(s, IQR/1.349) n^(−1/5) = 0.9 × min(13.59, 17.79) × 272^(−0.2) = 0.9 × 13.59 × 0.3259 = 3.99.
- LSCV(h) = ∫f̂² − (2/n)Σf̂₋ᵢ(xᵢ) has expectation E[ISE] − ∫f² under iid sampling at fixed h. It chooses 2.65.
- The 0.9 constant is a robust rule of thumb, whereas the Gaussian normal-reference AMISE constant is about 1.06; a bimodal density has more curvature (larger ∫f''²) and needs less smoothing. Use LSCV or Sheather–Jones, and show both.
-
The variance's influence function (Part 30).
Solution
- Contaminate: F_ε = (1 − ε)F + εδₓ, so μ_ε = μ + ε(x − μ).
- Then T(F_ε) = (1 − ε)∫(y − μ_ε)²dF + ε(x − μ_ε)². Differentiating at 0 gives −σ² − 2(x − μ)∫(y − μ)dF + (x − μ)², so IF(x) = (x − μ)² − σ².
- Newcomb's −44: IF = 4,816, about 73 when divided by n = 66. The variance is 113.7 with the point and 38.5 without.
- Sensitivity curves: the mean's is unbounded (26.21), the median's bounded (27.0), Huber's bounded and smooth (27.38). The modern value is 33.0.
-
A lasso KKT check (Part 32).
Solution
- Let gⱼ = xⱼ'(y − Xβ̂)/n. At the solution, gⱼ = λ sign(β̂ⱼ) where β̂ⱼ ≠ 0, and |gⱼ| ≤ λ where β̂ⱼ = 0. These are necessary and, by convexity, sufficient.
- The colleague's β̂ (least squares soft-thresholded once) fails: g_lcavol = 0.137, and the worst violation on the support is 0.182. The predictors are correlated up to 0.76.
- Coordinate descent at λ = 0.1 has support {lcavol, lweight, lbph, svi, pgg45} with gⱼ = 0.1 exactly. Off the support, max |gⱼ| = 0.056.
-
BH by hand (Part 33). Compare p₍ᵢ₎ with i/120.
Solution
- p₍₈₎ = 0.0458 ≤ 0.0667, while p₍₉₎ = 0.172 > 0.075, so reject 8 (all eight happen to be below their own lines in this example).
- Bonferroni (0.1/12 = 0.0083) allows 4. The BH-adjusted p-values are 0.0024, 0.0066, 0.0156, 0.0246, 0.0295, 0.0434, 0.0687, 0.0687, 0.229, 0.361, 0.714, 0.882.
- The promise: E[V/max(R, 1)] ≤ q for valid null p-values under independence or the specific PRDS condition. It is an average over uses, not a statement about this list.
- On the 6,033 genes: BH finds 59, Bonferroni 7.
-
Split conformal (Part 34).
Solution
- k = ⌈(n + 1)(1 − α)⌉ = ⌈10 × 0.8⌉ = 8. The 8th smallest of 0.4, 0.9, 1.2, 1.6, 2.1, 2.7, 3.3, 4.4, 5.8 is 4.4, so the interval is 10 ± 4.4 = [5.6, 14.4].
- Coverage: under exchangeability, the test residual's rank among the n + 1 is uniform. So P(R₍ₙ₊₁₎ ≤ R₍ₖ₎) ≥ k/(n + 1) = 0.8.
- The guarantee is marginal and assumes only exchangeability.
- On ozone (37 fit, 37 calibrate, 37 test): k = 35 and q = 51.9 ppb, so the forecast at 85°F is 56 ± 52. All 37 test days are covered; CQR would let the width follow the spread.
-
Kaplan–Meier and Greenwood (Part 40).
Solution
- Ŝ(6) = 18/21 = 0.857, Ŝ(7) = 0.857 × 16/17 = 0.807, Ŝ(10) = × 14/15 = 0.753, Ŝ(13) = × 11/12 = 0.690.
- Greenwood: Σd/(n(n − d)) = 3/378 + 1/272 + 1/210 + 1/132 = 0.02395, so SE = 0.690 × √0.02395 = 0.107.
- Log-log: s = √0.02395/|log 0.690| = 0.417, and Ŝ^{exp(±1.96 s)} = [0.432, 0.849].
- The medians are 23 weeks (6-MP) and 8 (placebo); the log-rank χ²₁ = 16.8.
-
The variance of a cluster trial.
Solution
- ȳⱼ = μ + τzⱼ + bⱼ + ēⱼ has variance ρσ² + (1 − ρ)σ²/m = σ²[1 + (m − 1)ρ]/m.
- The difference of two arm means of k such terms has variance 2σ²[1 + (m − 1)ρ]/(km).
- Setting that equal to δ²/(z + z)² and letting m → ∞ gives k ≥ 2(z + z)²ρσ²/δ².
-
A collider's bias.
Solution
- Take T and Y independent, and V = 1 with probability g(αT + βY), with α = β = 1 and g the logistic function, and T and Y independent Bernoulli(1/2).
- Then P(T = 1 | V = 1, Y = y) = P(T = 1) E[g(α + βy)] / E[g(αT + βy)], which is about 0.594 at y = 0 and 0.546 at y = 1. So T and Y are dependent given V, though independent unconditionally ("explaining away").
-
The information identity.
Solution
- If the model is correct, E[U U'] = −E[∂U/∂θ'], that is B = A, by differentiating ∫f = 1 twice.
- Then A⁻¹BA⁻¹ = A⁻¹ = I⁻¹.
-
IRLS is Newton.
Solution
- For a GLM with canonical link, U = X'(y − μ) and −∂U/∂β' = X'WX, with W = diag(Var(yᵢ)).
- The Newton step β + (X'WX)⁻¹X'(y − μ) equals (X'WX)⁻¹X'Wz, with z = η + W⁻¹(y − μ).
- With a non-canonical link the observed Hessian carries an extra term with mean zero. IRLS uses the expected one: Fisher scoring.
-
The orthonormal lasso.
Solution
- If X'X = nI, the objective separates into Σⱼ [½(βⱼ − β̂ⱼ^OLS)² + λ|βⱼ|] (up to constants).
- Each term is minimized by the soft threshold sign(β̂ⱼ^OLS)(|β̂ⱼ^OLS| − λ)₊.
-
BH controls the FDR.
Solution
- For a true null i with independent p-values, write the FDR as Σ over nulls i and k of (1/k) P(pᵢ ≤ qk/m, R = k).
- Conditioning on the other p-values (the leave-one-out argument of Benjamini & Yekutieli 2001), each true null contributes at most q/m for super-uniform null p-values (equality for continuous uniform nulls).
- Summing over the m₀ nulls gives FDR ≤ q m₀/m ≤ q; equality holds for independent continuous uniform null p-values.
Notes and sources
Where it comes back
- Part 43: what a random variable is, and why the limit theorems hold.
- Part 47: the sandwich's asymptotics, proved.
- Part 49: AIPW attains the semiparametric efficiency bound.
- Part 55: the qualifying exam, the PhD's version of this part.
- Part 58: anytime-valid inference and adaptive designs revisit trial design.
Glossary
- Consulting.
- Estimand; smallest effect worth detecting; protocol; pre-registration; CONSORT: the shape of a design question.
- Cluster trials.
- Unit of randomization; contamination; intraclass correlation; design effect; cluster-level analysis; the floor on clusters: the cluster trial's vocabulary.
- Observational analysis.
- Confounding by indication; back-door set; mediator; collider; bad control: what the graph decides.
- Sensitivity.
- Robustness value; partial R²; benchmark: how strong a hidden confounder would need to be.
- The exam.
- Score; information; sandwich; IRLS; working response; REML; error contrasts; partial pooling; R̂; ESS; AIC; BIC; bandwidth; LSCV; influence function; sensitivity curve; KKT conditions; FDR; step-up; conformal quantile; Greenwood's formula; log-log interval: the exam's tools.
Sources
- Consulting and design.
- R. A. Fisher, Sankhyā 4 (1938), the "post mortem" remark; J. Cornfield, Am. J. Epidemiol. 108 (1978).
- A. Donner & N. Klar, Design and Analysis of Cluster Randomization Trials in Health Research (2000); R. Hayes & L. Moulton, Cluster Randomised Trials (2nd ed. 2017).
- M. Campbell, G. Piaggio, D. Elbourne & D. Altman, BMJ 345 (2012), CONSORT for cluster trials; D. Cox & C. Donnelly, Principles of Applied Statistics (2011).
- Observational analysis.
- M. Hernán & J. Robins, Causal Inference: What If (2020); J. Robins, A. Rotnitzky & L. P. Zhao, JASA 89 (1994).
- C. Cinelli & C. Hazlett, JRSS B 82 (2020); D. Rubin (1987); B. Neal et al., NEJM 385 (2021).
- The exam.
- C. Bliss, Ann. Appl. Biol. 22 (1935); J. Longley, JASA 62 (1967); H. D. Patterson & R. Thompson, Biometrika 58 (1971).
- D. Rubin, J. Educ. Stat. 6 (1981); A. Gelman et al., Bayesian Data Analysis (3rd ed. 2013); A. Vehtari et al., Bayesian Anal. 16 (2021).
- H. Akaike, IEEE Trans. Autom. Control 19 (1974); G. Schwarz, Ann. Stat. 6 (1978); B. Silverman, Density Estimation (1986).
- M. Rudemo, Scand. J. Stat. 9 (1982); F. Hampel, JASA 69 (1974); S. Stigler, Ann. Stat. 5 (1977).
- R. Tibshirani, JRSS B 58 (1996); Y. Benjamini & Y. Hochberg, JRSS B 57 (1995); J. Lei et al., JASA 113 (2018).
- E. Freireich et al., Blood 21 (1963); E. Gehan, Biometrika 52 (1965); M. Greenwood, Reports on Public Health and Medical Subjects 33 (1926).
- D. Cox & D. Hinkley, Problems and Solutions in Theoretical Statistics (1978); L. Wasserman, All of Statistics (2004).
About this partfrom its README
Part 42 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the last part of Stage III, Master's. Like Part 20, it adds no new method. A client writes with two questions and a deadline. The comprehensive exam follows. The part covers:
- Case 1, a trial to design:
- the estimand;
- the unit of randomization;
- the intraclass correlation from a pilot;
- the sample size with a design effect;
- the analysis plan, tested by simulation before use.
- Case 2, an observational survey to analyse:
- the causal graph;
- bad controls;
- imputation of a missing confounder;
- overlap and balance;
- AIPW;
- a robustness value with benchmarks;
- a one-page report.
- Twelve exam problems, each posed, paused and solved on screen:
- a Poisson MLE with its model-based and sandwich SEs;
- one IRLS step;
- ML against REML for a variance;
- the eight schools' posterior;
- MCMC diagnostics;
- AIC against BIC;
- a KDE bandwidth;
- an influence function;
- a lasso KKT check;
- BH by hand;
- a split-conformal interval;
- Kaplan–Meier with Greenwood's variance.
The MSc goes on the Transcript, and the PhD core begins (→ Part 43).
Built in this part:
- The MSc problem bank: the twelve exam problems and six more, each with a full solution, below.
- The exam card (
ExamCardinexplainer/stats/viz.py), the part's instrument: a problem's card with its number, topic, the parts it draws on, its marks, the question, and a pause clock.sweep()turns the clock while the viewer works,shrink()lifts the card so the solution can be worked beneath, andstamp()seals it solved. - The World gains its
ministryblock:- the pilot survey: 30 adults in each of 200 towns, with town effects of SD 3.5 mm Hg and a year's drift of SD 1.5;
- the salt-substitute survey of 3,000 adults, drawn from
World.substitute_draw, the law of uptake, potassium (the mediator), the clinic visit (the collider) and who withholds income.
Data.
- From the Museum:
- Bliss's beetles (1935);
- Longley (1967), via statsmodels;
- Rubin's eight schools;
- Old Faithful's waiting times (Azzalini & Bowman 1990);
- Newcomb's 1882 timings of light (Stigler 1977);
- Stamey's prostate data (via The Elements of Statistical Learning);
- Singh et al.'s (2002) prostate microarray (R's
sda, GPL ≥ 2); - New York's air quality, 1973;
- Freireich's 6-MP trial as tabulated by Gehan (1965).
- From the World: the pilot, the trial's towns and the salt-substitute survey.
- The rest are seeded simulations.
The Coverage Board gains ten rows:
| Method | Setting | Achieved | Verdict |
|---|---|---|---|
| individual-level t, cluster trial | 42 towns × 50 adults, ICC 0.054 | 60.9% | broken |
| cluster-level t | same | 90.2% | kept |
| cluster-level ANCOVA on the pilot | same | 90.0% | kept |
| naive difference in means | 3,000 adults, income MAR for over a third | 0.0% | broken |
| regression adjusting for a collider | same | 7.5% | broken |
| AIPW on complete cases | same | 81.5% | broken |
| AIPW with multiple imputation | same | 87.8% | kept |
| Poisson MLE, model-based SE | the World's doctor visits, n = 500 | 50.1% | broken |
| Poisson MLE, sandwich SE | same | 89.2% | kept |
| split conformal, 99 calibration points | the World's pressure from age and BMI | 89.9% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | A letter from the ministry | two questions, six weeks |
| 1 | Case 1: what to randomize | pilot ICC 0.034 [0.020, 0.048]; truth 0.046, then 0.054 |
| 2 | Case 1: how many towns | 267 per arm × DE 3.70 → 21 towns per arm, 42 in all |
| 3 | Case 1: the analysis plan | type I error 30% vs 5.3%; power 82% → 95%; trial −3.13 [−5.99, −0.27] |
| 4 | Case 2: the survey and its graph | +6.7 raw; −2.33 adjusted; +0.09 with the mediator; −4.18 with the collider |
| 5 | Case 2: imputation and AIPW | 37% missing, FMI 0.13; AIPW −2.22 [−3.42, −1.01] |
| 6 | Case 2: sensitivity and the report | RV 0.074; benchmark (0.040, 0.033); the trial's −3.3 |
| 7 | Exam I: likelihood | SEs 0.527 vs 1.036; β = (−60.72, 34.27); σ² 52,277 vs 92,936 |
| 8 | Exam II: Bayes and model choice | A: 28 → 11.4; R̂ 1.45 → 1.01; AIC 4 vs BIC 2 |
| 9 | Exam III: smoothing, robustness, sparsity | h 3.99 vs 2.65; IF 4,816; KKT 0.182 off |
| 10 | Exam IV: discoveries, guarantees, survival | BH 8 vs 4, genes 59 vs 7; 10 ± 4.4; Ŝ(13) = 0.690 ± 0.107 |
| 11 | Outro | the MSc |
Case 1. The ministry wants community health workers in its towns, and must decide between a fall of 4 mm Hg (worth paying for) and none.
- The unit. Households randomized within a town contaminate one another, so towns are randomized (Cornfield 1978: analysing a group-randomized trial as if individuals were randomized is "an exercise in self-deception").
- The pilot's ICC.
- The one-way ANOVA of 6,000 pilot adults gives MSB = 545.1, MSW = 263.8 and σ̂²_b = 9.38, so ρ̂ = 0.034.
- A bootstrap over towns gives a 90% interval of [0.020, 0.048].
- Planning value 0.055: the upper end plus a year's drift. The World's truth is 0.046 in the pilot year and 0.054 in the trial year.
- The size.
- n = 2(1.96 + 0.84)²σ²/δ² = 267 per arm with σ = 16.5.
- The design effect 1 + 49 × 0.055 = 3.70 gives 987 adults, so 19.7 → 20 towns of 50 per arm. Hayes & Moulton add one for the t: 21 per arm, 42 towns, 2,100 adults.
- The floor as m → ∞ is 2(z + z)²ρσ²/δ² = 14.7 towns per arm. Ten adults per town needs 82 towns; five hundred still needs 34.
- With the pilot's ρ̂ the plan would have recruited 15 per arm; each 0.01 of ρ costs about 2.6 towns per arm.
- Treating adults as independent, eight towns per arm "has" 93% power; the truth is 38%.
- The plan, simulated from the towns' law (4,000 trials).
- Type I error: 30.2% for the individual-level analysis, 5.3% for both cluster-level analyses.
- Power: 81.7% for the cluster t and 95.1% for the cluster ANCOVA on the pilot mean; the SD of τ̂ falls from 1.34 to 1.09.
- The trial run in the World.
- ANCOVA −3.13 [−5.99, −0.27]; cluster t −2.67 [−5.92, 0.57]; the individual-level interval [−4.09, −1.26] is less than half as wide as the cluster t's.
- The truth is −4.
Case 2. A potassium-enriched salt substitute went on sale a year before the survey; 819 of 3,000 adults use it.
- The raw comparison. Users' pressure is 6.7 mm Hg higher (90% CI 5.5 to 7.9).
- Confounding by indication. Users are older (56.9 vs 43.3 years), heavier (BMI 29.1 vs 26.9), slightly richer, and three times as likely to have been told their pressure is high (37% vs 11%).
- The graph.
- The back-door set is {age and sex, BMI, income, diagnosis}.
- Potassium is a mediator (users excrete 95 vs 65 mmol a day). The clinic visit is a collider (36% vs 11%).
- Over 40 imputations: adjusted −2.33; adding the mediator +0.09; adding the collider −4.18.
- Missing income. 37% withhold it: 63% of those under 40 and 10% of those over 60; 22% of users against 43% of
non-users; less often at higher pressure.
- Complete cases select on the outcome.
- MI from age, sex, BMI, diagnosis, T, Y and T × Y (m = 40) has an FMI of 0.13.
- Overlap and balance. Propensities run from 0.02 to 0.93. The largest SMD falls from 0.78 to 0.04 after weighting.
- AIPW with Rubin's rules. −2.22 (SE 0.73), 90% CI [−3.42, −1.01]. With every income known it would be −2.26; the truth is −3.0.
- Sensitivity.
- The adjusted OLS gives t = −4.23 on 2,993 df, so RV = 0.074 and approximate RV₀.₀₅ = 0.041.
- The benchmark, "told: high pressure", has classical-OLS partial R² 0.040 with uptake and 0.033 with pressure. A confounder twice as strong would not erase the effect; three times as strong would.
- The real trial. The Salt Substitute and Stroke Study (Neal et al. 2021) randomized 600 Chinese villages (20,995 adults): systolic pressure −3.34 mm Hg, stroke rate ratio 0.86 (0.77–0.96).
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: the client. A consulting request from the World's ministry of health.
- Case 1: a design question. Sample size, randomization unit, analysis plan, worked through (Parts 13, 35).
- Case 2: an observational question. DAG, adjustment set, estimator, sensitivity, report (Parts 36, 41).
- Exam problems, each posed, paused and solved:
- an MLE with its asymptotic variance and a sandwich;
- a GLM's IRLS step;
- a REML derivation;
- a posterior for a hierarchical model;
- MCMC diagnostics;
- AIC vs BIC;
- a KDE bandwidth;
- an influence function;
- a lasso KKT check;
- BH by hand;
- a conformal interval;
- a Kaplan–Meier curve with Greenwood bands.
- Outro. The Transcript: the MSc. The PhD core begins.
Built: the MSc problem bank (every problem with a full solution in the README).
Build the film
python -m videos.stats.stats42.compute # the part's numbers, into .cache/stats42
python tools/build.py stats42 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats42 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats42. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
OMP_NUM_THREADS=1 python -m videos.stats.stats42.compute # once (about a minute)
python tools/build.py stats42 -q l # fast 480p preview
python tools/build.py stats42 # 1080p30 -> renders/stats42.mp4
python tools/qa_scene.py stats42 TrialSize
python tools/lecture_length.py stats42 --floor 50