Which Model?
How do you choose a model without fooling yourself?
In 1983 David Freedman regresses a hundred observations of noise on fifty columns of noise, keeps the columns that look promising and runs the regression again: the second round is significant 95% of the time. The gap between how a chosen model fits and how it predicts is optimism, and the part measures it: 2 sigma squared d over n for least squares, and a covariance that defines degrees of freedom for any procedure. Cp and AIC estimate prediction error and are derived by two Taylor expansions; BIC comes from Laplace's method and answers a different question. On the model-selection bench, with Stamey's prostate data, AIC chooses seven predictors and BIC two, and two simulations show the trade: BIC finds a true quadratic 99% of the time at large n where AIC stays near 75%, and AIC predicts better at n = 1,000 when every candidate is wrong. Cross-validation, PSIS-LOO and WAIC do the same job by prediction, singular models break BIC's count of parameters, and stacking beats Bayesian model averaging when no candidate is true. The part ends with the cost of choosing (the naive interval after AIC covers 75%) and with forecasts judged by calibration and proper scores.
What you need. Part 19's cross-validation, Part 22's likelihood asymptotics (Taylor expansions around the MLE, Wilks's theorem) and Part 26's marginal likelihood.
- Hook
- Freedman's paradox, 1983
- Mathematics
- optimism, AIC and BIC derived, CV and GCV, PSIS-LOO, WAIC, MDL, stacking
- Built
- a model-selection bench
What you will be able to do
Bachelor's
- Explain Freedman's paradox: why a regression on screened noise looks significant, and what splitting the data would have shown.
- Read a curve of training error and test error against model size and say where optimism comes from.
Master's
- Derive the optimism of a linear smoother from Efron's covariance formula, and the leave-one-out shortcut from Sherman-Morrison.
- Derive AIC as an estimate of expected Kullback-Leibler loss and BIC from Laplace's method, and say which goal each serves.
- Compute PSIS-LOO and WAIC from posterior draws and read the Pareto k-hat warnings.
PhD
- Compute the real log canonical threshold of a singular model by hand and state Watanabe's free-energy expansion that replaces BIC's d/2.
- State the conflict between consistency and minimax-rate efficiency (Yang 2005) and what it does not rule out.
Practice
- Choose a model size by cross-validation with the search redone inside every fold, and apply the one-standard-error rule.
- Report inference after selection honestly: split the sample, or say that the naive interval undercovers.
- Judge a probabilistic forecast by its PIT histogram, log score and CRPS.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 9 min · Master's 50 min · PhD 55 min · Practice 23 min.
- 0Freedman's paradox, 1983Bachelor's2 min
- 1OptimismBachelor's4 min
- 2Cp and AICMaster's5 min
- 3BICMaster's5 min
- 4Cross-validation theoryMaster's4 min
- 5Bayesian LOO and WAICMaster's4 min
- 6Singular modelsPhD5 min
- 7Minimum description lengthMaster's4 min
- 8AveragingMaster's5 min
- 9Inference after selectionPractice4 min
- 10Subset selectionPractice4 min
- 11Calibrated forecastsPractice5 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Freedman's paradox, 1983Bachelor's2 min
In 1983 David Freedman ran an experiment on an empty box. A hundred observations of a response and fifty predictors, every one of them independent random noise. Regress the response on all fifty, keep the predictors that look promising, and run the regression again. It was the standard practice of the day. Run on pure noise, it finds a significant model.
Round one. Each dot is one predictor's p-value. With fifty predictors and a hundred observations, R squared is point four six, but the overall F test, p of point seven six, gives no evidence against the null in this run. A large p-value is not proof that every coefficient is zero. Fourteen predictors have p-values below point two five: keep those. Two are below point oh five, about what chance would give.
Round two: regress again on only the fourteen kept. R squared is still point two seven, from fewer predictors. Now the overall F test gives p of point oh one three: significant. Four individual coefficients are significant at five percent. Every number in this regression is noise. The p-values were computed as if the fourteen had been chosen in advance, but they were chosen for looking significant.
Was that run unlucky? Repeat the experiment a thousand times. Honest p-values would spread evenly between zero and one, the grey line. The second-round p-values pile up near zero: ninety-five percent of the time, pure noise produces a significant regression. Typically twelve predictors survive screening, and five or six of them look individually significant.
The lesson: choosing a model with the data, then testing it on the same data, is circular. The more choice you have, the better the chosen fit looks, whether or not anything is there; statisticians call the gap optimism. This part estimates predictive optimism with AIC and cross-validation, contrasts BIC's evidence objective, uses splitting to separate selection from inference, and considers corrections after selection. And it asks what the chosen model is for: to predict well, or to find the truth, which turn out to be different goals.
Numbers: p 0.76 → 0.013; 94.7% of 1,000 repeats
1OptimismBachelor's4 min
The phenomenon in miniature. Thirty noisy points from a smooth curve, the truth dashed in gold. A straight line misses the bend. A cubic follows it. A degree-ten polynomial follows the points best of all, chasing their noise, and its training error is the smallest of the three.
Average over six hundred data sets. Training error falls with every added degree, below even the noise variance. Error on new responses at the same x values falls, bottoms out a little above the noise floor, flat at about point three from degree three to six, and then climbs as the polynomial starts fitting noise. The gap between the two curves is the optimism of the training error.
The shape has a simple anatomy. The error of a prediction at a new point is the noise, plus the squared bias of the fit there, plus its variance, Part 9's decomposition. For least squares with d coefficients, averaged over the design points, the variance term is sigma squared d over n: it grows with every coefficient, while the bias falls. The training error has the same noise and bias, but the fit has absorbed d dimensions of the noise, so it sits sigma squared d over n below the noise level instead of above. The gap is two sigma squared d over n.
Bradley Efron made the gap precise. The optimism is the expected in-sample prediction error minus the expected training error. It equals two over n times the sum of the covariances between each fitted value and its own observation: a fit that copies its data looks good on that data. For a linear fit with d parameters, the covariances sum to sigma squared times d, so the optimism is two sigma squared d over n. At degree three, four parameters, the simulated gap is point oh six seven, as the formula says, and the same holds at every degree.
That suggests a definition. A procedure's degrees of freedom are the summed covariances between fitted and observed values, divided by sigma squared: how hard the fit copies the data. For a fixed linear smoother S, independent of the observed responses, it is the trace of S under the equal-variance model, the effective number of parameters of a ridge regression or a spline, Part 29. For Gaussian noise and suitable weak differentiability and integrability, Stein's lemma identifies it with the expected divergence. Discontinuous selection rules require care. And for any procedure at all, stepwise selection included, it can be measured by simulation.
A surprising example. Fit the lasso of Part 19 to responses simulated around the prostate data's eight predictors, at four penalties, and measure its degrees of freedom by the covariance. The table compares covariance degrees of freedom, now with Monte Carlo error, to one plus the average active count. Hui Zou, Trevor Hastie and Robert Tibshirani proved it: for Gaussian responses, a fixed penalty and a suitable fixed full-rank design, the active count is an unbiased degrees-of-freedom estimate. Tuning the penalty adds another selection step; this is not a free-search theorem for every lasso procedure. Best-subset selection, by contrast, costs more than its count of coefficients.
Numbers: gap 0.067 = 2σ²d/n; lasso df ≈ 1 + nonzeros
2Cp and AICMaster's5 min
Mallows's Cp and Akaike's information criterion. The direct cure: estimate the optimism and add it back. Colin Mallows's Cp is the training error plus two d sigma squared over n, with a noise-variance estimate, often from a sufficiently rich full model. With fixed linear fits and an unbiased noise estimate, its expectation is prediction error for new responses at the same design points, so choosing the model with the smallest Cp aims at the best predictor. It is chapter one's optimism, made into a criterion.
Hirotugu Akaike generalized it beyond squared error. Measure how far a fitted model is from the unknown truth g by the Kullback–Leibler divergence. Up to a constant that is the same for every model, minimizing it means maximizing the expected log density of new data under the fitted model, the log score of Part 24. The maximized log likelihood estimates that, but optimistically, because the same data chose theta hat: by about k, the number of parameters. Correct for it, multiply by minus two, and you have AIC.
Where k comes from, in two Taylor expansions. The log likelihood at the truth is the maximized log likelihood minus half a quadratic form in the estimation error. The new data's expected log likelihood at the estimate is its value at the truth minus the same quadratic form. That quadratic form is, in expectation, Part 22's chi-squared with k degrees of freedom: it averages k. So the training log likelihood sits k over two above the truth's, and the new data's k over two below it: an optimism of k in total, when the model is correct.
AIC's k assumes the model is right. If it isn't, Part 22's sandwich appears: the quadratic form averages the trace of J times K inverse, where J is the variance of the score and K the expected curvature. Kei Takeuchi's criterion uses that trace as the penalty. A Poisson regression for the World's doctor visits, intercept and age, has two parameters, but Takeuchi's penalty is nine point five, because the visits are far more variable than a Poisson allows. Fitted to data that really are Poisson, the same trace is one point eight, close to two. In practice the estimated penalty is noisy and relies on regularity and suitable independent observations. It corrects an expected log-score bias; it does not repair every model defect.
With small samples AIC is itself optimistic about big models. The corrected AICc adds two k times k plus one over n minus k minus one. The Taylor argument assumes k is small relative to n; when it isn't, AIC chooses models that are too large. For correctly specified Gaussian linear regression with unknown variance and n greater than k plus one, this is an exact correction for each fixed candidate, from Nariaki Sugiura, and Clifford Hurvich and Chih-Ling Tsai. Kenneth Burnham and David Anderson's advice: use AICc unless n is more than about forty times k.
The model-selection bench, on real data: Stamey's prostate cancer study, sixty-seven men in the training set, log PSA predicted from eight clinical measures, with the best subset of each size. Teal is each model's misfit, minus twice its log likelihood above the best one's; it shrinks as predictors are added. Blue is AIC's penalty, two per parameter. Their sum is smallest at seven predictors, everything except gleason. These are searched fits; a penalty based on their coefficient counts alone does not account for the whole subset-search procedure.
AIC differences are meaningful for comparable likelihoods on the same data and response scale. The absolute value depends on the likelihood convention. Here are the six best sizes, ranked by their difference from the best. Six predictors are half a unit behind seven, four a little over one, five and eight under two. Burnham and Anderson's rule of thumb: models within two of the best have substantial support, those four to seven behind considerably less, and those more than ten behind essentially none. Five models here are within two: AIC has a favourite, but not a winner.
Numbers: TIC 9.47 vs k = 2; AIC picks 7 of 8
3BICMaster's5 min
The Bayesian information criterion. BIC comes from Bayes, not from prediction. The evidence for a model, Part 26's marginal likelihood, is the likelihood integrated against the prior. Laplace's method at the maximum gives the maximized likelihood times the prior there times a volume factor, two pi to the k over two over the square root of the determinant of the information. The information grows like n, so its determinant grows like n to the k, and the log evidence is the maximized log likelihood minus k over two log n, plus terms that don't grow. Gideon Schwarz dropped those terms: minus twice it is BIC, whose penalty per parameter is log n rather than two.
What did Schwarz throw away? The dropped constant involves the prior at the estimate and the information per observation. Robert Kass and Larry Wasserman noticed that for one particular prior, a normal centred at the estimate with the information of a single observation, the unit-information prior, in a regular setting those leading constants cancel. Centering this illustrative prior at the estimate uses the data; it is not a uniquely prescribed fixed prior or an automatic Bayes-factor guarantee. So the exponentiated difference in BIC approximates a Bayes factor under a prior worth one data point: diffuse, and so, by Part 26's Lindley paradox, kind to small models.
Back on the bench, AIC chose seven predictors. With sixty-seven men, BIC charges log sixty-seven, four point two, per parameter, more than twice AIC's price. Its total is smallest at two predictors: cancer volume and prostate weight. The same data, two respectable criteria, and models of seven and two predictors. The difference is not a technicality: they are trying to do different things.
First, when the truth is among the candidates: data from a quadratic, polynomials of degree zero to six, three hundred data sets at each sample size. BIC's chance of picking degree two climbs to ninety-nine percent: it is consistent. AIC's stalls around three quarters, however much data arrives: a quarter of the time it adds a superfluous term. Its fixed penalty of two is beaten, now and then, by noise; for a fixed regular candidate list containing the identifiable truth, BIC's growing penalty yields model-selection consistency.
Second, when no candidate is true: a smooth curve that is not a polynomial, approximated by polynomials up to degree twelve, and judged by prediction risk. With a thousand points, AIC's choices predict fifteen percent better than BIC's: this finite experiment favours AIC at that sample size. It does not establish an asymptotic efficiency theorem for the fixed list of degrees zero through twelve. With fifty points, plain AIC's licence to fit degree-twelve polynomials is a disaster, and AICc repairs most of it. Yuhong Yang studied a tradeoff between model-identification consistency and uniform risk adaptation. That result has a specific scope; it is not a ban on every criterion being both consistent and prediction-efficient in a finite regular candidate list.
Why AIC plateaus. For two nested models differing by one parameter, AIC prefers the larger exactly when twice the log likelihood gain exceeds two. If the smaller model is true, that statistic is, by Part 22's Wilks theorem, chi-squared with one degree of freedom. So AIC picks the superfluous parameter with probability tending to fifteen point seven percent, whatever n is: it is a likelihood-ratio test at level point one five seven. With several superfluous degrees on offer, Ritei Shibata computed the limiting chances, and they match the plateau. BIC's threshold is log n, which grows, so its chance of overfitting goes to zero.
So: if you want to identify the true model and believe it is among your candidates, BIC. If you want good predictions and suspect the truth is more complex than any candidate, as it usually is, AIC, AICc or cross-validation. Neither tells you the chosen model is right, and neither makes its p-values honest, Freedman's lesson, which chapter nine takes up.
Numbers: picks 2; P(true degree) 0.99 vs AIC's 0.75; P(χ²₁ > 2) = 0.157
4Cross-validation theoryMaster's4 min
Part 19 introduced cross-validation; here is its theory. For ordinary least squares, and compatible fixed-penalty linear fits, leave-one-out has an algebraic shortcut: the left-out residual is the ordinary residual divided by one minus that point's leverage. Summing their squares gives PRESS, from David Allen and Mervyn Stone in 1974. Replacing each leverage by the average gives generalized cross-validation, Peter Craven and Grace Wahba's: training error inflated by one minus the degrees of freedom over n, squared. Across four hundred regressions the two correlate at point nine nine.
On the prostate data, ten-fold cross-validation of the best subset of each size, with conventional fold-based error bars. Because the fold fits overlap, these are a tuning heuristic, not confidence intervals. The lowest CV error is at seven predictors, AIC's answer. But the curve is nearly flat from two predictors on: every size from two to eight except three is within one standard error of the best. Part 19's one-standard-error rule picks the smallest model within that band, two predictors, BIC's answer. Cross-validation's estimates are noisy, and the noise matters.
On the same data, the shortcuts. Green is ten-fold cross-validation, with the best subset chosen again inside every fold. Gold is PRESS, exact leave-one-out for each fixed subset, computed from the leverages without a single refit. Purple is GCV, all but identical to PRESS. At several sizes they sit below the cross-validation curve; one reason is that they evaluate the subset that was chosen using all sixty-seven men; only the honest version repeats the search and pays for it.
But what does cross-validation estimate? Two different things could be meant: the error of the very model you fitted to your training set, or the error of the procedure, averaged over all the training sets you might have had. Stephen Bates, Trevor Hastie and Robert Tibshirani showed in 2024 that in their normal linear-regression setting, cross-validation can track average procedure error while being nearly uninformative about the realized error of one fit. This is not a universal statement that CV carries no conditional-error information for every learning algorithm. And the usual standard error across folds is too small, because the folds share data; they propose a nested-CV construction for interval estimation. Ordinary nested hyperparameter tuning alone does not guarantee a valid error interval.
How many folds? Each fold's model is fitted to a fraction K minus one over K of the data. If expected prediction error decreases with training size, fitting on fewer observations induces an upward training-size bias, usually larger for small K. Nonmonotone learning curves are possible. Leave-one-out has almost no bias, but its n fitted models are nearly identical, so their errors are highly correlated and their average can be variable, especially for unstable procedures like subset selection. Leo Breiman and Philip Spector, and Ron Kohavi, found five or ten folds a good compromise, and that remains the default.
See it. Four hundred simulated regressions, fifty observations, ten predictors of which four matter. For each training set, its true error on new data against its ten-fold CV estimate. They are uncorrelated: minus point oh six. A training set that produced a bad fit is not one that cross-validation flags. Yet on average they agree, one point three two against one point three: cross-validation estimates the procedure's expected error well, and says almost nothing about this particular fit.
Practical rules. Five or ten folds is a common compromise. Relative variance and training-size bias depend on the learning procedure and its learning curve. Every data-driven step, selection included, must be redone inside each fold, or the estimate is optimistic, Part 19's warning. With time series or grouped data, leave out whole blocks. And use cross-validation to compare procedures; to know one fitted model's error, there is no substitute for fresh data.
Numbers: one-SE picks 2; corr(CV, true error) −0.06
5Bayesian LOO and WAICMaster's4 min
For Bayesian models, the natural target is the expected log predictive density of new data: how probable the posterior predictive makes fresh observations. Leave-one-out estimates it by predicting each observation from the posterior fitted without it. Each term is a posterior predictive density, an integral over the leave-one-out posterior. Done literally, that is n separate fits, each an MCMC run. Part 27's importance sampling avoids them.
The leave-one-out posterior differs from the full posterior only by one likelihood term. So the full posterior's draws can be reweighted by one over that observation's likelihood. The weighted average then estimates the leave-one-out predictive density. These weights can have heavy tails, so Aki Vehtari, Andrew Gelman and Jonah Gabry smooth them with Part 27's Pareto fit, and each estimated k-hat warns about a deletion's weight-tail stability. The warning threshold depends on effective sample size and is capped near point seven.
Sumio Watanabe's WAIC takes another route. Start from the log predictive density of the observed data, which is optimistic. Estimate the optimism by the posterior variance of each observation's log likelihood, summed: an effective number of parameters. Subtract. Under suitable analytic and integrability assumptions, Watanabe established asymptotic equivalence to Bayesian leave-one-out for important singular-model settings. This is not a finite-sample guarantee for every model.
Compare predictions of a whole left-out school. Complete pooling uses a flat common-mean prior; the hierarchy uses flat mean and scale priors with a proper posterior. Independent effects now have explicit normal priors with standard deviation one hundred: a flat prior would leave the held-out effect undefined. Complete pooling has PSIS score minus thirty point six zero, versus analytic leave-one-out minus thirty point five six. The hierarchy gives minus thirty-one point one eight, versus the numerical reference minus thirty-one point three four. The independent model's PSIS score is minus thirty-six point four six, but its analytic score is minus forty-four point three three. The failed importance approximation is much too optimistic. The small pooling-versus-hierarchy difference also needs uncertainty, not just a ranking.
The weight-tail diagnostics help explain these approximations. Complete pooling shares information across schools, so each deletion changes relatively little. The hierarchy has more variable deletion weights and needs closer inspection. For independent effects under the diffuse proper prior, deleting a school's only measurement leaves its broad prior; reweighting the much narrower full posterior is difficult. Large k-hats warn against trusting PSIS. Here exact analytic prediction is available; in other cases refit or integrate out local latent effects. A low k-hat alone would not prove accuracy.
With the explicit proper independent-effect priors, compare both approximations against the analytic leave-one-school-out score of minus forty-four point three three. PSIS gives about minus thirty-six point five and WAIC about minus thirty-three point nine: both are too optimistic, with high k-hats warning that importance sampling is unstable. Their difference is not itself a measurement of the truth. For the hierarchy, both approximations are much closer to the numerical refit reference. PSIS-LOO is useful because its tail diagnostics help identify difficult deletions, which should then be checked or refitted.
When comparing models this way, report the differences in elpd with their standard errors. For these eight schools the pooling-versus-hierarchy lead is small and uncertain. The caption reports a rough paired pointwise standard error; with only eight heterogeneous schools, it needs caution. Four elpd units is a practical heuristic, not a universal decision boundary. These are estimates of predictive accuracy, not tests of which model is true. And rather than choose, it is often better to weight, chapter eight.
Numbers: refit/analytic −30.56 / −31.34 / −44.33; check PSIS tail warnings
6Singular modelsPhD5 min
The classical AIC and BIC derivations just used regular, identifiable parameterizations with nonsingular information. Cross-validation and importance-sampling identities do not themselves require all those assumptions. Many useful models aren't regular. Take a mixture: with probability a, a standard normal is shifted by b. Suppose the truth is a plain standard normal. Then any parameter with a equal to zero is true, whatever b is, and so is any parameter with b equal to zero, whatever a is. The true parameters form a cross. Along it the Fisher information is singular, and the Taylor expansions behind AIC and BIC, which divided by it, fail.
Here is the parameter plane, with the true set in gold: the whole left edge, where the weight is zero, and the whole middle line, where the shift is zero. The orange curves are the log likelihood's level sets for a hundred standard normal draws. The high-likelihood region is no ellipse around a point; it is a broad band hugging the cross. With two thousand draws it narrows, but slowly and unevenly. Near the crossing, the leading volume is proportional to log n over root n, whereas a regular two-parameter model gives one over n. That exponent is what BIC gets wrong.
Watanabe asked what the log evidence really does. Call minus the log evidence the free energy. For a regular model it is the minimized negative log likelihood plus d over two log n: BIC. For a singular model, Sumio Watanabe proved in 2009, using resolution of singularities from algebraic geometry, that it is lambda log n, with a log log n correction. Lambda is the real log canonical threshold, a birational invariant of the true set. In the well-behaved realizable analytic setting with an appropriate positive prior, it is at most d over two and can be smaller: a singular model is effectively simpler than its parameter count.
For the mixture it can be done by hand. Near the intersection a equals b equals zero, the leading divergence is half a squared times b squared. Away from that intersection the coefficient changes, though the relevant local vanishing structure remains. The evidence is governed by the prior volume of parameters whose divergence is below a small t, which scales like t to the lambda. The set where a squared b squared is below t has volume of order root t times log one over t. So lambda is one half, with multiplicity two: half the exponent of a regular two-parameter model.
Check it numerically. For sample sizes from thirty to ten thousand, compute the evidence by quadrature over the parameter plane, for six data sets each. A regular two-parameter normal model: its free energy grows with slope point nine nine in log n, the predicted one. The mixture's grows with slope point four two. Watanabe's one half, pulled down a little by the log log n term. BIC would charge the mixture the full one, giving the wrong leading evidence penalty for this singular example. Mixtures and neural models can also have locally regular regions; not every instance shares this exponent.
The real log canonical threshold has been worked out for many models. For a regular model it is d over two, BIC's value. For our mixture at a single-component truth, one half instead of one. For reduced-rank regression, Miki Aoyagi and Watanabe computed it exactly, with thresholds depending on matrix dimensions and the fitted and true ranks; at singular lower-rank truths they can differ from the regular half-dimension penalty. For neural networks, the threshold depends on architecture, the true parameter stratum and the prior. Counting only the units used by one representation is not a general formula. And it depends on where the truth lies, not only on the model, so no penalty that just counts parameters can be right for singular models.
Singular models are everywhere: mixtures, hidden Markov models, factor analysis, reduced-rank regression, and neural networks with redundant or inactive units. A finite permutation symmetry alone does not make a locally identified mode singular. For important analytic singular settings, WAIC and Bayesian leave-one-out retain asymptotic predictive relationships under additional assumptions. Finite-sample approximation and sampling diagnostics still matter. His WBIC estimates the evidence from a single posterior tempered at one over log n. And Mathias Drton and Martyn Plummer's singular BIC puts the right lambda into a BIC, model by model.
Numbers: slopes 0.42 vs 0.99 (theory ½ vs 1)
7Minimum description lengthMaster's4 min
A third tradition starts from compression. Any probability distribution defines a code: by Shannon, minus log two p is an ideal code length; integer prefix-code lengths may need rounding. And by Kraft's inequality, uniquely decodable prefix-code lengths satisfy a subprobability bound. With suitable normalization, codes and probability models are closely related. Jorma Rissanen's idea: to send data, first send a model, then the data using that model's code. The best model gives the shortest total: a model that captures real regularities compresses; one that memorizes noise costs too much to describe.
Apply it to chapter one's thirty points. The teal bars are the bits needed to send the responses given each polynomial's fit, up to a common discretization constant; they fall as the degree rises. The gold bars are the bits to send the coefficients. In a regular fixed-dimensional approximation, precision of order one over root n gives a leading half log two n penalty per coefficient and for the noise scale. Ranges, model-index coding and data discretization contribute additional terms. This leading-term relative code criterion selects degree five in this dataset. The averaged prediction-risk curve also had its minimum there, a numerical coincidence rather than a coding guarantee. Half log n per parameter is BIC's penalty, arrived at by an entirely different road.
The two-part code is crude. A sharper code would use the best-fitting parameter for the data at hand, but that isn't a distribution: its sum over all possible data sets exceeds one. Yuri Shtarkov's normalized maximum likelihood divides by that sum when it is finite. Unrestricted Gaussian models often require restrictions or another coding construction. Every data set then costs the same amount more than its hindsight-optimal code, the log of the normalizer, and no code does better in the worst case. That excess, the regret, is the model's complexity. Rissanen showed it is k over two log n over two pi, plus the log of Jeffreys's prior's total volume: BIC, refined by the geometry of the model.
For a coin, the regret can be computed exactly, summing over all possible numbers of heads. Rissanen's approximation is half log of n pi over two, because the Jeffreys volume of a coin is pi. It is off by a sixth of a nat at ten flips and by less than two hundredths at a thousand: the complexity of a one-parameter model grows like half log n, the same rate for every regular parameter.
A third code is sequential. Any joint probability factors into one-step-ahead predictions, so a code length is a running total of forecasting losses. Predict each observation from the estimate fitted to those before it: Philip Dawid's prequential approach, honest because no observation helps predict itself. Part 26's marginal likelihood is exactly such a sum, which explains why it penalizes complexity. For suitably regular well-specified models and properly initialized predictors, their leading redundancy can be k over two log n. This is not a statement about every plug-in predictor or improper evidence. MDL, Bayes and honest prediction meet, and chapter eleven returns to Dawid's forecasts.
Numbers: degree 5 at 40.9 bits; regret ≈ ½ log(nπ/2)
8AveragingMaster's5 min
Choosing one model throws away the uncertainty about which. Bayes's answer: give each model a prior probability, and its posterior probability is proportional to the prior times the evidence. Predict with the posterior-weighted mixture of the models' predictions. Its uncertainty includes both the uncertainty within each model and the uncertainty between them, the case Jennifer Hoeting, David Madigan, Adrian Raftery and Chris Volinsky made in 1999. Under the stated joint prior and log score, the posterior predictive is Bayes optimal for prior-averaged prediction. Merely containing the fixed true model does not guarantee finite-sample dominance over every predictor.
With p predictors there are two to the p subsets, too many to average over. David Madigan and Adrian Raftery's Occam's window keeps only the models within a factor of twenty of the best. Madigan and Jeremy York's MC cubed runs a Markov chain over the models themselves, Part 27's machinery on a discrete space. And the prior on models matters: a uniform prior on subsets piles its mass on models of half the size, so James Scott and James Berger recommend a beta-binomial prior on the number of predictors, which also corrects for multiplicity.
José Bernardo and Adrian Smith named the distinction. In the M-closed world the truth is one of the candidates. In the M-open world none is, and the honest goal is the best combination. In that world Bayesian model averaging behaves oddly: as data accumulate, with a unique KL-best candidate and suitable conditions, its weights concentrate there. Equal-KL candidates, as in our symmetric example, need not converge to one fixed winner, because the evidence of each model is a product over observations. Yet a weighted mixture of wrong models can be much closer to the truth than any one of them.
A stark example. The truth is a fifty-fifty mixture of two normals, at minus two and plus two. Model one says every observation is normal around minus two. Model two says plus two. Both are wrong, and equally wrong. But an equal mixture of their predictions is exactly the truth. Which weights do the two methods find?
A hundred data sets at each sample size, from twenty to five hundred. Plotted is the weight given to whichever model a method favours. Bayesian model averaging puts ninety-nine percent on one model, already at twenty observations: whichever happened to have slightly more data on its side, chosen essentially by coin toss. Stacking chooses the weights that maximize the leave-one-out log score of the mixture; it puts fifty-nine percent on the favourite at twenty and moves towards half and half as n grows, which is the right answer.
Judge the predictions on two thousand new draws by their log score. The single candidate selected on the training data scores about minus five point four: it assigns almost no probability to half of the data. Bayesian model averaging also loses heavily in this example because it has in effect chosen one model. As sample size grows, stacking approaches the true predictive distribution's score, near minus two point oh five. Here the mixture improves prediction greatly. That is an example of stacking's potential benefit under misspecification, not a theorem that it always beats Bayesian weights.
Stacking, in the Bayesian form of Yuling Yao, Aki Vehtari, Daniel Simpson and Andrew Gelman: choose weights on the simplex to maximize the summed log of the weighted leave-one-out predictive densities. When its diagnostics are adequate, chapter five's PSIS-LOO can estimate those densities without a full refit for every point. Weighting each model by its exponentiated elpd, pseudo-BMA, is cheaper but behaves like BMA, piling weight on one model. For point predictions the idea is older: David Wolpert's stacked generalization and Leo Breiman's stacked regressions, today's super learners.
Back to the prostate data. Burnham and Anderson's Akaike weights turn AIC differences into weights. No subset size gets more than about a third of them; the weight spreads over four to eight predictors. For a fixed candidate list with appropriate model and parameter priors, BIC differences can approximate posterior model odds. Here we display normalized criterion weights for one searched subset per size; they are not posterior probabilities of subset sizes or of all possible models. They move the weight to smaller models, but split it almost evenly between two, three and four predictors. Either way the message is the same as chapter four's flat CV curve: the data do not single out one subset, and any report that pretends they do overstates what is known.
Numbers: BMA 0.99 on one model; stacking −2.06 vs truth −2.05
9Inference after selectionPractice4 min
Recall the hook. A hundred rows of pure noise, fifty columns of noise, and an F-test that rightly finds nothing. Keep the columns with p-values below a quarter, refit, and the regression's p-value is point oh one three, with four coefficients significant at five percent. In ninety-five percent of a thousand repeats. Every criterion in this part selects; none of them makes the usual tests and intervals of the selected model valid.
Why, in the simplest case. A coefficient whose true value is point oh five is estimated with standard error point one. Roughly, AIC keeps a predictor when its t-statistic exceeds root two in size: the red tails. That happens about a fifth of the time. And when it does, the estimate is, on average, almost four times the truth in size. Only estimates with extreme magnitudes survive, including some with the wrong sign: the winner's curse.
The usual interval covers ninety-five percent of the time, averaged over all data sets. But it is only reported when the predictor is kept. Given that, its coverage is the chance of covering and being kept, over the chance of being kept. A normal calculation gives about seventy-six percent for this known-standard-error normal example. The relevant guarantee is coverage conditional on the selection that led us to look, the idea Yoav Benjamini and Daniel Yekutieli formalized for selected parameters, and William Fithian, Dennis Sun and Jonathan Taylor for selected models.
The Board runs the full procedure: ten independent candidate predictors, a hundred observations, x one's coefficient point oh five, forward stepwise selection by AIC, and the usual ninety-five percent interval for x one whenever it is kept, two thousand times. It is kept about a fifth of the time, and then its interval covers the truth seventy-five percent of the time: broken, and in line with the calculation. Select on a random half of the data and compute the interval on the other half: ninety-five point seven percent, kept. And the full model with no selection covers ninety-five percent, as it must.
Splitting is the oldest fix, from David Cox in 1975. With a valid inferential model and a well-defined target, an untouched independent half supports inference regardless of the selection rule on the first half. Changing the covariates can change the target coefficient; the Board's independent predictors avoid that population-target problem. The price is power, since each task gets half the data, and an answer that depends on the random split. Here x one was kept about as often from half the data as from all of it, but its intervals are wider by a factor of about root two.
Three modern fixes use all the data. Richard Berk and colleagues' PoSI widens intervals enough to cover simultaneously over every model that could have been chosen. Jason Lee, Dennis Sun, Yuekai Sun and Jonathan Taylor showed that for suitable fixed-tuning lasso and forward-stepwise selection records, conditioning on the appropriate signs and choices yields polyhedral events under a Gaussian model. Data-dependent tuning needs additional treatment. Data fission uses auxiliary randomness and an appropriate observation model to separate selection and inference information. Independent components require the corresponding construction and assumptions; they are not arbitrary deterministic pieces of an observation. Part 56 builds all three and puts them on the Board.
Numbers: 76% by the coherent known-SE calculation; Board 75.1% vs 95.7% split
10Subset selectionPractice4 min
Stepwise regression has a long charge sheet, set out by Frank Harrell among others. Its p-values and F-tests ignore the search that produced them, chapter nine's problem. The chosen coefficients are biased away from zero and their intervals are too narrow. It is unstable, Breiman's complaint: perturb the data slightly and a different model comes out. And it is greedy: adding one variable at a time can miss a pair that only works together.
The alternative to greed is to search everything: the subset of size s with the smallest residual sum of squares. There are two to the p subsets, and the problem is NP-hard in general. George Furnival and Robert Wilson's leaps and bounds prunes whole branches of the search tree, since adding variables can only lower the RSS; it handles thirty or forty predictors. Dimitris Bertsimas, Angela King and Rahul Mazumder used modern mixed-integer solvers to reach hundreds, with an optimality certificate when the solver closes the gap; difficulty and running time depend on the design. Statkit's best_subset enumerates, which is enough for the prostate data's eight.
Which wins? Trevor Hastie, Robert Tibshirani and Ryan Tibshirani ran the race in 2020; here is a small version: a hundred observations, ten correlated predictors of which five matter, and four signal-to-noise ratios. The plotted metric is prediction risk above irreducible noise, divided by the signal variance, so the zero predictor has relative excess risk one. Best subset and forward stepwise, each tuned on a validation set, run almost together. The lasso is green. When the signal is weak, the lasso wins clearly: its shrinkage tames the variance that subset selection's all-or-nothing choices add. When the signal is strong, best subset wins: unshrunk subset estimates can have less bias, while lasso shrinkage can cost accuracy. These are twenty-five-replication point estimates for one design, not a universal winner.
And the prostate data's verdict, on the thirty men held out. The null model's error is one point oh six. Full least squares: point five two. AIC's and CV's seven predictors: point five two. BIC's and the one-SE rule's two: point four nine. The lasso and ridge: point five oh. The nonnull methods' observed errors differ by about three hundredths. We now also compute paired test-case differences against full least squares: their standard errors range from about point oh oh five to point oh six five. A large individual-error SE is not itself evidence that two methods are equivalent. Chapter four's flat CV curve was telling the truth: on these data the choice hardly matters, and a confident claim that one model is best would be noise.
How stable are the prostate selections? Resample the sixty-seven men with replacement four hundred times and redo the best-subset search each time. The bars show how often each predictor is kept, blue for AIC and purple for BIC. AIC produced sixty-six different models, and its original seven-predictor choice came back only fifteen percent of the time. BIC produced sixty-two, and its pair came back eighteen percent of the time. Only cancer volume is kept every time. This is Breiman's instability, measured; Nicolai Meinshausen and Peter Bühlmann's stability selection uses structured subsampling and additional assumptions to obtain error control. These ordinary bootstrap frequencies are a descriptive stability check, not that guarantee.
The lesson. With weak signals, shrink: the lasso, ridge, and Part 25's James–Stein. With strong signals and a truly sparse truth, best subset can win. Hastie and the Tibshiranis found the relaxed lasso, which selects with the lasso and then shrinks less, close to the best of both. Tune any of them by cross-validation, and don't believe the chosen model's p-values.
Numbers: lasso wins at SNR 0.05, best subset at 6; 66 bootstrap models
11Calibrated forecastsPractice5 min
Chapter seven ended with Philip Dawid's view: a statistical model is a machine for issuing forecasts, one observation ahead. His prequential principle says to judge it only by the forecasts it issued and what then happened, not by its parameters or the story behind it. Two questions follow. Are its forecasts calibrated, meaning events it calls seventy percent likely happen seventy percent of the time? And, among calibrated forecasts, how sharp are they?
The tool is the probability integral transform. Each forecast is a whole distribution, issued before the observation arrives. Evaluate it at what happened. For continuous outcomes, if forecasts are the true conditional distributions given the relevant past information, the PIT values are independent uniforms. Discrete outcomes require a randomized transform: Part 7's inverse-CDF method run backwards. So their histogram should be flat, Dawid's proposal, made routine for economic forecasts by Francis Diebold, Todd Gunther and Anthony Tay.
Two thousand observations from a drifting level with unit noise, and four forecasters who all know the level. The calibrated one forecasts normal with the right spread: its PIT histogram is flat, within noise. The overconfident one uses half the spread: too many observations fall in its tails, and the histogram is U-shaped. The underconfident one doubles it: the observations crowd its middle, a hump. The biased one is shifted up by point seven: most observations fall below its median, and the histogram slopes down.
Score them. The log score of Part 24 is minus the log forecast density at the outcome; the continuous ranked probability score compares the whole forecast distribution with the outcome, in the units of the data. The calibrated forecaster wins on both. The overconfident one's ninety percent intervals cover only fifty-eight percent. The underconfident one's cover almost every observation, which looks safe but is penalized all the same: its forecasts are vaguer than they need be.
For each of sixty-seven prostate training observations, fit on the other sixty-six. Under a normal linear model with the reference prior, the predictive CDF is Student t, applied to the externally studentized residual. These leave-one-out PITs share training data, so ordinary independent-sample Kolmogorov–Smirnov p-values are not valid calibration tests. The two-predictor model has a higher average held-out log density than the intercept-only model. The full model gains about another hundredth of a nat. The displayed histograms and descriptive KS distances can reveal patterns, but neither a flat histogram nor a large uncalibrated p-value would prove that a model is calibrated. Assess prediction with appropriate held-out or model-based checks and proper scores.
Why these scores? A scoring rule charges a penalty for a forecast once the outcome is known. It is proper if a forecaster who believes G minimizes their expected penalty by reporting G itself: honesty is the best policy. Strictly proper if nothing else ties. The log score and CRPS are strictly proper, Tilmann Gneiting and Adrian Raftery's survey explains; squared error of the forecast mean is proper but not strictly proper over full distributions, because any forecast with the correct mean ties, regardless of its spread. AIC, WAIC and LOO are all estimates of an expected log score: this part's criteria are forecasters' scores in disguise.
The CRPS deserves a closer look. It is the integrated squared distance between the forecast CDF and the step function that jumps at the outcome. Equivalently, the expected distance from a forecast draw to the outcome, minus half the expected distance between two independent forecast draws: accuracy, with a rebate for honest spread. For a normal forecast it has a closed form, which statkit's crps_normal from Part 24 computes. And for a forecast that is a single point it is just the absolute error, so the CRPS lets point and probabilistic forecasts be compared on one scale.
Gneiting, Fadoua Balabdaoui and Raftery summed it up: maximize the sharpness of the forecasts, subject to calibration. Calibration alone isn't enough: a climatological forecast can be marginally calibrated and useful as a baseline, yet miss information that improves conditional prediction. So check the PIT histogram, and compare competing models by a proper score. Weather forecasters have worked this way since Glenn Brier's score of 1950, Scoring helps evaluate progress; improvements also depend on observations, physical models and computation.
Numbers: coverage 58% / 90% / 99.95%; LOO log score −1.63 vs −1.18
Recap, problems, and the road aheadAll tracks3 min
Part twenty-eight in twelve lines. Freedman's screening turned fifty columns of noise into a significant regression. Training error is optimistic by two sigma squared times the degrees of freedom over n, and degrees of freedom can be measured for any procedure. Mallows's Cp and Akaike's AIC add the optimism back; Takeuchi's TIC handles the wrong model and AICc small samples. BIC, from the Laplace approximation, can consistently identify a true model in a suitable fixed regular candidate list; its prediction ranking depends on the setting. Cross-validation estimates procedure performance; it can give limited information about the realized error of one fitted model. PSIS-LOO and WAIC bring prediction to Bayesian models, with k-hat as a warning light. Singular models like mixtures have Watanabe's lambda, one half here, in place of d over two. MDL chooses the model that compresses the data most, and rediscovers BIC. In our symmetric example, stacking learns the correct mixture while Bayesian model averaging concentrates on a randomly favoured candidate. Intervals after selection covered seventy-five percent, and splitting restored ninety-five. Our sparse-design experiment favours shrinkage at low signal and unshrunk subsets at high signal. And forecasts should be calibrated, checked by the PIT, and compared by proper scores.
Where it comes back. Part 29 chooses smoothing parameters by GCV and counts their degrees of freedom. Part 32 studies selection in high dimensions. Part 33 controls the false discovery rate and the coverage of selected effects. Part 34's conformal prediction gives predictive intervals with exchangeability and appropriate separation of fitting from calibration. Part 36 picks nuisance models for causal estimates by cross-fitting. Part 38 evaluates forecasts. Part 50 proves oracle inequalities for model selection. And Part 56 returns to inference after selection, in depth.
Six problems, with full solutions in the README. The optimism of a linear smoother; the leave-one-out shortcut; BIC from Laplace's method; AIC's penalty, exactly, for a normal mean; the probability that AIC overfits by one parameter, fifteen point seven percent, which explains chapter three's plateau; and why the log score is proper. Pause here if you want to try them.
The books this part follows: Burnham and Anderson on multimodel inference, chapters three and seven of The Elements of Statistical Learning, Claeskens and Hjort on model selection and averaging, Watanabe's algebraic geometry and Grünwald's MDL; with the papers from Mallows and Akaike to Bates, Hastie and Tibshirani.
Twenty-eight parts of sixty-five. We can now choose among models, and know what the choice costs. But every candidate today had a fixed number of parameters. What if the thing to estimate is a whole curve? The eruptions of Old Faithful have a distribution with two humps, or perhaps three, and no finite family is obliged to contain it. Part 29: smoothing.
Where it goes next. GCV and degrees of freedom choose the smoothing parameter in Part 29; the lasso's degrees of freedom and selection in high dimensions return in Part 32, conformal prediction in Part 34, oracle inequalities in Part 50, and inference after selection is done properly in Part 56.
Key results
The part's results in one place, for revision.
Try it
Lab 28 · Freedman's paradox and the price of a parameter
Repeat Freedman's two-round regression on pure noise 300 times with statkit.select, then fit polynomials of degree 0 to 10 to 30 noisy points 600 times and compare the gap between new-response and training error with 2 sigma^2 d / n for d = degree + 1 coefficients. Count how often AIC and BIC choose each degree.
python -m videos.stats.labs 28
needs numpy, scipy, matplotlib · download lab28.py ·
source on GitHubround 1 (all 50 columns): overall F significant at 5% 5.7% (honest: 5%)
round 2 (the screened columns): significant at 5% 95.3% (film: 94.7% of 1,000)
columns kept by the screen, median 12 (50 x 0.25 = 12.5 expected)
degree 1: new-response error minus training error 0.038 (2 sigma^2 (degree + 1) / n = 0.033)
degree 3: new-response error minus training error 0.066 (2 sigma^2 (degree + 1) / n = 0.067)
degree 10: new-response error minus training error 0.178 (2 sigma^2 (degree + 1) / n = 0.183)
degree with the lowest new-response error 5 (training error is lowest at degree 10)
mean degree chosen: AIC, BIC 5.37, 3.87
leave-one-out error, degree 3: shortcut, refitting 0.29079, 0.29079
Selection on the same data manufactures significance, and each fitted coefficient buys 2 sigma^2 / n of optimism: training error keeps falling while the error on new responses turns up.
The code (96 lines; it asserts its own result)
"""Lab 28: screen fifty columns of noise as Freedman did, and measure the optimism 2 sigma^2 d / n of a polynomial fit."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import select
TITLE = "Freedman's paradox and the price of a parameter"
GOAL = ("Repeat Freedman's two-round regression on pure noise 300 times with statkit.select, then fit polynomials of "
"degree 0 to 10 to 30 noisy points 600 times and compare the gap between new-response and training error "
"with 2 sigma^2 d / n for d = degree + 1 coefficients. Count how often AIC and BIC choose each degree.")
TASKS = [
"Screen at alpha = 0.05 instead of 0.25 (select.freedman's last argument). Is round two significant more or less often?",
"Raise n from 30 to 300 in the polynomial experiment. Which criterion's choice of degree settles down, and which keeps overfitting?",
"Replace AIC by select.aicc in the tally. How much of AIC's overfitting at n = 30 does the correction remove?",
]
def truth(x):
return np.sin(2.5 * x) + 0.5 * x
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. Freedman (1983): 100 observations, 50 predictors, all noise; keep those with p < 0.25 and refit.
reps = 300
runs = [select.freedman(100, 50, rng) for _ in range(reps)]
p1 = np.array([r["first"]["pF"] for r in runs])
p2 = np.array([r["second"]["pF"] for r in runs])
kept = np.array([len(r["second"]["cols"]) for r in runs])
lab.row("round 1 (all 50 columns): overall F significant at 5%", f"{np.mean(p1 < 0.05):.1%} (honest: 5%)")
lab.row("round 2 (the screened columns): significant at 5%", f"{np.mean(p2 < 0.05):.1%} (film: 94.7% of 1,000)")
lab.row("columns kept by the screen, median", f"{np.median(kept):.0f} (50 x 0.25 = 12.5 expected)")
assert np.mean(p1 < 0.05) < 0.11, "the first-round F test is honest"
assert np.mean(p2 < 0.05) > 0.85, "after screening, noise looks significant"
assert 10 <= np.median(kept) <= 15
# 2. Optimism: thirty points from a smooth curve, noise sd 0.5, polynomials of degree 0..10.
n, sigma, R = 30, 0.5, 600
x = np.linspace(-1.5, 1.5, n)
degs = np.arange(11)
H = [select.hat_matrix(np.polynomial.legendre.legvander(x / 1.5, d)) for d in degs]
train, new = np.zeros(len(degs)), np.zeros(len(degs))
picks = {"AIC": np.zeros(len(degs)), "BIC": np.zeros(len(degs))}
for _ in range(R):
y = truth(x) + sigma * rng.standard_normal(n)
y2 = truth(x) + sigma * rng.standard_normal(n) # new responses at the same x
crit = {"AIC": [], "BIC": []}
for k, d in enumerate(degs):
fit = H[k] @ y
rss = float(np.sum((y - fit) ** 2))
train[k] += rss / n / R
new[k] += np.mean((y2 - fit) ** 2) / R
ll = select.gaussian_ll(rss, n)
crit["AIC"].append(select.aic(ll, d + 2))
crit["BIC"].append(select.bic(ll, d + 2, n))
for name in picks:
picks[name][int(np.argmin(crit[name]))] += 1 / R
gap, theory = new - train, 2 * sigma ** 2 * (degs + 1) / n
for d in (1, 3, 10):
lab.row(f"degree {d}: new-response error minus training error", f"{gap[d]:.3f} (2 sigma^2 (degree + 1) / n = {theory[d]:.3f})")
best = int(np.argmin(new))
lab.row("degree with the lowest new-response error", f"{best} (training error is lowest at degree {int(np.argmin(train))})")
mean_deg = {k: float(v @ degs) for k, v in picks.items()}
lab.row("mean degree chosen: AIC, BIC", f"{mean_deg['AIC']:.2f}, {mean_deg['BIC']:.2f}")
assert np.max(np.abs(gap - theory)) < 0.03, "the optimism of least squares is 2 sigma^2 d / n"
assert np.argmin(train) == 10 and 3 <= best <= 6, "training error always prefers the largest model"
assert mean_deg["BIC"] < mean_deg["AIC"], "BIC's log n per parameter chooses smaller models than AIC's 2"
# 3. The leave-one-out shortcut against refitting thirty times.
X = np.polynomial.legendre.legvander(x / 1.5, 3)
y = truth(x) + sigma * rng.standard_normal(n)
brute = np.mean([(y[i] - X[i] @ np.linalg.lstsq(np.delete(X, i, 0), np.delete(y, i), rcond=None)[0]) ** 2 for i in range(n)])
lab.row("leave-one-out error, degree 3: shortcut, refitting", f"{select.press(X, y):.5f}, {brute:.5f}")
assert abs(select.press(X, y) - brute) < 1e-9, "PRESS is residual / (1 - h_ii), exactly"
lab.note = ("Selection on the same data manufactures significance, and each fitted coefficient buys 2 sigma^2 / n "
"of optimism: training error keeps falling while the error on new responses turns up.")
fig, ax = labs.figure(2, size=(11, 4.2))
bins = np.linspace(0, 1, 21)
ax[0].hist(p1, bins=bins, color=labs.BLUE, alpha=0.6, label="round 1: all 50 noise columns")
ax[0].hist(p2, bins=bins, color=labs.RED, alpha=0.6, label="round 2: the columns that passed")
ax[0].axhline(reps / 20, color=labs.MUTED, ls="--", label="honest p-values")
ax[0].set(title="Freedman's paradox: overall F-test p-values", xlabel="p-value", ylabel=f"count of {reps} repeats")
ax[0].legend()
ax[1].plot(degs, train, "o-", color=labs.BLUE, label="training error")
ax[1].plot(degs, new, "o-", color=labs.RED, label="error on new responses")
ax[1].plot(degs, train + theory, "--", color=labs.GOLD, label="training error + 2 sigma^2 (degree + 1) / n")
ax[1].axhline(sigma ** 2, color=labs.MUTED, ls=":", label="noise variance")
ax[1].set(title="Optimism: thirty points, 600 data sets", xlabel="polynomial degree (0 to 2 are off the scale)", ylabel="mean squared error",
ylim=(0, 0.6))
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Screen at alpha = 0.05 instead of 0.25 (select.freedman's last argument). Is round two significant more or less often?
- Raise n from 30 to 300 in the polynomial experiment. Which criterion's choice of degree settles down, and which keeps overfitting?
- Replace AIC by select.aicc in the tally. How much of AIC's overfitting at n = 30 does the correction remove?
Problems, with solutions
Try each problem before opening its solution.
1. The optimism of a linear smoother. For \(\hat y = Sy\) with \(S\) fixed and \(\mathrm{Var}(y) = \sigma^2 I\), show that the optimism is \(2\sigma^2 \mathrm{tr}(S)/n\).
Solution
Let μ = E y, and let y⁰ be an independent copy. Then E(y⁰ᵢ − ŷᵢ)² = σ² + E(ŷᵢ − μᵢ)². Also E(yᵢ − ŷᵢ)² = σ² + E(ŷᵢ − μᵢ)² − 2Cov(yᵢ, ŷᵢ), expanding (yᵢ − μᵢ) − (ŷᵢ − μᵢ). Averaging, the optimism is (2/n)Σ Cov(yᵢ, ŷᵢ). With ŷ = Sy, Cov(ŷ, y) = S Var(y) = σ²S, and the diagonal sums to σ² tr S. So the optimism is 2σ² tr(S)/n, and 2σ²d/n for least squares with d columns (tr H = d).
2. The leave-one-out shortcut. For least squares with hat matrix \(H\), show that \(y_i - \hat y_{-i} = (y_i - \hat y_i)/(1 - h_{ii})\).
Solution
Write A = XᵀX and β̂₋ᵢ = (A − xᵢxᵢᵀ)⁻¹(Xᵀy − xᵢyᵢ). Sherman–Morrison gives (A − xxᵀ)⁻¹ = A⁻¹ + A⁻¹xxᵀA⁻¹/(1 − h), with h = xᵀA⁻¹x = hᵢᵢ. Multiplying out, xᵢᵀβ̂₋ᵢ = (ŷᵢ − hᵢᵢyᵢ)/(1 − hᵢᵢ). Then yᵢ − xᵢᵀβ̂₋ᵢ = (yᵢ − hᵢᵢyᵢ − ŷᵢ + hᵢᵢyᵢ)/(1 − hᵢᵢ) = (yᵢ − ŷᵢ)/(1 − hᵢᵢ).
3. BIC from Laplace's method. Derive BIC from Laplace's method: show \(\log p(y \mid M) = \ell(\hat\theta) - \tfrac k2 \log n + O_p(1)\).
Solution
Expand ℓ(θ) = ℓ(θ̂) − ½(θ − θ̂)ᵀJₙ(θ − θ̂) + …, where Jₙ = −∇²ℓ(θ̂) = n Ĵ₁ and Ĵ₁ → I₁. Integrating against a prior continuous and positive at θ̂ gives p(y | M) = e^{ℓ(θ̂)} p(θ̂)(2π)^{k/2}|nĴ₁|^{−1/2}(1 + O_p(n^{−1/2})). Taking logs, log p(y | M) = ℓ(θ̂) − (k/2) log n + [log p(θ̂) + (k/2) log 2π − ½ log|Ĵ₁|] + o_p(1). The bracket is O_p(1). Multiply by −2 and drop it: BIC.
4. AIC's penalty for a normal mean, exactly. Show AIC's penalty for the normal mean with known \(\sigma\): \(E[\ell(\hat\mu)] - E[\ell_{\text{new}}(\hat\mu)] = 1\), exactly.
Solution
With σ known, ℓ(μ) = c − Σ(yᵢ − μ)²/(2σ²) and μ̂ = ȳ. E Σ(yᵢ − ȳ)² = (n − 1)σ², so E ℓ(μ̂) = c − (n − 1)/2. For new data y′ (n independent copies), E Σ(y′ᵢ − ȳ)² = nσ²(1 + 1/n) = (n + 1)σ², so E ℓ_new(μ̂) = c − (n + 1)/2. The difference is exactly 1 = k: AIC's penalty is exact here.
5. AIC overfits by one parameter 15.7% of the time. Show that for nested models differing by one parameter, AIC prefers the larger with probability \(\to P(\chi^2_1 > 2) = 0.157\).
Solution
AIC prefers M_{k+1} to M_k iff −2ℓ_{k+1} + 2(k + 1) < −2ℓ_k + 2k, that is, iff 2(ℓ_{k+1} − ℓ_k) > 2. Under M_k (regular, nested), Wilks's theorem gives 2(ℓ_{k+1} − ℓ_k) → χ²₁, so the probability tends to P(χ²₁ > 2) = 2(1 − Φ(√2)) = 0.157. BIC's threshold log n → ∞, so its probability → 0.
6. The log score is strictly proper. Show that the log score is strictly proper: \(E_g[-\log f(Y)]\) is minimized over densities \(f\) at \(f = g\).
Solution
E_g[−log f(Y)] − E_g[−log g(Y)] = E_g log(g/f) = KL(g ‖ f). By Jensen, KL ≥ 0, with equality only if f = g almost everywhere. So reporting the true g uniquely minimizes the expected log score.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| GCV and degrees of freedom for smoothers | 29 |
| the lasso's df; selection in high dimensions | 32 |
| FDR and selected effects | 33 |
| conformal prediction | 34 |
| cross-fitting nuisance models | 36 |
| forecast evaluation | 38 |
| oracle inequalities, minimax rates | 50 |
| selective inference in depth | 56 |
| the Coverage Board | every part; 65 |
Glossary
- Optimism; in-sample error; covariance penalty: the expected amount by which training error understates error on new responses at the same x; Efron's (2/n)Σ Cov(ŷᵢ, yᵢ).
- Degrees of freedom (effective): Σ Cov(ŷᵢ, yᵢ)/σ²; tr S for a linear smoother; the expected divergence by Stein's lemma.
- Cp; AIC; AICc; TIC:
- Mallows's training error plus 2dσ̂²/n;
- −2ℓ + 2k, an estimate of expected KL to the truth;
- its small-sample correction;
- Takeuchi's misspecification-robust penalty tr(JK⁻¹).
- BIC; unit-information prior; consistency; efficiency:
- −2ℓ + k log n, from the Laplace approximation to the evidence;
- the prior under which it is accurate;
- choosing the true model with probability → 1;
- attaining the best achievable prediction risk.
- PRESS; GCV; K-fold CV; one-SE rule:
- leave-one-out squared error by leverages;
- its average-leverage version;
- cross-validation with K folds;
- the smallest model within one SE of the best.
- Err versus Err_XY: the expected error of a procedure versus the error of the fitted model in hand.
- elpd; PSIS-LOO; Pareto k̂; WAIC; p_loo, p_WAIC: expected log predictive density; its Pareto-smoothed leave-one-out estimate and diagnostic; Watanabe's criterion; effective numbers of parameters.
- Singular model; real log canonical threshold (RLCT); free energy; WBIC; sBIC:
- a model whose information matrix is singular at the truth;
- the λ replacing d/2;
- minus the log evidence;
- Watanabe's tempered-posterior evidence;
- Drton and Plummer's singular BIC.
- MDL; Kraft's inequality; two-part code; NML; regret; prequential:
- choose the shortest description;
- codes are distributions;
- model then data;
- Shtarkov's normalized maximum likelihood;
- its minimax excess code length;
- sequential predictive codes.
- BMA; Occam's window; MC³; M-closed and M-open; stacking; pseudo-BMA; Akaike weights: averaging by posterior model probabilities and its computation; whether the truth is a candidate; weights chosen for predictive performance; exp(elpd) and exp(−AIC/2) weights.
- Selective inference; winner's curse; data splitting; PoSI; polyhedral lemma; data fission: valid inference after data-driven selection, and the methods that achieve it.
- Best subset; leaps and bounds; mixed-integer optimization; forward stepwise; relaxed lasso; stability selection: subset search and its relatives.
- PIT; calibration; sharpness; proper scoring rule; log score; CRPS:
- F(y) at the outcome, uniform if F is right;
- forecasts agree with frequencies;
- concentration of the forecasts;
- honesty minimizes expected penalty;
- −log f(y);
- E|X − y| − ½E|X − X′|.
Sources
- History. D. Freedman, The American Statistician 37 (1983); T. Stamey et al., J. Urology 141 (1989).
- Optimism and degrees of freedom. B. Efron, JASA 81 (1986) and 99 (2004); C. Stein, Ann. Stat. 9 (1981); H. Zou, T. Hastie & R. Tibshirani, Ann. Stat. 35 (2007).
- Information criteria.
- C. Mallows, Technometrics 15 (1973); H. Akaike, 2nd Int. Symp. Information Theory (1973), IEEE Trans. Aut. Control 19 (1974); K. Takeuchi, Suri-Kagaku 153 (1976).
- N. Sugiura, Comm. Stat. A7 (1978); C. Hurvich & C.-L. Tsai, Biometrika 76 (1989).
- G. Schwarz, Ann. Stat. 6 (1978); R. Kass & L. Wasserman, JASA 90 (1995).
- R. Shibata, Biometrika 63 (1976) and 68 (1981); Y. Yang, Biometrika 92 (2005).
- Cross-validation. D. Allen, Technometrics 16 (1974); M. Stone, JRSS B 36 (1974); P. Craven & G. Wahba, Numer. Math. 31 (1979); L. Breiman & P. Spector, Int. Stat. Rev. 60 (1992); R. Kohavi, IJCAI (1995); S. Bates, T. Hastie & R. Tibshirani, JASA 119 (2024).
- Bayesian.
- A. Vehtari, A. Gelman & J. Gabry, Stat. Comput. 27 (2017); S. Watanabe, JMLR 11 (2010) and 14 (2013), and Algebraic Geometry and Statistical Learning Theory (2009).
- M. Aoyagi & S. Watanabe, Neural Networks 18 (2005); M. Drton & M. Plummer, JRSS B 79 (2017).
- MDL. J. Rissanen, Automatica 14 (1978) and IEEE Trans. Inf. Theory 42 (1996); Y. Shtarkov, Probl. Inf. Transm. 23 (1987); A. P. Dawid, JRSS A 147 (1984); P. Grünwald, The Minimum Description Length Principle (2007).
- Averaging.
- J. Hoeting, D. Madigan, A. Raftery & C. Volinsky, Stat. Sci. 14 (1999); D. Madigan & A. Raftery, JASA 89 (1994); D. Madigan & J. York, Int. Stat. Rev. 63 (1995); J. Scott & J. Berger, Ann. Stat. 38 (2010).
- J. Bernardo & A. Smith, Bayesian Theory (1994); D. Wolpert, Neural Networks 5 (1992); L. Breiman, Machine Learning 24 (1996); Y. Yao, A. Vehtari, D. Simpson & A. Gelman, Bayesian Analysis 13 (2018).
- After selection. D. Cox, Biometrika 62 (1975); Y. Benjamini & D. Yekutieli, JASA 100 (2005); R. Berk, L. Brown, A. Buja, K. Zhang & L. Zhao, Ann. Stat. 41 (2013); J. Lee, D. Sun, Y. Sun & J. Taylor, Ann. Stat. 44 (2016); W. Fithian, D. Sun & J. Taylor (2014); J. Leiner, B. Duan, L. Wasserman & A. Ramdas, JASA (2023).
- Subsets. G. Furnival & R. Wilson, Technometrics 16 (1974); B. Natarajan, SIAM J. Comput. 24 (1995); D. Bertsimas, A. King & R. Mazumder, Ann. Stat. 44 (2016); T. Hastie, R. Tibshirani & R. Tibshirani, Stat. Sci. 35 (2020); N. Meinshausen & P. Bühlmann, JRSS B 72 (2010); F. Harrell, Regression Modeling Strategies (2015).
- Forecasts. F. Diebold, T. Gunther & A. Tay, Int. Econ. Rev. 39 (1998); J. Matheson & R. Winkler, Mgmt. Sci. 22 (1976); T. Gneiting & A. Raftery, JASA 102 (2007); T. Gneiting, F. Balabdaoui & A. Raftery, JRSS B 69 (2007); G. Brier, Monthly Weather Review 78 (1950).
- Books.
- K. Burnham & D. Anderson, Model Selection and Multimodel Inference (2nd ed., 2002).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning (2nd ed., 2009), chapters 3 and 7.
- G. Claeskens & N. Hjort, Model Selection and Model Averaging (2008).
About this partfrom its README
Part 28 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the eighth part of Stage III, Master's. Part 27 introduced computational tools and their limits. This part asks which of them to believe, and how to choose without fooling yourself:
- the optimism of training error, and degrees of freedom for any procedure;
- Cp, AIC, TIC and AICc; BIC, consistency and efficiency; cross-validation and what it estimates;
- Bayesian leave-one-out with Pareto-smoothed importance sampling, WAIC, and singular models;
- minimum description length, model averaging and stacking, inference after selection, subset selection, and calibrated forecasts.
Its instrument is the model-selection bench (CriterionBench), on which each candidate's misfit and penalty are
stacked, and the criterion's choice is the lowest total. Its kit is statkit.select.
It opens with Freedman's paradox (1983): 100 observations, 50 predictors, all independent noise.
- Round 1: R² = 0.455, overall F = 0.82, p = 0.76. Fourteen predictors have p < 0.25; two have p < 0.05.
- Round 2, on the fourteen kept: R² = 0.268, F = 2.23, p = 0.013, and four coefficients significant at 5%.
- Over 1,000 repeats, round 2 is significant at 5% in 94.7% (median 12 kept, 5.6 significant on average).
From there the part covers:
-
Optimism.
-
Thirty points from a smooth curve with noise SD 0.5; polynomials of degree 0–12, 600 data sets. Training error falls to 0.142; error on new responses is about 0.30 from degree 3 to 6 (minimum 0.299 at 5), then rises to 0.355.
-
Efron's covariance formula: optimism = (2/n) Σ Cov(ŷᵢ, yᵢ) = 2σ²d/n for a linear fit (degree 3: 0.067 simulated, 0.067 by formula); the bias–variance anatomy of the gap.
-
Degrees of freedom: tr S for linear smoothers, Stein's divergence, and Monte Carlo for anything. The lasso on the prostate predictors (600 simulated responses per λ):
λ df estimate ± MCSE 1 + E(nonzero) 0.02 8.00 ± 0.16 8.04 0.08 6.48 ± 0.15 6.07 0.2 4.58 ± 0.12 4.61 0.4 2.95 ± 0.11 2.95
-
-
Cp and AIC.
- Mallows's Cp; AIC as an estimate of expected KL, derived by two Taylor expansions (optimism k).
- TIC: tr(ĴK̂⁻¹) for a Poisson regression of the World's doctor visits (mean 2.42, variance 13.7) is 9.47 against k = 2; on Poisson data, 1.81. AICc (Sugiura 1978; Hurvich & Tsai 1989).
- The bench on Stamey's prostate data (67 training men, searched best subset of each size): AIC chooses 7 predictors (all but gleason). ΔAIC: 6 predictors 0.46, 4 1.28, 5 1.74, 8 1.98, 3 3.42, 2 5.49.
-
BIC.
-
Laplace's method derived; the unit-information prior (Kass & Wasserman 1995).
-
On the bench, log 67 = 4.20 per parameter: BIC chooses 2 (lcavol, lweight).
-
AIC as a likelihood-ratio test at level P(χ²₁ > 2) = 0.157.
-
Truth a quadratic, degrees 0–6, 300 data sets per n. P(choose degree 2):
n 20 50 100 200 500 1,000 3,000 AIC 0.41 0.67 0.71 0.73 0.77 0.76 0.72 AICc 0.46 0.74 0.74 0.76 0.77 0.77 0.72 BIC 0.43 0.81 0.96 0.97 0.98 0.997 0.993 -
Truth sin(2x)e^{0.3x}, degrees 0–12, prediction risk of each criterion's choice:
n AIC AICc BIC 50 0.874 0.311 0.071 200 0.0118 0.0114 0.0107 1,000 0.00252 0.00250 0.00297 Consistency against efficiency (Shibata 1981; Yang 2005).
-
-
Cross-validation theory.
- PRESS and GCV for linear smoothers; across 400 regressions they correlate at 0.986.
- Prostate, 10-fold CV with the search redone in each fold: CV error 1.47, 0.70, 0.60, 0.70, 0.66, 0.67, 0.62, 0.57, 0.59 for sizes 0–8. The minimum is at 7, and sizes 2 and 4–8 lie within one SE; the one-SE rule picks 2. PRESS (no search inside) is smoother and lower at sizes 3–5 (0.59, 0.58, 0.59).
- What CV estimates (Bates, Hastie & Tibshirani 2024). In 400 simulated regressions (n = 50, 10 predictors, 4 real), corr(CV, this fit's true error) = −0.06, while mean CV 1.32 matches the mean error 1.30.
- Choosing K (Breiman & Spector 1992; Kohavi 1995).
-
Bayesian LOO and WAIC, predicting a whole held-out school. The hierarchy uses flat mean/scale priors with proper leave-one-out posteriors; independent effects use explicit N(0,100²) priors.
Model PSIS-LOO elpd refit/analytic LOO p_loo WAIC p_WAIC complete pooling -30.60 -30.56 0.70 -30.57 0.68 hierarchical -31.18 -31.34 1.56 -30.96 1.34 independent effects, proper prior -36.46 -44.33 6.42 -33.91 3.87 The exact pooled-minus-hierarchical difference is 0.781, with a rough paired pointwise SE of 0.275 across only eight schools. For independent effects, both PSIS and WAIC are seriously optimistic against the analytic reference; large Pareto tail estimates warn of unstable deletion weights. A flat independent prior would instead make the held-out effect's posterior undefined.
-
Singular models.
- The mixture (1 − a)N(0, 1) + aN(b, 1) at a N(0, 1) truth: the true set is a cross.
- Watanabe's free energy, λ log n − (m − 1) log log n, with λ = ½, m = 2 by hand. By quadrature for n = 30 to 10,000, the free energy grows with slope 0.42 in log n (theory ½ with a log log correction; finite-n Monte Carlo comparison), against 0.99 for a regular two-parameter model (theory 1).
- RLCTs of other models; WBIC and sBIC.
-
MDL.
-
Kraft and Shannon; the two-part code on chapter one's 30 points is shortest at degree 5 (40.9 bits); ½ log₂ n per coefficient is BIC.
-
Shtarkov's NML and its regret for a coin, exactly and by ½ log(nπ/2):
n 10 30 100 300 1,000 3,000 10,000 regret 1.539 2.021 2.581 3.108 3.696 4.239 4.836 ½ log(nπ/2) 1.377 1.926 2.528 3.078 3.680 4.229 4.831 -
Dawid's prequential codes.
-
-
Averaging.
-
BMA (Hoeting et al. 1999), Occam's window, MC³, priors on models (Scott & Berger 2010).
-
M-closed and M-open. The truth is ½N(−2, 1) + ½N(2, 1); the two candidates are N(−2, 1) and N(2, 1), 100 data sets per n:
n 20 50 100 200 500 BMA weight on favourite 0.988 0.992 0.992 0.993 0.999 stacking weight on favourite 0.593 0.561 0.541 0.527 0.519 log density, training-selected single -5.411 -5.419 -5.423 -5.423 -5.412 log density, BMA -5.031 -5.207 -5.074 -5.238 -5.358 log density, stacking -2.087 -2.062 -2.057 -2.052 -2.054 The truth's own score is −2.05.
-
Stacking (Wolpert 1992; Breiman 1996; Yao et al. 2018).
-
Prostate Akaike weights peak at 0.30 (size 7) and spread over sizes 4–8. BIC weights split 0.30 / 0.28 / 0.27 over sizes 2, 3 and 4.
-
-
Inference after selection.
- The winner's curse for β₁ = 0.05 with known SE 0.1. AIC keeps it 21% of the time, when |β̂₁| averages 3.9 times the truth; the conditional coverage of the usual 95% interval is 0.1581/0.2081 = 0.7597 by a normal calculation.
- The Board's simulation (below); splitting (Cox 1975); PoSI, polyhedral inference, data fission (Part 56).
-
Subset selection.
-
Stepwise's sins; leaps and bounds; mixed-integer optimization.
-
The race: n = 100, p = 10, 5 true, correlation 0.35^{|i−j|}, tuned on a validation set. Relative excess risk (above irreducible noise, divided by signal variance), averaged over 25 replicates:
SNR 0.05 0.25 1 6 best subset 1.337 0.496 0.085 0.0107 forward stepwise 1.360 0.467 0.087 0.0107 lasso 1.007 0.404 0.092 0.0182 -
Prostate test error on the 30 held-out men:
Method Predictors Test error null 0 1.057 full least squares 8 0.521 AIC = CV best subset 7 0.517 BIC = CV one-SE 2 0.492 lasso (10-fold CV, fold-specific preprocessing) 7 0.501 ridge (10-fold CV, fold-specific preprocessing) 8 0.502 -
Bootstrap stability, 400 resamples:
- AIC produced 66 distinct models and its original pick 15% of the time;
- BIC produced 62 and its pair 18%;
- lcavol was kept every time.
-
-
Calibrated forecasts.
-
The PIT; four forecasters of a drifting level, 2,000 steps:
Forecaster Log score CRPS 90% interval covers PIT shape calibrated 1.423 0.569 90.1% flat overconfident (SD 0.5) 2.241 0.619 58.0% U underconfident (SD 2) 1.738 0.658 99.95% hump biased (+0.7) 1.687 0.715 80.6% sloped -
Prostate leave-one-out PITs are descriptive, dependent residual-based diagnostics. Mean held-out log densities are −1.631 (intercept), −1.183 (two predictors) and −1.170 (all eight). Descriptive KS distances are 0.060, 0.044 and 0.093; iid KS p-values are omitted because the LOO fits overlap. None of these histograms proves calibration.
-
Proper scoring rules and the CRPS (Matheson & Winkler 1976; Gneiting & Raftery 2007); sharpness subject to calibration.
-
Data:
- Stamey et al.'s prostate data (1989, via The Elements of Statistical Learning) and the eight schools are the Museum's;
- the doctor visits are the World's;
- the rest are seeded simulations.
Built in this part:
statkit.select(explainer/stats/kit/select.py), checked intests/test_stats_kit_select.py:- Criteria: the Gaussian log likelihood from an RSS, AIC, AICc, BIC, Cp, Takeuchi's penalty.
- Leave-one-out: the hat matrix, PRESS, GCV, and Efron's Monte Carlo degrees of freedom.
- Search: Freedman's screening experiment, best subset by enumeration, forward stepwise.
- Bayesian: PSIS-LOO (using
statkit.ppl's Pareto smoothing), WAIC, stacking weights, BMA weights. - MDL: the exact NML regret of a Bernoulli model.
- The Museum gains Stamey's prostate data (97 men, 8 predictors, the 67/30 split) as
museum.prostate(). - The model-selection bench (
CriterionBenchinexplainer/stats/viz.py): misfit and penalty stacked per candidate, with the minimum ringed;bars(penalty_per_k)re-prices the same bench (AIC's 2 or BIC's log n).
The Coverage Board gains three rows. Ten independent candidate predictors, n = 100, β₁ = 0.05 (two others nonzero), forward stepwise selection by AIC, 2,000 data sets:
| Method | Setting | Reps | Achieved | Verdict |
|---|---|---|---|---|
| naive CI after AIC selection | β₁ = 0.05, when x₁ is kept | 430 | 75.1% | broken |
| select on half, CI on the other half | β₁ = 0.05, when x₁ is kept | 441 | 95.7% | kept |
| full model, no selection | β₁ = 0.05 | 2,000 | 95.0% | kept |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Freedman's paradox, 1983 | p 0.76 → 0.013; 94.7% of 1,000 repeats |
| 1 | Optimism | gap 0.067 = 2σ²d/n; lasso df ≈ 1 + nonzeros |
| 2 | Cp and AIC | TIC 9.47 vs k = 2; AIC picks 7 of 8 |
| 3 | BIC | picks 2; P(true degree) 0.99 vs AIC's 0.75; P(χ²₁ > 2) = 0.157 |
| 4 | Cross-validation theory | one-SE picks 2; corr(CV, true error) −0.06 |
| 5 | Bayesian LOO and WAIC | refit/analytic −30.56 / −31.34 / −44.33; check PSIS tail warnings |
| 6 | Singular models | slopes 0.42 vs 0.99 (theory ½ vs 1) |
| 7 | Minimum description length | degree 5 at 40.9 bits; regret ≈ ½ log(nπ/2) |
| 8 | Averaging | BMA 0.99 on one model; stacking −2.06 vs truth −2.05 |
| 9 | Inference after selection | 76% by the coherent known-SE calculation; Board 75.1% vs 95.7% split |
| 10 | Subset selection | lasso wins at SNR 0.05, best subset at 6; 66 bootstrap models |
| 11 | Calibrated forecasts | coverage 58% / 90% / 99.95%; LOO log score −1.63 vs −1.18 |
| 12 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Freedman's paradox (1983).
- Optimism. 2σ²·df/n (Efron 1986); degrees of freedom via Stein's lemma (Efron 2004).
- Cp and AIC (Mallows 1973; Akaike 1973). AIC as expected KL, derived; TIC; AICc.
- BIC (Schwarz 1978). The Laplace approximation, derived; consistency vs efficiency (Yang 2005).
- Cross-validation theory. LOO and GCV for linear smoothers; what CV estimates (Bates, Hastie & Tibshirani 2024).
- Bayesian LOO. PSIS-LOO and Pareto-k̂; WAIC (Watanabe 2010).
- Singular models. Watanabe's RLCT replacing d/2 (computed on a mixture).
- MDL (Rissanen 1978).
- Averaging. BMA (Hoeting et al. 1999) vs stacking (Yao et al. 2018).
- Inference after selection, first look. The naive CI after AIC (Board); splitting (Part 56).
- Subset selection. Stepwise's sins; best subset by MIO vs the lasso (Hastie, Tibshirani & Tibshirani 2020).
- Calibrated forecasts. PIT; log score and CRPS; Dawid (1984).
- Outro.
Built: the model-selection bench; statkit.select.
Build the film
python -m videos.stats.stats28.compute # the part's numbers, into .cache/stats28
python tools/build.py stats28 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats28 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats28. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats28.compute # once (several minutes)
python tools/build.py stats28 -q l # fast 480p preview
python tools/build.py stats28 # 1080p30 -> renders/stats28.mp4
python tools/qa_scene.py stats28 Singular
python tools/lecture_length.py stats28 --floor 50