SStatistics, Built

Stage III · Master's

Part 34 of 65

Prediction with Guarantees

Master'sstarts at this level84 min of film13 chaptersprerequisites: Part 16, Part 19, Part 33

Can any prediction, from any model, come with an honest guarantee?

In 2001 Breiman tells statisticians that algorithms have won prediction, and Cox and Efron reply that prediction is not all of science. The part treats the algorithms as estimators. Fifty bootstrap trees on the breast cancer data predict equally well and tell different stories; a forest's variance is rho sigma squared plus what averaging removes; boosting is stagewise additive modelling; cross-validation estimates the average error over training sets and not the error of the model in hand; a predicted probability needs calibrating. The part turns at split conformal prediction: sort the calibration scores on the score ladder, take the rank ceil((n+1)(1-alpha)), and the interval covers a new exchangeable case with probability at least 1-alpha, whatever the model. Jackknife+, conformalized quantile regression, weighted and adaptive conformal, and classification sets extend the guarantee and mark where it stops: it is marginal, and it needs exchangeability. Prediction-powered inference then turns 20,000 biased smartwatch guesses and 300 clinic visits into a valid interval for the World's mean blood pressure. It ends with a pneumonia model that predicts well and would advise badly.

What you need. Trees, cross-validation and the bias-variance trade-off from Part 19; the bootstrap of Part 16.

Hook
Breiman's two cultures, 2001
Mathematics
forests and boosting as estimators, what CV estimates, calibration, split and jackknife+ conformal, PPI
Built
statkit.conformal

What you will be able to do

Bachelor's

  • Compute a split conformal interval from a list of calibration residuals, and say exactly what its 90% promises and what it does not.
  • Explain why several different models can predict equally well and still disagree about which variables matter.

Master's

  • Derive the variance of an average of B correlated trees and the quantile lemma behind split conformal coverage.
  • Implement jackknife+, CQR and weighted conformal, and adaptive conformal on a stream.
  • Compute a prediction-powered mean with its interval and the tuned PPI++ weight.

PhD

  • Prove that coverage given the calibration set is Beta(k, n+1-k) for i.i.d. continuous scores, and state why exchangeability alone does not give that law.
  • State the impossibility of distribution-free conditional coverage and the 1-2 alpha bound for jackknife+.

Practice

  • Check a classifier's reliability diagram and recalibrate it by Platt, isotonic or temperature scaling on held-out data.
  • Say what a permutation importance, a partial dependence curve, LOCO and a Shapley value each estimate before reporting one.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 23 min · Master's 78 min · PhD 84 min · Practice 35 min.

  1. 0The two culturesBachelor's5 min
  2. 1Explain or predict?Bachelor's6 min
  3. 2ForestsMaster's10 min
  4. 3BoostingMaster's7 min
  5. 4What cross-validation estimatesMaster's6 min
  6. 5CalibrationPractice5 min
  7. 6Split conformalBachelor's7 min
  8. 7Jackknife+ and CQRMaster's8 min
  9. 8Under shiftPhD6 min
  10. 9Classification setsMaster's6 min
  11. 10Prediction-powered inferenceMaster's7 min
  12. 11Interpretation as estimationPractice7 min
  13. Recap, problems, and the road aheadAll tracks5 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.

The two culturesBachelor's5 min

In 2001 Leo Breiman published a paper in Statistical Science called Statistical Modeling: The Two Cultures. Breiman was a probabilist who had left a professorship to work as a consultant for thirteen years, predicting next-day ozone levels for Los Angeles and identifying chemical compounds from their mass spectra. When he came back to Berkeley he found his colleagues doing something he no longer recognised as useful. There are two cultures, he wrote. In one, which he estimated held ninety-eight percent of statisticians, you assume the data come from a stochastic model and estimate its parameters. In the other, two percent, you treat the mechanism as unknown and find an algorithm that predicts well. His verdict was blunt: the commitment to data models had led to irrelevant theory and questionable conclusions, and kept statisticians away from the most interesting problems of the day.

His picture was a box. Nature takes inputs x, does something inside the box, and produces responses y. The data modeller fills the box with a model: a linear regression, a logistic regression, a proportional hazards model, with parameters to estimate and test. The model is judged by goodness of fit tests and residual plots, which, Breiman argued, rarely reject anything. The algorithmic modeller leaves the box closed. Find any function f of x that predicts y well: a decision tree, a neural network, a forest. Judge it by one standard only: its accuracy on data it has not seen.

He named three lessons. The Rashomon effect, after Kurosawa's film in which four witnesses tell four different stories of one crime: many quite different models fit the data equally well, so which one tells the truth? Occam's dilemma: the most accurate predictors, forests and ensembles, are the least interpretable, and simplicity may cost accuracy in some problems; this is an empirical tradeoff, not a universal law. And Bellman's dimensionality: for prediction, more features are often a blessing, not the curse that classical theory fears. His examples were medical: on a hepatitis survival data set and others, random forests, which he had just invented, beat logistic regression.

The journal printed replies. David Cox agreed that prediction mattered, but said it was rarely the only aim. Much of statistics is about understanding a process, about deciding which data to collect, and about questions where the future will not resemble the past, so that a model of the mechanism is the only thing that transfers. Bradley Efron opened with a sentence that is still quoted. At first glance, he wrote, Breiman's stimulating paper looks like an argument against parsimony and scientific insight, and in favor of black boxes with lots of knobs to twiddle. At second glance it still looks that way. Breiman's rejoinder was more conciliatory than his paper: the best solution to a data problem might be a data model, and it might be an algorithm. Use whatever works, and check it.

In the twenty-five years since, prediction contests went Breiman's way. The Netflix Prize in 2009 was won by a large blend of models. In 2012 a deep convolutional network won the ImageNet image-recognition competition by a wide margin, and machine learning took over vision, speech and language. On ordinary tables of data, gradient boosted trees are still the ones to beat, as Grinsztajn, Oyallon and Varoquaux found in 2022. So the algorithms won prediction. But that left statistics with a new question, and it is the question of this part.

Here is a problem of Breiman's kind. In the early 1990s William Wolberg, Nick Street and Olvi Mangasarian digitized the cells of five hundred and sixty-nine breast biopsies at the University of Wisconsin, and measured thirty features of the nuclei: their radius, texture, concavity and so on. A random forest trained on four hundred of them classifies the other hundred and sixty-nine with ninety-four percent accuracy. For a new patient it says: malignant, probability point eight three. A statistician asks: is point eight three honest? How wrong could the forest be about this patient? And what, exactly, is the forest estimating?

Numbers: 98% vs 2%; a forest at 94.1%

1Explain or predict?Bachelor's6 min

Galit Shmueli made the distinction precise in 2010, in a paper called To Explain or to Predict? Explanatory modelling starts from a causal theory, translates it into a statistical model, and wants the right model with unbiased coefficients, so that each coefficient means what the theory says. It is judged by fit, by tests, and by whether it agrees with theory. Predictive modelling wants any function that maps new inputs to accurate outputs. It is judged only by its error on data it has not seen. Shmueli's point was that these are different goals, which can call for different models fitted to the same data, and that a field which only does one of them is missing half its science.

The difference shows in the expected prediction error at a point x nought. It splits, as in Part 19, into the noise sigma squared, the squared bias of the fitted function, and its variance. Explanation cares about the bias: a coefficient that is wrong on average answers the scientific question wrongly, however small its variance. Prediction cares about the sum, and will happily accept some bias to buy a larger fall in variance.

A small example makes it concrete. Suppose the truth has two predictors, and the second has a small coefficient. The correct model is unbiased and, with independent standardized predictors, has expected prediction error about sigma squared times one plus two over n. The wrong model, which drops x two, has one fewer coefficient to estimate but carries the bias beta two squared times the variance of x two. So the wrong model predicts better whenever that bias is smaller than sigma squared over n: when the effect is smaller than the noise can resolve. The model that explains correctly is not always the one that predicts best.

Breiman's Rashomon effect is easy to see on the breast cancer data. Take fifty bootstrap samples of the four hundred training biopsies, and grow a tree three levels deep on each. On the hundred and sixty-nine held-out cases they are all about as good: ninety-three percent correct, give or take two. But the first split, the one a doctor would read as the most important feature, changes from tree to tree: the worst radius, the worst perimeter, the worst area, the mean concave points.

Over all fifty trees, five different features appear at the root. The worst concave points wins twenty-one times, the mean concave points eleven, the worst perimeter ten. And if we list each tree's three most important features, we get thirty-nine different lists from fifty trees. The reason is no mystery. The radius, perimeter and area of a nucleus are essentially the same measurement, correlated between point nine four and point nine nine eight, and the concavity features move together too. The data cannot say which of them matters, because any of them predicts as well as any other. A tree picks one, almost by chance.

The same happens with a data model. Here are three logistic regressions, each on two standardized features, with no feature in common. The first uses the mean concave points and the worst perimeter; the second, the worst concave points and worst radius; the third, the worst area and worst texture. Their accuracies are ninety-five, ninety-five and ninety-three percent. Each would make a respectable paper: two predictive associations with malignancy. We have not calculated significance tests for these displayed coefficients. None of them is the mechanism. They are three witnesses to one crime, each telling the story from where it stood.

Cynthia Rudin and her colleagues turned the effect into an object. The Rashomon set is every model in a class whose loss is within epsilon of the best. For one model, the reliance on feature j is how much its loss grows when that feature is scrambled. Instead of reporting one model's reliance, Aaron Fisher, Rudin and Francesca Dominici proposed reporting its range over the whole Rashomon set: the least and the most any good model needs the feature. A feature that every good model needs is important; one that some good models ignore is not indispensable within that model class, although it may remain useful. And when the Rashomon set is large, it may contain a simple, interpretable model with comparable predictive accuracy; this is not guaranteed by its size alone, which is Rudin's argument for using one in high-stakes decisions.

So the first lesson: a good predictor is not an explanation. When many models predict equally well, the data simply do not choose between their stories. But Breiman's culture is not outside statistics. A predictor is an estimator of something; its error is a random variable; and we can ask for guarantees about it. We start with the forest itself.

Numbers: 5 root features, 39 top-three lists

2ForestsMaster's10 min

A decision tree grown deep, as in Part 19, has little bias, since it can follow almost any shape, and enormous variance: change a few training cases and the tree changes completely. In 1996 Breiman proposed bootstrap aggregation, bagging: grow a tree on each of B bootstrap samples and average their predictions. In 2001 he added one more twist, building on ideas of Tin Kam Ho and of Yali Amit and Donald Geman: at every split, let each tree consider only a random subset of m try features. That is a random forest. His defaults, the square root of p for classification and a third of p for regression, are historical recommendations; software defaults and useful tuning choices vary. Why would deliberately hobbling each tree make the average better?

Here is the reason. Over the randomness of the training set and of the trees themselves, each tree's prediction at x has some variance sigma squared, and two trees of the same forest have some correlation rho, since they were grown on overlapping samples of the same data. The variance of their average has B variance terms and B times B minus one covariances. It simplifies to rho sigma squared, plus one minus rho over B times sigma squared. The second term vanishes as the forest grows. The first does not: however many trees you average, the variance never falls below rho sigma squared. Bagging can only shrink the second term. Restricting the features at each split shrinks rho, at the price of making each tree a little worse.

We can measure both quantities. Jerome Friedman's 1991 test function has ten inputs, five of which matter, through a sine of a product, a square, and two straight lines. Forty training sets of three hundred points, a forest of forty trees on each, and the predictions at two hundred test points give sigma squared and rho directly. For bagging, with all ten features at every split, two trees are correlated at . With three features per split, rho falls to , and with a single random feature per split, to . Each curve falls with B towards its own dashed floor, rho sigma squared, and after a hundred trees the remaining Monte Carlo term depends on rho and the tree count; adding trees can still help.

The whole trade in one table. As m try falls from ten to one, a single tree gets noisier, sigma squared rises, and the bias of the forest rises, because a tree that must sometimes split on an irrelevant feature wastes its depth. But rho falls much faster, so the forest's variance falls. The mean squared error is smallest at m try equals here. Nothing magical: the forest is an estimator of the regression function, and its error is a bias plus a variance, like every estimator in this series. m try is the knob that trades one for the other.

Back to the biopsies, with two columns of pure noise added to the thirty features, for later. One deep tree misclassifies seven percent of the hundred and sixty-nine test cases. Bagging three hundred trees brings that down to six percent, and the forest, with six features per split, also to six. The curves wander a little with B, mostly because each test case is six tenths of a percent. On a problem this easy every reasonable method is close; on harder ones, like Friedman's, the forest's advantage over bagging is larger.

Bagging comes with its own test set. A given case is left out of a bootstrap sample with probability one minus one over n, to the n, which tends to one over e, about thirty-seven percent. So each training case has about a third of the trees that never saw it, and their average is an honest, out-of-bag prediction for it. The out-of-bag error on the four hundred training cases is three and a half percent, against six on the separate test set: the same order, as two noisy estimates of one error rate should be. It costs nothing: a cross-validation that comes free with the forest.

Is the forest a consistent estimator of the regression function? For Breiman's own algorithm, with its bootstrap, its data-dependent splits and its fully grown trees, the question resisted proof for years. Gérard Biau, Luc Devroye and Gábor Lugosi proved consistency in 2008 for simplified forests whose splits ignore the responses, and Biau extended it in 2012. In 2015 Erwan Scornet, Biau and Jean-Philippe Vert proved that Breiman's forests, with subsampling instead of the bootstrap, are consistent when the regression function is additive. And Stefan Wager and Susan Athey showed in 2018 that forests of honest trees, which use one half of each subsample to choose the splits and the other half to fill the leaves, are asymptotically normal. That opens the door to confidence intervals.

Forests also report which features matter, in two ways. Breiman's impurity importance adds up, for each feature, how much its splits reduced the training error, across all the trees. His permutation importance instead scrambles one feature in held-out data and measures how much the error grows. For the real features they broadly agree. Now look at the two noise columns we added, one continuous and one a coin flip. Neither carries any information. Impurity importance credits the continuous one with times the coin's importance, because a feature with many distinct values offers many more chances to find a split that happens to fit the training data. Carolin Strobl and her colleagues documented this bias in 2007. Permutation importance, measured on data the trees did not see, gives both noise columns essentially zero.

How uncertain is a forest's prediction? Record, while growing the forest, how many times each training case appears in each tree's bootstrap sample. Efron's infinitesimal jackknife asks how the prediction would move if case i got a little more weight; for a bagged estimator that derivative is the covariance, across trees, between case i's count and the tree's prediction. Summing the squares over cases estimates the variance. With finitely many trees this is biased upwards by Monte Carlo noise, and Stefan Wager, Trevor Hastie and Efron subtract a correction. Then an interval is the prediction plus or minus one point six four five standard errors, for ninety percent. One forest, no refitting.

Try it at a point x nought near a peak of Friedman's surface. Three hundred training sets of two hundred and fifty points, a forest of five hundred trees on each, and an infinitesimal jackknife interval from each forest. Here are the first twenty. The true value of the regression function there is . The forests, averaged over training sets, reach an independently estimated pilot mean of : averaging over leaves pulls peaks down and valleys up. The independent pilot has Monte Carlo uncertainty, shown on screen; the reported coverage conditions on this estimated reference, rather than knowing the exact expectation. Worse, the intervals do not even cover the forests' own average at the promised rate: only percent. Their standard errors average , but the forests' predictions really vary with a standard deviation of . The infinitesimal jackknife captures only the linear part of an estimator's variability, and a deep tree grown on a bootstrap sample of the whole data set does not ensure an accurate linear approximation at this sample size.

Wager and Athey's remedy is to grow each tree on a small subsample drawn without replacement, here fifty of the two hundred and fifty points. Subsampling alone does not establish the honest-forest asymptotic theorem. Then each tree depends on any one case only rarely, the forest becomes nearly linear in the data, like a U-statistic, and the infinitesimal jackknife, with the subsampling correction, captures most of its variance. With two thousand trees per forest, the intervals now cover the forests' own average percent of the time: far better, though still short of ninety, because the standard errors remain about a tenth too small on average, and are themselves noisy. But trees on fifty points are coarser, so the forests are more biased, averaging against the true , and the intervals almost never cover the truth. A closer variance approximation still leaves a biased centre: the infinitesimal jackknife measures variance, not bias. Wager and Athey's asymptotic theory makes the bias negligible under conditions on honest tree construction, regularity and the subsampling rate. These ordinary CART trees are not an implementation of their honest forest theorem.

Numbers: ρ 0.128 → 0.024; IJ covers 60% / 84%

3BoostingMaster's7 min

Boosting came from computer science. In 1988 Michael Kearns and Leslie Valiant asked whether learners that are only slightly better than guessing could be combined into one that is arbitrarily accurate. Robert Schapire proved in 1990 that they could, and in 1997 Yoav Freund and Schapire published the algorithm that made it practical, AdaBoost. Fit a simple classifier, often a single split; increase the weights of the cases it got wrong; fit another; and so on, finally letting the classifiers vote with weights depending on their accuracy. It worked so well, and overfitted so little, that Breiman called it the best off-the-shelf classifier in the world. Nobody quite knew why it worked.

The explanation came from statisticians. In 2000 Jerome Friedman, Trevor Hastie and Robert Tibshirani showed that boosting fits an additive model, a sum of simple basis functions such as small trees. It fits it greedily, one term at a time: at stage m, choose the new term to minimize the loss of the current model plus that term, leaving all earlier terms alone. With the exponential loss, e to the minus y F, for labels plus or minus one, this forward stagewise procedure is exactly AdaBoost: the case weights are the exponential losses of the current model. Because earlier terms are never refitted, this is stagewise rather than stepwise, and that turns out to matter.

Friedman then made it general, in his 2001 paper on gradient boosting. For any differentiable loss, compute the negative gradient of the loss at each training point, with respect to the current fitted value. For squared error that gradient is just the residual. Fit a small tree to these pseudo-residuals, and add it to the model, scaled by a learning rate nu. Boosting is steepest descent, not in a space of parameters, but in a space of functions, taking small steps each in the direction of a tree.

Here it is in one dimension, with stumps, trees of a single split, and a learning rate of point three. The first stage puts one step into the constant fit, three tenths of the way towards the best split. Each further stage fits a stump to whatever is left over, and adds three tenths of it. After twelve stages the sum of twelve shrunken stumps is a staircase climbing towards the curve. No single term is a good model; their sum is.

The learning rate turns out to matter a great deal. With nu equal to one, each tree takes its full step towards the residuals. With nu a tenth, each tree takes a tenth of a step, and many more trees are needed. Friedman found, and practitioners have confirmed ever since, that smaller steps often improve generalization when the number of stages is tuned appropriately; there is no universal ranking. The number of trees is then the main regularization: boosting keeps lowering the training error, and is stopped when the error on validation data stops falling.

On Friedman's function, with four hundred training points and trees of depth two, measured on three thousand test points. With nu equal to one, the test error falls fast, bottoms out at after trees, and then climbs, while the faint training error keeps falling: overfitting. With nu a tenth the error falls slowly but much further, to after six hundred trees, and is still creeping down. For comparison, a random forest reaches , and the population Bayes risk cannot fall below the noise variance of one. These curve minima are test-set oracle diagnostics, not independently validated tuning results. On this smooth additive surface, slow boosting beats the forest by a wide margin.

Friedman, Hastie and Tibshirani's view also said what AdaBoost estimates. Ask which function minimizes the expected exponential loss at each x. Setting the derivative to zero gives half the log odds of the class probabilities. So AdaBoost, invented with no probability model in sight, is estimating half the logit, the same estimand as logistic regression. That suggested a better loss: the binomial deviance, which gives the same minimizer but grows linearly rather than exponentially for badly misclassified points, and so is less thrown by mislabelled cases. They called it LogitBoost.

Why should small steps help? A clue came from Part 32. Forward stagewise regression on the coefficients of a linear model, with infinitesimal steps, can follow the lasso path under additional design and coefficient-path conditions; the paths differ in general. Efron, Hastie, Johnstone and Tibshirani made that precise in their 2004 paper on least angle regression. Boosting with a small learning rate is forward stagewise regression on a dictionary of all possible trees, so it behaves like an L one penalized fit in that enormous space, with the number of trees playing the role of the penalty. Saharon Rosset, Ji Zhu and Hastie showed that for classification its limit maximizes a margin, which goes a long way to explaining why it overfits so slowly.

Today's boosting libraries, XGBoost from Tianqi Chen and Carlos Guestrin in 2016, then LightGBM and CatBoost, add second-order steps using the Hessian of the loss, penalties on the leaf values, and very fast split-finding. They also fit each stage to a random subsample of the data, Friedman's stochastic gradient boosting of 2002, which helps in the same way that bagging does. Seen as statistics, a boosted model is an estimator like any other, with a bias, a variance, and a tuning parameter, the number of trees, chosen by validation. Which brings us to a question that sounds simple: when we validate, what error are we estimating?

Numbers: ν = 0.1: 2.64 vs ν = 1: 6.63

4What cross-validation estimatesMaster's6 min

There are two different errors we might want. The first is the error of the model we actually fitted, on these training data, when it meets new cases: Err X Y, a conditional error. The second is the average of that over all the training sets of the same size we might have drawn: Err, the error of the procedure. Cross-validation, from Part 19, holds out each fold in turn, fits on the rest, and averages the held-out losses. We almost always report it as if it estimated the first: our model's error rate is so much. Does it?

Stephen Bates, Trevor Hastie and Robert Tibshirani studied the question in 2024, and their cleanest example is ordinary least squares. A hundred observations, twenty standard normal predictors, noise of variance one. For a fitted coefficient vector, the error on a new case is exactly one plus the squared distance from beta hat to beta, so for each simulated data set we know its conditional error exactly. Its average over data sets is one plus p over n minus p minus one, about one point two five, from the inverse Wishart mean. On each of a thousand data sets, compute ten-fold cross-validation and the exact conditional error, and compare.

Here are three hundred of the thousand data sets: the exact conditional error across, the cross-validation estimate up. If cross-validation estimated the error of the model in hand, the points would lie along the diagonal. They form a shapeless cloud. The correlation between the estimate and the quantity we think it estimates is : very little linear association in this experiment. The conditional error itself varies little from data set to data set, with a standard deviation of point oh nine; the estimate varies more than twice as much. Its average, one point two nine, is close to the average error, one point two five, slightly high because each fold trains on only ninety points. Bates, Hastie and Tibshirani's conclusion: cross-validation estimates Err, the error of the procedure averaged over training sets, and may be weakly informative about the error of the particular model we fitted.

Why should this be? Both quantities depend on the same training data, but on different features of it. A data set with small, well-behaved noise makes the held-out errors small, so cross-validation looks good. But beta hat is no closer to beta for that, so the model's real error is no smaller. The two are nearly independent. This is not special to cross-validation: Hastie, Tibshirani and Friedman's book had already shown that the bootstrap, A I C and Mallows' C p behave the same way. Estimating the error of the model in hand, rather than of the procedure, is simply very hard.

The usual standard error for a cross-validation estimate treats the n held-out losses as if they were independent: their standard deviation over root n. Plus or minus one point six four five of those gives a nominal ninety percent interval. Even for its proper target, the average error, it covers only percent of the time. The real standard deviation of the estimate is times the naive standard error, because training-size bias and dependence both matter. The held-out losses are correlated: every fold's model was trained on mostly the same points. Bates, Hastie and Tibshirani propose estimating the correction with a nested cross-validation.

Nested cross-validation has a second, older use. If cross-validation chooses a tuning parameter, such as a forest's m try or boosting's number of trees, then the minimum of the cross-validation curve is a biased, optimistic estimate of the chosen model's error: we picked the value that happened to look best. So split twice. The outer folds are held out only to assess. Within each outer training set, an inner cross-validation does all the tuning. Sudhir Varma and Richard Simon showed in 2006 how large the optimism from tuning on the assessment folds can be, following Christophe Ambroise and Geoffrey McLachlan's demonstration of 2002 that selecting genes outside the cross-validation loop can make random labels look predictable.

The arithmetic of that optimism is Part 33's again. Choosing the tuning parameter that minimizes the cross-validation curve, the expected value of the minimum is at most the minimum of the expected values, because the minimum of noisy curves lands, on average, below every one of them. More competing noisy choices can increase this optimism; the amount depends on their joint errors: the winner's curse of a selected estimate. The remedy is to assess the whole procedure, tuning included, on data that the choice never saw.

Cross-validation targets average performance at the fold training size, and need not closely track the conditional error of the full-data fit. The naive independent-loss standard error undercovers in this example; cross-validation uncertainty depends on the learning problem. And any choice it makes must be assessed outside it. Next, a different kind of honesty: when a model says seventy percent, does it mean seventy percent?

Numbers: corr 0.013; naive CI 82.8%

5CalibrationPractice5 min

A probability forecaster is calibrated if, among all the cases where it says p, the event happens a fraction p of the time. Weather forecasters were the first to check: among the days the forecast said seventy percent chance of rain, did it rain on seventy percent? The check is a reliability diagram. Group the predictions into bins, and plot each bin's observed frequency against its average prediction. Calibration puts the points on the diagonal. The expected calibration error averages the vertical gaps, weighted by how many cases fall in each bin. Calibration is not accuracy. A classifier can rank cases perfectly and still say ninety nine percent when it should say sixty.

Here is a famously overconfident classifier on the biopsies: Gaussian naive Bayes, which models each of the thirty features as normal within each class and independent of the others. Forty random splits into training, calibration and test sets; the test predictions are pooled. Ninety-eight percent of its predictions are below a tenth or above nine tenths: it is almost always certain. In between, where it says sixty, seventy, eighty percent, the cancers turn out to be malignant less than half the time. Its accuracy is a respectable ninety-four percent; its calibration is poor.

The reason is in its formula. Naive Bayes adds up the log likelihood ratios of the thirty features, as independent pieces of evidence. But the radius, perimeter and area of a nucleus are one fact measured three ways, and similar families run through the data, so the same evidence is counted many times. The log odds come out many times too large. The ordering of the cases, which determines ranking measures such as A U C, is much less damaged. This is the typical failure: right direction, wrong confidence.

Calibration can be repaired after the fact, on a separate calibration set that the model was not trained on. John Platt's method of 1999, invented to turn support vector machine scores into probabilities, is a logistic regression of the label on the model's score. Isotonic calibration, from Bianca Zadrozny and Charles Elkan, fits the best monotone step function of the score by Part 21's pool-adjacent-violators algorithm, assuming monotonicity but no parametric shape. Equal scores must be pooled before fitting. And temperature scaling, which Chuan Guo and his colleagues showed in 2017 fixes most of the overconfidence of modern neural networks, divides the log odds by a single number T. On the biopsies, the fitted temperature is about eight: naive Bayes's log odds were about eight times too large, roughly as many times as the evidence was over-counted.

After isotonic calibration, naive Bayes's points move towards the diagonal, and its expected calibration error falls from point oh six two to point oh three eight. A random forest's probability, the share of trees voting malignant, fails the other way. Averaging many trees pulls predictions in from zero and one, because some trees always disagree, so a forest says eighty percent for cases that are malignant nearly always: it is underconfident at the extremes, as Alexandru Niculescu-Mizil and Rich Caruana found for bagged trees in 2005. Isotonic calibration improves the reliability diagram here; finite-data recalibration is not guaranteed to improve every score.

All the numbers, averaged over forty splits. Platt and temperature scaling cut naive Bayes's calibration error by a sixth to a fifth, isotonic by two fifths; the forest's falls by a third. The accuracies barely move, since recalibration relabels the probability scale without changing the order of the cases much. The Brier score, the mean squared error of the probabilities, is a proper scoring rule from Part 24: it rewards both ranking and calibration. It improves by a quarter for naive Bayes; the forest's, already good, stays where it was.

Calibration is a promise about averages: of all the patients told point eight, eighty percent have cancer. It says nothing about whether this patient's point eight is right, and a model can be perfectly calibrated overall while badly wrong for every patient in some subgroup. Demanding calibration within many overlapping groups at once is multicalibration, proposed in 2018 by Úrsula Hébert-Johnson and her colleagues, and we will meet it again in Part 63 on fairness. Next, a marginal guarantee for a new exchangeable case. It does not promise conditional coverage for each individual.

Numbers: ECE 0.062 → 0.038; T̂ = 7.9

6Split conformalBachelor's7 min

Conformal prediction was developed by Vladimir Vovk, Alex Gammerman and Glenn Shafer, and set out in their 2005 book, Algorithmic Learning in a Random World. Vovk had been a student of Kolmogorov, and the idea grew out of algorithmic randomness: to predict a new case, ask how strange each possible answer would make it look among the cases already seen. The computationally cheap version, which splits the data once, came from Harris Papadopoulos and colleagues in 2002. It reached mainstream statistics through Jing Lei, Max G'Sell, Alessandro Rinaldo, Ryan Tibshirani and Larry Wasserman in 2018, and is now everywhere. Its guarantee rests on one simple fact about ranks.

Suppose the n calibration cases and the new case are exchangeable: their joint distribution does not change if we shuffle them. Independent and identically distributed cases are exchangeable, but so are many dependent ones. Apply any fixed score function to each case, say how far its response is from a model's prediction. The scores are exchangeable too. With no ties, symmetry makes its rank uniform. Ties require randomization for equality; the unrandomized coverage lower bound still holds. No parametric distribution or large-sample approximation, but exchangeability is essential. It is Part 16's permutation argument, pointed at the future.

This part's instrument is a score ladder. Here are nineteen calibration scores, sorted from smallest to largest. We want ninety percent coverage, so alpha is a tenth, and we take k as the ceiling of twenty times point nine: eighteen. The threshold q is the eighteenth smallest score. Across fresh continuous calibration sets and a new score jointly, each of the twenty ranks is equally likely. The gaps in this particular displayed, rounded ladder are not conditionally equally likely. In eighteen of the twenty it lands at or below the threshold. So the chance that a new score is at most q is exactly eighteen in twenty: ninety percent.

Check it by simulation: four thousand fresh sets of twenty scores, recording where the twentieth falls among the other nineteen. Every rank comes up about one time in twenty: the histogram is flat. Over twenty thousand repetitions, the new score falls at or below the eighteenth smallest percent of the time, where the exact answer is eighteen twentieths, ninety percent. The scores here were absolute values of normals, but nothing depended on that.

In general: with n calibration scores, take k as the ceiling of n plus one times one minus alpha, and the threshold q hat as the k-th smallest score. The new score is at most q hat exactly when its rank among the n plus one is at most k, which has probability k over n plus one. Since k over n plus one rounds one minus alpha up by less than one over n plus one, the coverage is at least one minus alpha, and, with no ties, at most one minus alpha plus one over n plus one. This is the quantile lemma. If k exceeds n, there are too few scores for the requested level, and the honest threshold is infinite.

Split conformal prediction turns this into intervals for any model. Train the model, any model at all, on one part of the data. On the other part, the calibration set, score each case by its absolute residual. Conditional on the fitted score function, the calibration and new cases must be exchangeable. Keeping model fitting separate is necessary but does not alone establish this assumption. The prediction interval is the model's prediction plus or minus q hat. The new response falls inside with probability at least one minus alpha. Finite sample, any distribution, any model, however wrong. A bad model gives wide intervals, not dishonest ones.

One subtlety. The ninety percent is an average over calibration sets as well as over the new case. Given one particular calibration set, the coverage is a random number, the score distribution function evaluated at q hat, and, for independent identically distributed continuous scores given the fitted model, it follows a beta distribution with parameters k and n plus one minus k. With nineteen calibration cases, the coverage you actually get lies between and in ninety percent of calibration sets. With ninety-nine, between and . With nine hundred and ninety-nine, within about one and a half points of ninety. This quantifies variation over calibration sets; it is not input-conditional coverage for your interval.

A real-sized test, on the World. Predict an adult's income from their age. The model is a cubic in age with a step at the retirement age, fitted by least squares to a thousand adults. On another thousand, the calibration set, the absolute residuals give q hat of about forty-four thousand dollars, so the band is the fitted curve plus or minus that. On twenty thousand new adults, percent fall inside. Exactly as promised, from a model that is certainly wrong: incomes are skewed, with a Pareto tail, and their spread changes with age.

But look at the coverage within age groups. For the young, whose incomes vary least, the band covers percent: it is wider than they need. For those aged fifty-five to sixty-six, at the peak of their careers and the widest spread, it covers only . The guarantee is marginal: ninety percent on average over everyone, which is not ninety percent for each kind of person. A band of constant width cannot be right everywhere when the spread is not constant.

Could we have coverage at every x, conditional on the inputs, without assumptions? No. Vovk in 2012, Lei and Wasserman in 2014, and Rina Foygel Barber and colleagues in 2021 proved versions of the same impossibility: any procedure with distribution-free conditional coverage cannot have finite expected interval length at non-atomic input values over an unrestricted response class. What survives is coverage within a few groups fixed in advance, which chapter nine will build. Or we can change the score so that the band breathes with the data, which is the next chapter. Part 57 returns to the impossibility theorems and proves them.

Numbers: 90.4%; 95.8% vs 83.4% by age

7Jackknife+ and CQRMaster's8 min

The jackknife plus, and conformalized quantile regression. Split conformal has a cost: the model is trained on only part of the data, and the calibration cases are used for nothing else. With small data sets that hurts. Full conformal prediction, Vovk's original, uses every case. For each candidate value y of the new response, add the new case with that y to the data, refit, and keep y if the new case's score does not stand out among all n plus one. It is exact, but needs a refit for every candidate value at every new point, which is affordable only for special models such as ridge regression. The natural compromise is to leave one case out at a time.

The crudest interval uses the residuals of the fitted model on its own training data. Those are too small, since the model was fitted to make them small. The jackknife uses leave-one-out residuals instead: refit without case i, and see how far off it is for case i. Then it centres the interval on the full model's prediction. The trouble is that mixture. The leave-one-out residuals describe models fitted without one case; the centre is the model fitted with all of them. When the fit is unstable, these can be very different. Rina Foygel Barber, Emmanuel Candès, Aaditya Ramdas and Ryan Tibshirani showed in 2021 that the jackknife has no coverage guarantee at all: for some fitting methods its coverage can be driven to zero.

Their fix, the jackknife plus, is small and decisive: use the leave-one-out models for the centre too. For each i, the model without case i makes a prediction at the new x, and we shift it down by case i's own residual. The lower end is a low quantile of these n numbers. The upper end is a high quantile of the predictions shifted up. They proved that this interval covers with probability at least one minus two alpha, for any distribution and any fitting algorithm that treats the cases symmetrically, however unstable. The factor of two is the price of the worst case; in practice, stability conditions can yield stronger approximate bounds with finite-sample slack. At alpha point one the general jackknife-plus guarantee is eighty percent, not ninety.

Barber and colleagues' own experiment, repeated. A hundred training points, p Gaussian predictors, and least squares, taking the minimum-norm solution once p exceeds n, where the fit interpolates the data. Sixty data sets at each p. The in-sample method collapses as p grows: at p equal to n the fit passes through every training point, the residuals are all zero, and the interval has no width. The jackknife holds up for small p but fails near the interpolation threshold, where leaving one point out changes the fit violently. The jackknife plus stays near ninety percent in this experiment, above its eighty percent general lower bound; at p equal to n it covers ninety-five. Split conformal is valid too, though it dips at p equal to fifty, where its own fit, on only half the data, is the one interpolating; with sixty data sets per point, some wobble is expected.

The widths tell the rest. The noise alone, with standard deviation one, needs an interval about three point three wide. Near p equal to n, the jackknife plus gives very wide intervals, because a least squares fit that has just enough parameters to interpolate predicts wildly. The jackknife's intervals are wide there too, but they are centred on the full model's wild prediction, and miss half the time. For small p, the jackknife plus is narrower than split conformal, because its models are trained on all but one case rather than half of them.

Refitting n times is expensive for a forest or a network. CV plus does the same with K folds: each case's residual comes from the model trained without its fold, and the same model makes that case's shifted prediction at the new point. Ten folds, ten fits. Its bound includes a fold-dependent correction under the theorem’s symmetry and fold-size conditions. Nominal ninety percent is not a universal CV-plus guarantee. And for bagged models there is a free version: Byol Kim, Chen Xu and Barber's jackknife plus after bootstrap uses, for each case, the trees that never saw it, exactly the out-of-bag idea of chapter two.

On real data: the diabetes study of Part 32, four hundred and forty-two patients, ten baseline measurements, and disease progression a year later. A random forest wrapped in ten-fold CV plus, at ninety percent, on ten random splits into training and test patients. Here are twelve test patients: white dots are their outcomes, bars their intervals. Over all the test patients, the coverage is percent, and split conformal, training the forest on half the data, gives percent with intervals of similar width. Both are wide, about two hundred units, because a year's progression of diabetes is hard to predict from ten measurements: the intervals say so honestly.

Now the fixed width. Yaniv Romano, Evan Patterson and Emmanuel Candès proposed in 2019 to start from a band that already adapts: quantile regressions, from Parts 21 and 23, at alpha over two and one minus alpha over two, fitted on the training part. On the calibration cases, the score measures how far each response falls outside its band, negative if inside. Then widen both ends of the band by Q hat, the conformal quantile of those scores; if the quantile regressions were too generous, Q hat is negative and the band shrinks. The guarantee is the quantile lemma's, unchanged, and the width now follows the data.

On the World's incomes, the split conformal band of the last chapter, of fixed width. And the conformalized quantile regression band, built from linear quantile regressions at five and ninety-five percent on the same cubic in age. It is narrow for the young, wide in mid-career, and narrower again after retirement. Its correction Q hat is almost zero: the quantile regressions were already about right. Overall coverage percent. Its average width is a little larger here, because it reaches up into the long right tail where the incomes really are.

By age group, the fixed band ranged from to percent. The adaptive band ranges only from to . It is much closer to conditional coverage, because the quantile regressions model how the spread changes with age. But only the marginal ninety percent is guaranteed; the rest depends on how good the quantile regressions are.

Numbers: p = n: 0%, 53%, 95%

8Under shiftPhD6 min

Everything so far rested on exchangeability: the new case looks like a random draw from the same population as the calibration cases. That fails all the time. A model calibrated on one hospital's patients is used at another, with older patients. The simplest failure is covariate shift: the relationship between x and y is unchanged, but the inputs come from a different distribution. The shift is described by the likelihood ratio w of x, how much more common such inputs are in the test population than in calibration. Once w is not constant, a new case is no longer exchangeable with the old ones, and the quantile lemma no longer applies.

On the World: the income model of chapter six, calibrated on adults of all ages. Now use it on a population tilted heavily towards ages forty to sixty, say the clients of a financial adviser. We know the tilt exactly, because we drew the test population with it. The shift matters because these are exactly the ages at which incomes vary most.

Use the ordinary split conformal band, calibrated on everyone, on the tilted group, over two hundred repetitions. It covers percent, not ninety. The threshold was set by a population full of young adults and pensioners, whose incomes are easier to predict. The repair is to reweight the calibration cases so that, in effect, they come from the test population.

Ryan Tibshirani, Barber, Candès and Ramdas showed how in 2019. Give each calibration score a weight proportional to the likelihood ratio at its x, and give the new point its own weight, placed at infinity. Take the one minus alpha quantile of this weighted distribution of scores. They proved a weighted version of the quantile lemma: the resulting band covers at least one minus alpha under the shift. When all the weights are equal, it is ordinary split conformal. The threshold now depends on x, through the new point's weight: a point with a larger target-to-calibration density ratio can require a higher threshold, possibly infinity.

The unweighted threshold was about thousand dollars, and covered percent. The weighted threshold rises to about thousand, and covers percent. The weights simply let the calibration cases from mid-career, the ones that resemble the test population, set the threshold.

Usually the likelihood ratio is unknown. It can be estimated by training a classifier to tell calibration inputs from test inputs, since the odds it assigns to test are proportional to the likelihood ratio. The guarantee then holds only as well as the classifier. For slower, general drift, Barber, Candès, Ramdas and Tibshirani showed in 2023 that weighting recent cases more heavily loses coverage only in proportion to how far the data have drifted, measured in total variation. And when the drift never stops, there is another approach.

Here is a stream of scores, one per time step, from a forecaster whose errors suddenly triple in size at time one thousand and calm down again at two thousand: a volatile period in a market, or a new sensor that fails. A static split conformal threshold, calibrated on the first three hundred steps, covers only percent of the time during the storm. No fixed threshold can be right both before and during it.

Isaac Gibbs and Candès proposed adaptive conformal inference in 2021. At each time, use the one minus alpha t quantile of recent scores, where alpha t is a level we keep adjusting. Record whether this step's score exceeded the threshold: a miss. Then update alpha t by a small step gamma times alpha minus the miss indicator. A miss lowers alpha t by gamma times one minus alpha, so the next band is wider; a hit raises it by gamma alpha, one ninth as much at alpha point one, so the band slowly narrows. It is the simplest feedback controller there is.

The coverage over the last hundred steps, for both methods. The static threshold collapses to about half when the storm begins, and recovers only when it ends. Adaptive conformal dips briefly at each change, then climbs back to ninety percent within a hundred or so steps, because the misses push alpha t down until the band is wide enough. Overall it covers percent.

The guarantee is of an unusual kind. Over T steps, the miss rate is within a constant over gamma T of alpha, with infinite and empty interval conventions, for every finite-score sequence, including one chosen by an adversary who knows the method. The proof is a few lines: alpha t stays in a bounded interval, and its total movement is gamma times the sum of alpha minus the misses. The catch is that this is a long-run frequency, not a probability for any single step; misses can bunch together. And gamma trades fast adaptation against a jittery band. Part 57 develops these guarantees, and Part 58's anytime-valid inference shares their spirit.

Numbers: 87.1% → 90.3%; ACI 44.8% → 89.5%

9Classification setsMaster's6 min

For classification, the prediction is a set of labels. The simplest score is one minus the probability the model gave to the true label: a case is strange if the model thought its true class unlikely. For a new case, include every label whose score would not be strange, that is, every label whose probability is at least one minus q hat. The quantile lemma guarantees that the true label is in the set with probability at least one minus alpha under exchangeability. Mauricio Sadinle, Lei and Wasserman showed in 2019 that population probability-threshold sets are optimal in expected size when the true class probabilities are known. Estimated probabilities do not automatically attain that oracle optimum. The set's size is itself informative: one label when the model is sure, several when it is not.

Smallest on average is not always what we want: such sets can be too small for the hard cases and too large for the easy ones. Yaniv Romano, Matteo Sesia and Candès proposed adaptive prediction sets in 2020. Rank the labels from most to least probable. A case's score is the total probability of the labels ranked above its true label, plus a uniformly random share of the true label's own probability, which makes the score continuous when probabilities are positive. Coverage follows the finite calibration rank level, with rounding. The set for a new case includes labels whose randomized cumulative-probability score is at most q hat, using one shared random number for the new case. The boundary label may be included or excluded. If the model's probabilities were correct, their population score would be uniform conditional on the inputs. With estimated probabilities, improved conditional coverage is a goal, not a guarantee.

Fisher's irises from Part 31, made harder by using only the sepal measurements. Setosa stands apart, but versicolor and virginica overlap heavily. Quadratic discriminant analysis gets only seventy-six percent right. Sixty flowers train it, forty-five calibrate adaptive prediction sets at ninety percent, and forty-five test them, over three hundred random splits.

Eight test flowers from one split. The model's three probabilities, and the set. Each setosa gets the set setosa alone. Flowers the model splits between versicolor and virginica mostly get both; flower five, at fifty-seven to forty-three, kept only one, because of the randomized boundary decision. All eight are covered here; over many flowers, about one in ten would not be. The set says what the classifier knows, and what it does not.

Over all the splits, the sets cover percent of test flowers. Half the sets have a single label, nearly half have two, and a handful have none or all three. For setosa, the sets almost always contain one label. For the other two species, they average about one and two thirds: the overlap in the data shows up as the size of the answer.

Coverage by species is not guaranteed by a single threshold. With one threshold for all classes, setosa is covered percent of the time and virginica . Vovk's Mondrian conformal prediction, named after the painter's grid of separate rectangles, calibrates each class separately, using only the calibration cases of that class to set its own threshold. Then each class is covered at least ninety percent of the time; here above ninety, since each class has only about fifteen calibration flowers, and the quantile lemma's rounding is coarse. The same trick gives coverage within any groups fixed in advance: by sex, by hospital, by age band.

Back to the biopsies, with a deliberately simple logistic regression on three features and ninety-five percent sets. The coverage is percent overall, though malignant cases are covered a little less often than benign: the Mondrian version would fix that, and for a cancer test it should. Nearly every set has one label. A few contain both labels, and about two percent are empty. An empty set is the score-based method's way of spending its five percent: for a case the model puts near fifty-fifty, neither label is probable enough to pass the threshold. Adaptive sets can also be empty under randomization. Enlarging an empty set to both labels preserves the marginal coverage lower bound, while changing efficiency; clinical decisions need their own validation.

The same ranks give a p-value for any new case: one plus the number of calibration scores at least as large as its score, over n plus one. If the new case is exchangeable with the calibration data, this p-value is valid. A small one says the case is unlike anything seen: an outlier, a fraud, a new kind of tumour. With many new cases, run Part 33's Benjamini–Hochberg procedure on their conformal p-values. They share the calibration set and so are dependent, but Stephen Bates, Candès, Lei, Romano and Sesia proved this for independently sampled null test cases and calibration data with a separately fitted score. In that setting the dependence is of the positive kind BH tolerates, so the false discovery rate is controlled.

Numbers: 91.2%; sizes 1.00 vs 1.71

10Prediction-powered inferenceMaster's7 min

So far we have put intervals around predictions. Now turn it round: use predictions to estimate something else. Suppose measuring the truth is expensive, so we have it for only n cases. But a machine-learning model can guess it cheaply for a great many more, N. This is now common in science: protein structures predicted by AlphaFold instead of solved by crystallography, galaxies classified by a neural network instead of by volunteers, documents coded by a language model instead of by researchers. We want a population quantity, a mean or a regression coefficient, with an interval we can trust, and we want the guesses to help.

On the World. A health agency wants the island's mean systolic blood pressure. The truth for a person requires a clinic visit with three cuff readings; it can afford three hundred. But twenty thousand residents wear a smartwatch that estimates blood pressure. The watch's estimate is a random forest on the wearer's age, sex, body-mass index and the watch's own pulse-wave signal, trained by the manufacturer on its early users, who were all aged eighteen to fifty. Its guesses track the clinic readings well, with correlation , but not along the diagonal.

Here is the problem. By age, the true mean pressure rises steadily, and the watch agrees, over the ages it was trained on. Beyond fifty it falls behind, because a forest cannot extrapolate: for a pressure higher than any it saw in training, it cannot extrapolate its prediction beyond the range of training responses. For the over-eighties, the truth averages a hundred and fifty-one, the watch a hundred and thirty-six. Over the whole island, its guesses are about three millimetres of mercury too low.

Three estimates, each with a ninety percent interval, from one draw of the labelled and unlabelled samples. The true island mean, which we know because this is the World, is the dashed line. The classical estimate uses the three hundred clinic visits alone. It is honest and wide. The naive estimate treats the twenty thousand guesses as if they were data. Its interval is tiny, and it is nowhere near the truth: it estimates the mean of the watch, not of the people. The prediction-powered estimate uses both, and is both honest and narrower than the classical one.

The idea is one line of algebra. The mean of Y equals the mean of the guesses, minus the mean error of the guesses. Estimate the first term with the many unlabelled cases, and the second, the rectifier, with the few labelled ones, where we have both the guess and the truth. For a fixed prediction function, independent representative samples and finite moments, the mean estimator is unbiased even if the predictions are biased. That is Anastasios Angelopoulos, Stephen Bates, Clara Fannjiang, Michael Jordan and Tijana Zrnic's prediction-powered inference, published in Science in 2023. Here, the rectifier says the watch reads about three millimetres low on the labelled cases, and the estimate adds that back.

Its variance has two parts, one from each sample: the variance of the guesses over N, and the variance of the guesses' errors over n. The classical estimate's variance is the variance of Y over n. So plain prediction-powered inference wins when the residual variance plus n over N times the prediction variance is below the outcome variance. With enough unlabelled cases, that is approximately when the guesses' errors vary less than the truth itself, which is to say whenever the model explains some of the variation, even if it is biased. For the watch, the standard error falls from about one millimetre to about a half. Three hundred clinic visits, helped by twenty thousand biased guesses, are worth about visits alone.

What if the model is bad? Put a weight lambda on the guesses. The estimate stays unbiased for every fixed lambda; estimating lambda from the same data need not preserve exact unbiasedness, and the lambda that minimizes its variance is a regression coefficient of Y on the guesses, slightly shrunk. Angelopoulos, John Duchi and Zrnic call this PPI plus plus. Loosen the watch strap, so that each guess carries extra noise with a standard deviation of twenty-five. Plain prediction-powered inference, with lambda one, now has a standard error of , worse than the of the labels alone. PPI plus plus turns lambda down to about , and its standard error, , is again a little better than the classical one. With lambda estimated, it is never worse than ignoring the guesses, up to terms that vanish with n.

Survey statisticians will recognize the estimator. With the population's guesses known and a random sample measured, it is the difference estimator, the simplest case of Part 18's model-assisted estimation: the population mean of the model, plus the sample mean of the residuals. Claes Cassel, Carl-Erik Särndal and Jan Wretman analysed it in 1976, and Jay Breidt and Jean Opsomer surveyed its use with machine-learning models in 2017. What the new work adds is generality, to regression coefficients, quantiles and any estimand defined by a convex loss, and the tuning of lambda; and, perhaps most of all, a reason for the many fields now flooded with machine-learning labels to use it.

Two conditions carry the guarantee. The labelled cases must be a random sample from the same population as the unlabelled ones; if the clinic only sees the sick, no rectifier can save us. And the model must not have been trained on the labelled cases, or its errors there will look too small; with only one data set, cross-fitting does the job. With regularity conditions and asymptotically valid power tuning, a model can improve precision; plain PPI with weight one can increase variance. One last question about black boxes: when we ask one to explain itself, what are we estimating?

Numbers: 300 visits ≈ 1,045

11Interpretation as estimationPractice7 min

Statisticians are used to asking what an estimator estimates. Interpretation methods deserve the same question. Friedman's partial dependence of the fitted function on feature j sets that feature to v for everyone, and averages the predictions over the other features. Breiman's permutation importance is the increase in loss when feature j is scrambled. Leave one covariate out, LOCO, refits the model without feature j, and measures how much the loss rises. Each is a functional of the fitted model and of the population. They are different functionals, and they answer different questions.

A forest of two hundred trees on five hundred points from Friedman's function. On the left, its partial dependence on x four, whose true effect is a straight line, ten times x four. The forest's curve has the right slope in the middle and flattens at the ends, the edge bias of averaging over leaves that we saw in chapter two. On the right, x three, whose true effect is a deep parabola. The forest only half finds it: a shallow dish, rising at the ends, because a curve in a weaker feature is hard for splits to capture while stronger features compete for them. So partial dependence is an honest summary of the fitted model. Whether it describes nature depends on how good the model is, and, as the next example shows, on the other features.

Now give the forest a twin: an eleventh feature that is x one plus a little noise, correlated about point nine seven with it, and carrying no additional outcome information once the original feature is known. Permutation importance, computed on fresh test data, credits both: x one with and the twin with . LOCO, which refits the forest without each feature in turn, tells a different story: without x one the twin stands in for it, and the loss barely rises, and the same is true the other way round. These fitted-model loss differences are small. The original still has information missing from its noisy twin; finite-model LOCO need not equal the oracle population importance.

Why does permutation give the twin so much credit? Scrambling x one alone creates artificial cases in which x one is point nine and its twin point one. Such cases are extremely rare under this noisy-twin distribution, so the forest has little training support there; its predictions there are arbitrary. So permutation importance partly measures how the model behaves away from the data, which is a property of the model, not of the world. Giles Hooker, Lucas Mentch and Siyu Zhou made this argument in 2021 under the heading: please stop permuting features. Partial dependence plots extrapolate in exactly the same way when features are correlated.

LOCO's target can be written without any model at all. Its population version is the increase in the best possible mean squared error when feature j is withheld. It equals the expected squared difference between the regression function and its conditional mean given the other features. It is zero exactly when feature j adds nothing to the others: a conditional importance, which is why the twins both scored near zero. Being a population quantity, it can be estimated with a confidence interval, by sample splitting and refitting; Brian Williamson, Peter Gilbert, Noah Simon and Marco Carone showed in 2021 how to do so efficiently, with any machine-learning method inside.

For a single prediction, the most popular explanation borrows from game theory. Treat the features as players. The value of a coalition S is the average prediction when the features in S are fixed at this case's values and the others are drawn from the population. Lloyd Shapley showed in 1953 that only one way of sharing out a game's value is symmetric, additive and gives nothing to a player who contributes nothing: with the efficiency axiom as well, each player’s average marginal contribution over all orders of joining. The shares add up exactly to this prediction minus the average prediction. With m features there are two to the m coalitions, so in practice they are approximated; Scott Lundberg and Su-In Lee's SHAP of 2017 made that fast, especially for trees.

Exact Shapley values for one case, over the first five features as players, computing all thirty-two coalitions with the forest. The average prediction over the chosen 120-case background is . Each feature's share is a step up or down. This case has a large x four, which pushes the prediction up most, then x two and x one, through the sine of their product; x three, near the high end of its parabola, adds a little; x five, near its average, a small contribution. The steps end exactly at the prediction for this case's five values, : the shares account for the whole difference for this five-player game; the other features, including the twin, are averaged over the background rather than fixed at the full case. Like partial dependence, the coalition values fill in the missing features independently of the ones fixed, so with correlated features they too ask the model about combinations that are very rare under their joint distribution.

So an explanation is an estimate, and has a sampling distribution. Retrain on a bootstrap sample and the importances move, as the trees' root splits moved in chapter one. Before reporting one, say whether it describes the model, which is fine for debugging the model, or nature, which is what a scientist wants. For nature, population quantities such as LOCO's, estimated with intervals, are the honest choice.

And none of them is causal. That the model leans on a feature does not mean that changing the feature would change the outcome. The outro tells the story of a model that concluded asthma protects you from dying of pneumonia, and was right about the data.

Numbers: permutation 3.49 / 1.96 vs LOCO 0.42 / 0.04

Recap, problems, and the road aheadAll tracks5 min

We end with a warning that Rich Caruana and his colleagues published in 2015. In the 1990s, a large study had built models to predict which pneumonia patients were likely to die, so that the low-risk ones could be treated at home. One rule-based model learned that patients with asthma were at lower risk. Caruana's team rebuilt the analysis on over fourteen thousand patients with an intelligible model, and found the same pattern, and others like it. The model was right about the data. Asthmatics who came in with pneumonia were sent straight to intensive care and treated aggressively, and the authors proposed treatment intensity as an explanation for the association; predictive accuracy alone does not establish that causal effect. Used to decide who can go home, the model could incorrectly classify asthmatics as suitable for less intensive care. That counterfactual risk is not measured by predictive accuracy. A perfect predictor of what happened is not a guide to what to do. Prediction answers what will happen if we carry on as before. Decisions need the answer to a different question: what would happen if we acted differently.

Part thirty-four in twelve lines. Breiman told statisticians that algorithms had won prediction, and Cox and Efron replied that prediction is not all of science. Many models predict equally well and tell different stories. A forest's variance is rho sigma squared plus a term that vanishes with more trees, so decorrelating the trees is what helps. The infinitesimal jackknife measures a forest's variance but not its bias. Boosting is forward stagewise additive modelling. Cross-validation estimates the error of the procedure, not of the model in hand. Probabilities can be recalibrated. The quantile lemma makes split conformal intervals valid for any model. The jackknife plus uses all the data, and conformalized quantile regression gives bands that adapt. Weighting repairs a known covariate shift, and adaptive conformal tracks a drifting stream. Prediction sets admit doubt, class by class if we ask. And prediction-powered inference turns biased guesses into valid estimates with a rectifier.

A promise for later. This part gave every model a finite-sample coverage guarantee. It assumed exchangeability, or a shift we know, and it delivered marginal coverage, an average over the population. Part 57 asks what can be guaranteed with no assumptions at all, proves that some things cannot, starting with Bahadur and Savage's obstruction to nontrivial honest mean intervals over an unrestricted finite-mean distribution class, and finds the conditional guarantees that are possible.

Where it comes back. Part 35 begins with the difference between predicting and intervening. Part 36's double machine learning uses forests and boosting to fit nuisance functions. Part 40 grows survival forests and conformal bands for censored times. Part 54 proves generalization bounds for learners. Part 57 proves the distribution-free results of this part, and their limits. Part 58's anytime-valid inference uses probability guarantees that differ from adaptive conformal’s long-run miss-frequency control. Part 60 studies distribution shift in depth. Part 62 grows causal forests for treatment effects that vary from person to person. And Part 64 returns to machine-learning labels, with language models as the labellers.

Six problems, with full solutions in the README. The forest's variance formula; what AdaBoost estimates; both sides of the quantile lemma; the beta distribution of conditional coverage; the prediction-powered estimator's bias and its best lambda; and the adaptive conformal bound. Pause here if you want to try them.

The books this part follows: Vovk, Gammerman and Shafer's Algorithmic Learning in a Random World; Angelopoulos and Bates's gentle introduction to conformal prediction; The Elements of Statistical Learning; and Efron and Hastie's Computer Age Statistical Inference; with the papers from Breiman to Caruana.

Thirty-four parts of sixty-five. Any black box can now come with an honest interval, and its guesses can sharpen an honest estimate. But the asthma model shows the limit of prediction: it says what happens if nothing changes. Part 35 asks what it means for one thing to cause another, and why a coin flip lets us find out. What if?

Where it goes next. Prediction is not intervention: potential outcomes in Part 35. Forests and boosting return as nuisance fits in Part 36, conformal bands for censored times in Part 40, distribution-free inference with its impossibility theorems in Part 57, anytime-valid inference in Part 58, shift in Part 60, and PPI's successors in Part 64.

Key results

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

Variance of a forest\(\displaystyle \operatorname{Var}\Bigl(\tfrac1B\sum_{b=1}^B T_b(x)\Bigr)=\rho\sigma^2+\frac{1-\rho}{B}\,\sigma^2\)
Split conformal\(\displaystyle \hat q=S_{(k)},\ k=\lceil(n+1)(1-\alpha)\rceil:\qquad\allowbreak 1-\alpha\le\Pr\bigl(|Y-\hat\mu(X)|\le\hat q\bigr)\le1-\alpha+\frac{1}{n+1}\quad\allowbreak \text{(upper }\allowbreak \text{bound: }\allowbreak \text{no }\allowbreak \text{ties)}\)
Coverage given the calibration set\(\displaystyle \Pr\bigl(Y\in\hat C(X)\mid\text{calibration}\bigr)\sim\operatorname{Beta}(k,\ n+1-k)\quad\allowbreak \text{(i.i.d. }\allowbreak \text{continuous }\allowbreak \text{scores)}\)
Adaptive conformal inference\(\displaystyle \alpha_{t+1}=\alpha_t+\gamma\,(\alpha-\operatorname{err}_t),\qquad\allowbreak \operatorname{err}_t=\mathbf 1\{Y_t\notin\hat C_t\}\)
Prediction-powered mean\(\displaystyle \hat\theta=\frac1N\sum_{j=1}^Nf(\tilde X_j)-\frac1n\sum_{i=1}^n\bigl(f(X_i)-Y_i\bigr),\qquad\allowbreak \operatorname{Var}=\frac{\sigma_f^2}{N}+\frac{\sigma_{Y-f}^2}{n}\)

Try it

Lab 34 · Split conformal: what 90% promises

With 19 calibration scores take the 18th smallest as the threshold, four thousand times, and compare the coverage with the quantile lemma's 18/20 and with the Beta(18, 2) law of coverage given the calibration set; then fit least squares with 20 predictors and compare intervals from in-sample residuals with split conformal.

Figure produced by Lab 34: Split conformal: what 90% promises
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 34 needs numpy, scipy, matplotlib · download lab34.py · source on GitHub
n = 19: rank k = ceil((n + 1)(1 - alpha))                       18
coverage of one new case                                        0.906   (theory k/(n + 1) = 0.900)
coverage given the calibration set, 5% and 95% points           0.768, 0.982   (Beta(18, 2): 0.774, 0.981)
Kolmogorov distance of that coverage from the Beta law          0.013   (p = 0.51)
least squares, p = 20, n = 100: in-sample residual band covers  80.3%   (nominal 90%), width 2.90
split conformal with 100 fresh calibration cases covers         90.3%   (theory 90.1%), width 3.75

The guarantee is exact and marginal: 18/20 on average over calibration sets, but any one calibration set of 19 gives coverage anywhere from 77% to 98%. Residuals of the training cases give no guarantee.
The code (83 lines; it asserts its own result)
"""Lab 34: climb the score ladder: split conformal's coverage, exactly and given the calibration set."""

import numpy as np
from scipy import stats

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

TITLE = "Split conformal: what 90% promises"
GOAL = ("With 19 calibration scores take the 18th smallest as the threshold, four thousand times, and compare the "
        "coverage with the quantile lemma's 18/20 and with the Beta(18, 2) law of coverage given the calibration set; "
        "then fit least squares with 20 predictors and compare intervals from in-sample residuals with split conformal.")
TASKS = [
    "Set N_CAL to 99 and to 999. How does the 5%-95% range of the conditional coverage narrow, and what is its Beta law?",
    "Multiply the test noise by 1.5 so calibration and test are no longer exchangeable. What does the 90% become?",
    "Replace split conformal by conformal.jackknife_plus with least squares. Compare its coverage and width with the split.",
]

N_CAL, ALPHA = 19, 0.1


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. the ladder: scores |e| with e ~ N(0, 1), so coverage given the threshold q is exactly 2 Phi(q) - 1
    reps = 4000
    k = int(np.ceil((N_CAL + 1) * (1 - ALPHA)))
    q = np.array([conformal.conformal_quantile(np.abs(rng.standard_normal(N_CAL)), ALPHA) for _ in range(reps)])
    cond = 2 * stats.norm.cdf(q) - 1
    hit = np.abs(rng.standard_normal(reps)) <= q
    beta = stats.beta(k, N_CAL + 1 - k)
    lab.row(f"n = {N_CAL}: rank k = ceil((n + 1)(1 - alpha))", f"{k}")
    lab.row("coverage of one new case", f"{hit.mean():.3f}   (theory k/(n + 1) = {k / (N_CAL + 1):.3f})")
    lab.row("coverage given the calibration set, 5% and 95% points",
            f"{np.quantile(cond, 0.05):.3f}, {np.quantile(cond, 0.95):.3f}   (Beta({k}, {N_CAL + 1 - k}): "
            f"{beta.ppf(0.05):.3f}, {beta.ppf(0.95):.3f})")
    ks = stats.kstest(cond, beta.cdf)
    lab.row("Kolmogorov distance of that coverage from the Beta law", f"{ks.statistic:.3f}   (p = {ks.pvalue:.2f})")
    assert abs(cond.mean() - k / (N_CAL + 1)) < 0.004 and abs(hit.mean() - k / (N_CAL + 1)) < 0.02, "the quantile lemma"
    assert 1 - ALPHA <= k / (N_CAL + 1) <= 1 - ALPHA + 1 / (N_CAL + 1)
    assert ks.statistic < 0.035, "coverage given the calibration set is Beta(k, n + 1 - k)"
    assert abs(np.quantile(cond, 0.05) - 0.774) < 0.015 and abs(np.quantile(cond, 0.95) - 0.981) < 0.006

    # 2. a model that overfits: least squares, n = 100 training cases, p = 20 predictors
    n, p, trials, ntest = 100, 20, 400, 200
    cov_in, cov_split, width_in, width_split = [], [], [], []
    for _ in range(trials):
        b = rng.standard_normal(p) / np.sqrt(p)
        X, Xc, Xt = (rng.standard_normal((m, p)) for m in (n, n, ntest))
        y, yc, yt = (Z @ b + rng.standard_normal(len(Z)) for Z in (X, Xc, Xt))
        bh = np.linalg.lstsq(X, y, rcond=None)[0]
        q_in = np.quantile(np.abs(y - X @ bh), 1 - ALPHA)  # residuals of the cases the model was fitted to
        sc = conformal.split_conformal(Xc @ bh, yc, Xt @ bh, ALPHA)  # residuals of 100 cases it never saw
        cov_in.append(np.mean(np.abs(yt - Xt @ bh) <= q_in))
        cov_split.append(np.mean((sc["lo"] <= yt) & (yt <= sc["hi"])))
        width_in.append(2 * q_in)
        width_split.append(2 * sc["q"])
    ci, cs = float(np.mean(cov_in)), float(np.mean(cov_split))
    lab.row("least squares, p = 20, n = 100: in-sample residual band covers", f"{ci:.1%}   (nominal 90%), width {np.mean(width_in):.2f}")
    lab.row("split conformal with 100 fresh calibration cases covers", f"{cs:.1%}   (theory {91 / 101:.1%}), width {np.mean(width_split):.2f}")
    assert ci < 0.84, "in-sample residuals are too small: the band undercovers"
    assert abs(cs - 91 / 101) < 0.012, "split conformal covers ceil(101 * 0.9)/101 whatever the model"
    lab.note = ("The guarantee is exact and marginal: 18/20 on average over calibration sets, but any one calibration "
                "set of 19 gives coverage anywhere from 77% to 98%. Residuals of the training cases give no guarantee.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    s = np.sort(np.abs(np.random.default_rng(seed + 1).standard_normal(N_CAL)))
    colors = [labs.GOLD if i == k - 1 else labs.BLUE for i in range(N_CAL)]
    ax[0].bar(np.arange(1, N_CAL + 1), s, color=colors)
    ax[0].axhline(s[k - 1], color=labs.GOLD, ls="--", label=f"threshold: the {k}th of {N_CAL} scores")
    ax[0].set(title="The score ladder", xlabel="rank of the calibration score", ylabel="score |y - prediction|")
    ax[0].set_xticks([1, 5, 10, 15, 18, 19])
    ax[0].legend(loc="upper left")
    grid = np.linspace(0.6, 1, 300)
    ax[1].hist(cond, bins=np.linspace(0.6, 1, 41), density=True, color=labs.BLUE, alpha=0.6,
               label="4,000 calibration sets of 19")
    ax[1].plot(grid, beta.pdf(grid), color=labs.GOLD, label=f"Beta({k}, {N_CAL + 1 - k})")
    ax[1].axvline(1 - ALPHA, color=labs.MUTED, ls="--", label="nominal 90%")
    ax[1].set(title="Coverage given the calibration set", xlabel="coverage of new cases", ylabel="density")
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Set N_CAL to 99 and to 999. How does the 5%-95% range of the conditional coverage narrow, and what is its Beta law?
  2. Multiply the test noise by 1.5 so calibration and test are no longer exchangeable. What does the 90% become?
  3. Replace split conformal by conformal.jackknife_plus with least squares. Compare its coverage and width with the split.

Problems, with solutions

Try each problem before opening its solution.

  1. The forest's variance. Show that \(B\) identically distributed predictions with pairwise correlation \(\rho\) average to variance \(\rho\sigma^2 + (1-\rho)\sigma^2/B\).

    Solution

    Let t₁, …, t_B have common variance σ² and pairwise correlation ρ.

    • Var(Σ t_b / B) = B⁻² (Σ_b Var t_b + Σ_{b≠b'} Cov(t_b, t_b')) = B⁻² (Bσ² + B(B − 1)ρσ²) = ρσ² + (1 − ρ)σ²/B.
    • As B → ∞ this falls to ρσ². The excess over the limit is (1 − ρ)σ²/B, so it is within 5% of the limit once (1 − ρ)/(Bρ) ≤ 0.05; for ρ = 0.1, that is B ≥ 180.
  2. What AdaBoost estimates. Show that \(\arg\min_F E[e^{-YF} \mid x] = \frac12 \log\{P(Y = 1 \mid x)/P(Y = -1 \mid x)\}\).

    Solution

    With p = P(Y = 1 | x), E[e^{−YF} | x] = p e^{−F} + (1 − p) e^{F}.

    • The derivative in F is −p e^{−F} + (1 − p) e^{F}, which is 0 when e^{2F} = p/(1 − p).
    • So F* = ½ log{p/(1 − p)}. The second derivative is positive, so this is the minimum.
  3. The quantile lemma. For continuous scores, prove \(1 - \alpha \le P(S_{n+1} \le \hat q) \le 1 - \alpha + 1/(n+1)\).

    Solution

    By exchangeability and continuity, the rank R of S_{n+1} among the n + 1 scores is uniform on {1, …, n + 1}.

    • S_{n+1} ≤ S_(k) (the k-th smallest of the first n) if and only if R ≤ k. So P = k/(n + 1).
    • With k = ⌈(n + 1)(1 − α)⌉ we have (n + 1)(1 − α) ≤ k < (n + 1)(1 − α) + 1.
    • Dividing by n + 1 gives 1 − α ≤ P < 1 − α + 1/(n + 1).
  4. Conditional coverage. Show that, given the calibration set, for i.i.d. continuous scores, the coverage \(F(\hat q)\) is \(\mathrm{Beta}(k, n + 1 - k)\).

    Solution

    Assume calibration and test scores are i.i.d. with continuous distribution F conditional on a separately trained model. Given the calibration scores, coverage is F(S_(k)).

    • For continuous F, the values U_i = F(S_i) are i.i.d. uniform, and F(S_(k)) = U_(k).
    • The k-th order statistic of n uniforms is Beta(k, n + 1 − k), with mean k/(n + 1).
  5. PPI. Show \(\hat\theta^{PP}_\lambda\) is unbiased for every fixed \(\lambda\); find the \(\lambda\) minimizing its variance.

    Solution

    θ̂_λ = λ f̄_N − (λ f̄_n − ȳ_n).

    • For a fixed prediction function, independent representative samples and fixed λ, its expectation is λ E f − λ E f + E Y = θ. Estimating λ on the labelled sample need not preserve exact unbiasedness.
    • The two samples are independent, so Var = λ² Var(f)/N + Var(Y − λf)/n = λ² Var f (1/N + 1/n) − 2λ Cov(Y, f)/n + Var Y/n.
    • Setting the derivative in λ to zero gives λ* = Cov(Y, f) / ((1 + n/N) Var f), PPI++'s choice. At λ = 0 the estimator is the classical one, so the population variance optimum is never worse. Estimated weights achieve this only asymptotically under appropriate moment and consistency conditions.
  6. The ACI bound. Prove the ACI bound \(|\frac1T\sum_t \mathrm{err}_t - \alpha| \le (\max(\alpha_1, 1 - \alpha_1) + \gamma)/(\gamma T)\).

    Solution

    Assume γ > 0, α₁ ∈ [0, 1], target α ∈ (0, 1), and the quantile convention q̂ = −∞ when α_t ≥ 1 and +∞ when α_t ≤ 0.

    • Then α_t stays in [−γ, 1 + γ]: when α_t < 0 the band is infinite, no miss occurs, and α_t rises. When α_t > 1 every step is a miss, and α_t falls.
    • Summing the update over t gives α_{T+1} − α₁ = γ Σ_t (α − err_t).
    • So |T⁻¹ Σ err_t − α| = |α_{T+1} − α₁|/(γT) ≤ (max(α₁, 1 − α₁) + γ)/(γT).

Notes and sources

Where it comes back

  • Part 35: prediction is not intervention; potential outcomes.
  • Part 36: forests and boosting as nuisance fits in double machine learning.
  • Part 40: survival forests; conformal bands for censored times.
  • Part 54: generalization bounds for learning algorithms.
  • Part 57: distribution-free inference proved, with its impossibility theorems (the upgrade card).
  • Part 58: anytime-valid inference, kin to ACI's sequence-wise guarantee.
  • Part 60: distribution shift in depth.
  • Part 62: causal forests and heterogeneous treatment effects.
  • Part 64: machine-learning and LLM labels; PPI's successors.

Glossary

  • Rashomon set: all models in a class whose loss is within ε of the best.
  • Bagging; random forest: averaging trees grown on bootstrap samples; with m_try random features per split.
  • Out-of-bag (OOB): the prediction for a case from the trees whose sample did not include it.
  • Impurity / permutation importance: a feature's total reduction in training loss across splits / the rise in held-out loss when it is scrambled.
  • Infinitesimal jackknife (IJ): Σ_i Cov_b(N_bi, t_b(x))², a variance estimate for a bagged predictor.
  • Forward stagewise additive modelling: adding one basis function at a time without refitting the others; boosting.
  • Err_XY / Err: the error of the fitted model on new data / its average over training sets.
  • Calibration; ECE: P(Y = 1 | p̂ = p) = p; the count-weighted mean gap in a reliability diagram.
  • Exchangeable: a joint distribution invariant to permutations.
  • Conformal quantile: the ⌈(n + 1)(1 − α)⌉-th smallest calibration score.
  • Split conformal; jackknife+; CV+: conformal intervals from a held-out calibration set; from leave-one-out or K-fold models.
  • CQR: conformalized quantile regression.
  • Covariate shift; weighted conformal: a change in P_X with P_{Y|X} fixed; calibration scores reweighted by dP̃/dP.
  • ACI: adaptive conformal inference, α_{t+1} = α_t + γ(α − err_t).
  • LAC; APS; Mondrian: least-ambiguous sets; adaptive prediction sets; class- or group-wise calibration.
  • Conformal p-value: (1 + #{S_i ≥ S})/(n + 1).
  • PPI; rectifier; PPI++: prediction-powered inference; the mean guess error on labelled data; the variance-tuned λ.
  • PDP; LOCO; Shapley value: partial dependence; leave-one-covariate-out importance; average marginal contribution over coalitions.

Sources

  • The two cultures.
    • L. Breiman, Stat. Sci. 16 (2001), with comments by D. R. Cox, B. Efron, B. Hoadley and E. Parzen.
    • G. Shmueli, Stat. Sci. 25 (2010).
    • A. Fisher, C. Rudin & F. Dominici, JMLR 20 (2019); L. Semenova, C. Rudin & R. Parr, FAccT (2022).
  • Forests.
    • L. Breiman, Mach. Learn. 24 (1996), 45 (2001); T. K. Ho (1995); Y. Amit & D. Geman, Neural Comput. 9 (1997).
    • G. Biau, L. Devroye & G. Lugosi, JMLR 9 (2008); G. Biau, JMLR 13 (2012); E. Scornet, G. Biau & J.-P. Vert, Ann. Stat. 43 (2015).
    • C. Strobl, A.-L. Boulesteix, A. Zeileis & T. Hothorn, BMC Bioinf. 8 (2007).
    • B. Efron, JASA 109 (2014); S. Wager, T. Hastie & B. Efron, JMLR 15 (2014); S. Wager & S. Athey, JASA 113 (2018).
    • J. Friedman, Ann. Stat. 19 (1991) (the test function).
  • Boosting.
    • M. Kearns & L. Valiant (1988); R. Schapire, Mach. Learn. 5 (1990); Y. Freund & R. Schapire, JCSS 55 (1997).
    • J. Friedman, T. Hastie & R. Tibshirani, Ann. Stat. 28 (2000); J. Friedman, Ann. Stat. 29 (2001), CSDA 38 (2002).
    • S. Rosset, J. Zhu & T. Hastie, JMLR 5 (2004); T. Chen & C. Guestrin, KDD (2016); L. Grinsztajn, E. Oyallon & G. Varoquaux, NeurIPS (2022).
  • Cross-validation.
    • M. Stone, JRSS B 36 (1974); S. Geisser, JASA 70 (1975).
    • C. Ambroise & G. McLachlan, PNAS 99 (2002); S. Varma & R. Simon, BMC Bioinf. 7 (2006).
    • S. Bates, T. Hastie & R. Tibshirani, JASA 119 (2024); T. Hastie, R. Tibshirani & J. Friedman, ESL, §7.12.
  • Calibration.
    • G. Brier, Mon. Weather Rev. 78 (1950); A. Murphy & R. Winkler, Appl. Stat. 26 (1977).
    • J. Platt (1999); B. Zadrozny & C. Elkan, KDD (2002); A. Niculescu-Mizil & R. Caruana, ICML (2005).
    • C. Guo, G. Pleiss, Y. Sun & K. Weinberger, ICML (2017); Ú. Hébert-Johnson, M. Kim, O. Reingold & G. Rothblum, ICML (2018).
  • Conformal.
    • V. Vovk, A. Gammerman & G. Shafer, Algorithmic Learning in a Random World (2005; 2nd ed. 2022).
    • H. Papadopoulos, K. Proedrou, V. Vovk & A. Gammerman, ECML (2002); V. Vovk, ACML (2012).
    • J. Lei, M. G'Sell, A. Rinaldo, R. Tibshirani & L. Wasserman, JASA 113 (2018); J. Lei & L. Wasserman, JRSS B 76 (2014).
    • R. Barber, E. Candès, A. Ramdas & R. Tibshirani, Ann. Stat. 49 (2021), Inf. Inference 10 (2021), Ann. Stat. 51 (2023).
    • B. Kim, C. Xu & R. Barber, NeurIPS (2020).
    • Y. Romano, E. Patterson & E. Candès, NeurIPS (2019); Y. Romano, M. Sesia & E. Candès, NeurIPS (2020).
    • R. Tibshirani, R. Barber, E. Candès & A. Ramdas, NeurIPS (2019); I. Gibbs & E. Candès, NeurIPS (2021).
    • M. Sadinle, J. Lei & L. Wasserman, JASA 114 (2019); S. Bates, E. Candès, L. Lei, Y. Romano & M. Sesia, Ann. Stat. 51 (2023).
    • A. Angelopoulos & S. Bates, Found. Trends Mach. Learn. 16 (2023).
  • PPI.
    • A. Angelopoulos, S. Bates, C. Fannjiang, M. Jordan & T. Zrnic, Science 382 (2023); A. Angelopoulos, J. Duchi & T. Zrnic, PPI++ (2023).
    • C. Cassel, C.-E. Särndal & J. Wretman, Biometrika 63 (1976); F. J. Breidt & J. Opsomer, Stat. Sci. 32 (2017).
  • Interpretation.
    • J. Friedman (2001) (partial dependence); L. Shapley (1953); E. Štrumbelj & I. Kononenko, JMLR 11 (2010); S. Lundberg & S.-I. Lee, NeurIPS (2017).
    • G. Hooker, L. Mentch & S. Zhou, Stat. Comput. 31 (2021); B. Williamson, P. Gilbert, N. Simon & M. Carone, JASA 116 (2021).
  • Asthma and pneumonia.
    • R. Caruana, Y. Lou, J. Gehrke, P. Koch, M. Sturm & N. Elhadad, KDD (2015); G. Cooper et al., Artif. Intell. Med. 9 (1997).
  • Data.
    • W. Wolberg, W. N. Street & O. Mangasarian (1995), via scikit-learn; R. A. Fisher, Ann. Eugen. 7 (1936); B. Efron, T. Hastie, I. Johnstone & R. Tibshirani, Ann. Stat. 32 (2004).
About this partfrom its README

Part 34 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the fourteenth part of Stage III, Master's. Part 33 controlled the error rates of many questions at once, with knockoff exchangeability, conditional-null and flip-sign conditions. This part asks how far that goes for prediction:

  • forests and boosting treated as estimators, with a variance, an importance measure and intervals;
  • what cross-validation estimates, and when a predicted probability can be trusted;
  • conformal prediction, which gives marginal finite-sample coverage with exchangeable calibration/test scores and a separately trained model;
  • prediction-powered inference, which turns a model's biased guesses into valid estimates;
  • what interpretation methods estimate.

Its builds are statkit.conformal and statkit.ppi. Its instrument is the score ladder (ScoreLadder): n calibration scores sorted as bars, the conformal rank k = ⌈(n + 1)(1 − α)⌉ picked out, the threshold drawn across, and the gap a new score falls into.

It opens with Breiman's "Statistical Modeling: The Two Cultures" (2001), with Cox's and Efron's replies, and a forest on the Wisconsin breast cancer data that says "malignant, probability 0.83" for one held-out patient.

From there the part covers:

  • Explain or predict? Shmueli (2010); the bias–variance decomposition of EPE, and when a wrong model predicts better in an orthogonal-regression approximation (β₂² Var x₂ < σ²/n).

    • 50 bootstrap depth-3 trees on 400 biopsies: test accuracy 93.4% ± 1.8, but 5 different root features (worst concave points 21 times, mean concave points 11, worst perimeter 10, worst area 4, worst radius 4) and 39 different "top three" lists. Radius, perimeter and area correlate 0.94–0.998.
    • Three logistic regressions on disjoint feature pairs: 95.3%, 95.3%, 92.9%.
    • The Rashomon set and model class reliance (Fisher, Rudin & Dominici 2019).
  • Forests. Bagging (Breiman 1996) and random forests (Breiman 2001).

    • Var = ρσ² + (1 − ρ)σ²/B, measured on Friedman 1 (n = 300, 40 training sets × 40 trees, 200 test points):

      m_try σ² (one tree) ρ Var (forest of 40) bias² MSE
      10 (bagging) 8.11 0.128 1.22 3.31 4.53
      5 9.86 0.068 0.90 3.57 4.47
      3 11.73 0.044 0.80 4.27 5.07
      1 14.99 0.024 0.72 8.39 9.12
    • Breast cancer (plus two pure-noise columns), 169 test cases: one deep tree 7.1% wrong, bagging 5.9%, forest (m_try = 6) 5.9%; OOB error 3.5%.

    • Consistency: Biau, Devroye & Lugosi (2008), Biau (2012), Scornet, Biau & Vert (2015); Wager & Athey (2018).

    • Importance: impurity importance credits the continuous noise column 15× the coin-flip column (Strobl et al. 2007); permutation importance gives both ≈ 0.

    • The infinitesimal jackknife (Wager, Hastie & Efron 2014) at a peak of Friedman 1 (μ(x₀) = 22.55), n = 250, 300 forests:

      • bootstrap forests of 500 trees have an independent pilot estimate E f̂(x₀) = 20.571 (MCSE 0.037, 200 pilot forests). Intervals cover this reference in 60.3% of 300 independent forests, because the mean SE is 0.39 against a true SD of 0.56;
      • subsampled CART forests (s = 50, 2,000 trees) cover their independent pilot reference 83.7% of the time. The reference is 18.798 (MCSE 0.048, 100 pilot forests); intervals cover μ(x₀) 0% of the time. Subsampling alone does not implement Wager–Athey honest forests or establish their theorem. Pilot-reference coverage also has Monte Carlo uncertainty.
  • Boosting. AdaBoost (Freund & Schapire 1997) as forward stagewise additive modelling (Friedman, Hastie & Tibshirani 2000) and gradient boosting (Friedman 2001).

    • A 1-D stump staircase.
    • Friedman 1 (n = 400, depth 2, 3,000 test points): ν = 1 bottoms out at MSE 6.63 after 59 trees, then rises; ν = 0.1 reaches 2.64 at 600 trees; a forest gives 5.43; the noise is 1. The minimum on the plotted test curve is an oracle comparison, not a cross-validated choice. Smaller learning rates need not always improve generalization.
    • The exponential loss's minimizer is half the log odds; LogitBoost; the stagewise–lasso link under additional path/monotonicity conditions; XGBoost.
  • What cross-validation estimates (Bates, Hastie & Tibshirani 2024). OLS, n = 100, p = 20, σ = 1, 1,000 data sets, with Err_XY = 1 + ‖β̂ − β‖² known exactly and Err = 1 + p/(n − p − 1) = 1.253:

    • corr(CV, Err_XY) = 0.013;
    • SD of Err_XY is 0.090 and SD of the CV estimate 0.222; mean CV 1.289;
    • the naive 90% interval covers Err 82.8% (and Err_XY 80.2%); the true SD is 1.23× the naive SE;
    • nested CV; selection bias in CV (Ambroise & McLachlan 2002; Varma & Simon 2006).
  • Calibration. Reliability diagrams and ECE; Gaussian naive Bayes on all 30 features (40 splits of 300 train / 135 calibrate / 134 test). 98% of its predictions fall below 0.1 or above 0.9; the fitted temperature is T̂ = 7.9.

    Model Accuracy Mean-split ECE Brier
    naive Bayes 93.7% 0.062 0.059
    + Platt 93.7% 0.049 0.045
    + temperature 93.7% 0.053 0.044
    + isotonic 93.3% 0.038 0.047
    forest 95.7% 0.052 0.035
    + isotonic 95.6% 0.033 0.035

    ECE is averaged over splits, while the reliability diagram pools held-out predictions; these are distinct summaries. Forests can be underconfident at the extremes (Niculescu-Mizil & Caruana 2005); multicalibration.

  • Split conformal (Vovk, Gammerman & Shafer 2005; Papadopoulos et al. 2002; Lei et al. 2018).

    • Exchangeability and uniform ranks; the quantile lemma, coverage ≥ 1 − α. The upper bound 1 − α + 1/(n + 1) requires no score ties.
    • The score ladder with 19 scores: k = 18, q = 21.0; 20,000 simulated draws cover 90.14% (exact 18/20).
    • For i.i.d. continuous scores conditional on the separately fitted model, coverage given the calibration set has distribution Beta(k, n + 1 − k); exchangeability alone is insufficient for this Beta law. Its central 90% range is 0.774–0.981 for n = 19, 0.847–0.944 for n = 99, and 0.884–0.915 for n = 999.
    • World incomes from a cubic in age with a retirement step: q̂ = 44.5 (thousand dollars), coverage 90.4%; by age, 95.8% (18–24) down to 83.4% (55–66).
    • The impossibility of useful exact distribution-free conditional coverage over unrestricted response laws and nonatomic covariates (Vovk 2012; Lei & Wasserman 2014; Barber et al. 2021), rather than an impossibility for every restricted model or groupwise target.
  • Jackknife+ and CQR.

    • Barber, Candès, Ramdas & Tibshirani (2021): n = 100, least squares (minimum-norm past p = n), 60 data sets per p. At p = n coverage is 0% in-sample, 53% for the jackknife, 95% for jackknife+ and 87% for split. These are experimental results. The general exchangeable-data jackknife+ bound is 1 − 2α (80% here); a near-90% guarantee needs stability or other conditions. CV+ also has a finite-fold correction.
    • CV+ with a forest on the diabetes data (10 splits): 90.5% coverage, width 184; split gives 90.8%, width 191.
    • CQR (Romano, Patterson & Candès 2019) on the World's incomes: 5% and 95% linear quantile regressions, Q̂ = 0.03, coverage 90.2%. By age group CQR ranges 88.2%–91.2%, against 83.4%–95.8% for the fixed-width band; its width runs from 59 (18–24) to 120 (55–66).
  • Under shift.

    • Weighted conformal (Tibshirani, Barber, Candès & Ramdas 2019), with test ages tilted to 40–60 and 200 repetitions: unweighted q̂ = 42.5 covers 87.1%; weighted q̂ ≈ 47.6 covers 90.3%. Calibration and test cases are independent draws with replacement from the World population; weights are known density ratios and P(Y|X) remains unchanged.
    • Estimating w by a classifier; nonexchangeable conformal (Barber et al. 2023).
    • Adaptive conformal inference (Gibbs & Candès 2021) on a stream whose noise triples for t = 1,000–2,000:
      • static split conformal covers 74.6% overall and 44.8% in the storm;
      • ACI with γ = 0.01 covers 90.0% overall and 89.5% in the storm;
      • The deterministic long-run bound under the stated extreme-quantile conventions; it does not imply local or conditional coverage.
  • Classification sets. LAC (Sadinle, Lei & Wasserman 2019) and APS (Romano, Sesia & Candès 2020).

    • Randomized APS uses the same auxiliary uniform in calibration and candidate scoring and can give an empty set; smallest-set oracle claims concern known true probabilities, not a universal property of fitted estimates.
    • Irises, sepals only, QDA (75.8% accurate), 300 splits: coverage 91.2%. Set sizes 0/1/2/3 occur 2.3%, 50.9%, 46.5% and 0.4% of the time. Mean size is 1.00 for setosa, 1.71 for versicolor and 1.64 for virginica.
    • Coverage by species is 93.0%, 91.4% and 89.7% with one threshold; Mondrian gives 94.1%, 92.8% and 93.9%.
    • Breast cancer, logistic on three features, 95% LAC sets (200 splits): coverage 95.3% (benign 96.4%, malignant 93.6%); one label 97.4%, both 0.4%, empty 2.3%.
    • Conformal p-values with BH (Bates et al. 2023).
  • Prediction-powered inference (Angelopoulos, Bates, Fannjiang, Jordan & Zrnic 2023), on the World's mean systolic blood pressure (truth 123.69 mm Hg).

    • 300 clinic visits (mean of three cuff readings); 20,000 smartwatch guesses. The watch is a forest on age, sex, BMI and a pulse-wave signal (pressure + N(0, 9²)), trained on 2,000 users aged 18–50. Its correlation with the truth is 0.86, but it reads 2.9 low overall and 151 → 136 for the over-80s.

    • One draw:

      Estimate Value 90% interval
      classical 123.22 [121.64, 124.81]
      naive 120.76 [120.61, 120.90]
      PPI 124.02 [123.18, 124.86]
    • Mean SE: 1.00 classical against 0.536 PPI and 0.536 PPI++; the PPI++ precision ratio makes 300 visits act like ≈ 1,045. Samples are independent representative draws with replacement from all adults with recorded cuff outcomes; the target is the fixed empirical World population, including training members, with predictions fixed before the study draws. Fixed-function, fixed-weight mean unbiasedness is distinguished from asymptotic Wald inference and estimated-weight PPI++.

    • A loose strap (extra noise, SD 25): classical 1.00, PPI 1.55, PPI++ (λ̂ ≈ 0.23) 0.92.

    • The survey sampling lineage: the difference estimator (Cassel, Särndal & Wretman 1976; Breidt & Opsomer 2017).

  • Interpretation as estimation.

    • Friedman 1 plus a twin of x₁ (correlation ≈ 0.97), forest of 200 trees.
    • The PDPs of x₄ and x₃ against the truth.
    • Permutation importance gives x₁ 3.49 and the twin 1.96; LOCO gives 0.42 and 0.04 (Hooker, Mentch & Zhou 2021; Williamson et al. 2021).
    • Exact Shapley values over five features: +1.04, +1.54, +0.24, +2.93, −0.20, summing from 14.74 to 20.30 (Shapley 1953; Lundberg & Lee 2017). This is a five-player game with the other six features averaged over the 120-case background; 20.30 is its grand-coalition value, not the full eleven-feature prediction 21.14. Signed importance estimates and partial-dependence values are retained rather than clamped.
  • Outro. Caruana et al. (2015): a pneumonia-mortality model with a misleading association between asthma and lower observed risk; intensive care is a proposed mechanism, not a causal effect established by that association.

Data:

  • the Wisconsin breast cancer data (Wolberg, Street & Mangasarian 1995), Fisher's irises and the diabetes data are the Museum's;
  • incomes and blood pressure are the World's;
  • the rest are seeded simulations, mostly on Friedman's (1991) test function.

Built in this part:

  • statkit.conformal (explainer/stats/kit/conformal.py):
    • Trees and ensembles: CART with cumulative-sum split search and impurity gains; random forests (bootstrap or subsampled) with OOB predictions, permutation importance and the bias-corrected infinitesimal jackknife (Wager, Hastie & Efron), with a subsampled CART teaching variant distinct from Wager–Athey honest forests; L2 boosting.
    • Calibration: reliability diagrams and ECE; Platt, isotonic (PAVA) and temperature scaling.
    • Conformal: the conformal quantile, split conformal, jackknife+/CV+, CQR, weighted conformal, adaptive conformal inference, APS scores and sets, Mondrian quantiles, conformal p-values.
  • statkit.ppi (explainer/stats/kit/ppi.py): classical, naive and prediction-powered means (PPI++'s tuned λ), and PPI least squares with its sandwich variance.
  • Both are checked in tests/test_stats_kit_conformal.py:
    • the conformal quantile's exact coverage;
    • jackknife+ and CQR coverage;
    • trees and forests: OOB, permutation importance, the IJ for bootstrap and subsampled forests;
    • PPI's unbiasedness and its gain over the classical estimate;
    • the score ladder.
  • The Museum gains breast_cancer().
  • The score ladder (ScoreLadder in explainer/stats/viz.py).

The Coverage Board gains fourteen rows, all with nominal 90%. Rows whose replications each average many test points retain the actual replication count and an empirical standard error from independent per-replication coverage fractions, rather than inventing independent test draws:

Method Setting Achieved Verdict
split conformal, 90% World incomes, cubic in age, n_cal = 500 90.0% kept
CQR, 90% World incomes, cubic in age, n_cal = 500 89.8% kept
in-sample residuals, 90% least squares, p = n = 100 0.0% broken
jackknife+, 90% least squares, p = n = 100 89.3% kept
split conformal, unweighted test ages shifted to 40--60 86.9% broken
weighted conformal, 90% test ages shifted to 40--60 90.2% kept
classical, 300 clinic visits World blood pressure, 90% 89.2% kept
watch guesses as data World blood pressure, 20,000 guesses 0.0% broken
prediction-powered World blood pressure, 90% 87.2% kept
PPI++ (tuned λ) World blood pressure, 90% 87.2% kept
forest IJ, bootstrap, for E f̂(x₀) Friedman 1, n = 250, 500 trees 60.3% broken
forest IJ, subsampled, for E f̂(x₀) Friedman 1, s = 50 of 250 83.7% broken
forest IJ, subsampled, for μ(x₀) Friedman 1, at a peak 0.0% broken
naive 10-fold CV interval, 90% least squares, n = 100, p = 20: for Err 82.8% broken
Chapter notes
# Chapter Numbers
0 The two cultures 98% vs 2%; a forest at 94.1%
1 Explain or predict? 5 root features, 39 top-three lists
2 Forests ρ 0.128 → 0.024; IJ covers 60% / 84%
3 Boosting ν = 0.1: 2.64 vs ν = 1: 6.63
4 What cross-validation estimates corr 0.013; naive CI 82.8%
5 Calibration ECE 0.062 → 0.038; T̂ = 7.9
6 Split conformal 90.4%; 95.8% vs 83.4% by age
7 Jackknife+ and CQR p = n: 0%, 53%, 95%
8 Under shift 87.1% → 90.3%; ACI 44.8% → 89.5%
9 Classification sets 91.2%; sizes 1.00 vs 1.71
10 Prediction-powered inference 300 visits ≈ 1,045
11 Interpretation as estimation permutation 3.49 / 1.96 vs LOCO 0.42 / 0.04
12 Outro asthma and pneumonia

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Breiman (2001), "The Two Cultures", and the replies of Cox and Efron.
  2. Explain or predict? The Rashomon effect; Shmueli (2010).
  3. Forests. The variance ρσ² + (1 − ρ)σ²/B; consistency (Scornet, Biau & Vert 2015); permutation importance's bias; IJ intervals (Wager, Hastie & Efron 2014) (Board).
  4. Boosting as stagewise additive modelling (Friedman, Hastie & Tibshirani 2000).
  5. What CV estimates; nested CV.
  6. Calibration. Reliability; Platt, isotonic, temperature scaling.
  7. Split conformal (Papadopoulos et al. 2002; Lei et al. 2018). The quantile lemma; coverage in [1 − α, 1 − α + 1/(n
    • 1)] (Board).
  8. Jackknife+ and CV+ (Barber et al. 2021); CQR (Romano, Patterson & Candès 2019).
  9. Under shift. Weighted conformal (Tibshirani et al. 2019) (Board); adaptive conformal online (Gibbs & Candès 2021).
  10. Classification sets (Romano, Sesia & Candès 2020).
  11. Prediction-powered inference (Angelopoulos et al. 2023); PPI++ (Board).
  12. Interpretation as estimation. Partial dependence, SHAP, LOCO.
  13. Outro. Asthma and pneumonia (Caruana et al. 2015); upgrade card for Part 57.

Built: statkit.conformal and statkit.ppi.

Build the film

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

Scenes: videos/stats/stats34. 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.stats34.compute    # once (about forty minutes; single-threaded BLAS is faster here)
python tools/build.py stats34 -q l                          # fast 480p preview
python tools/build.py stats34                               # 1080p30 -> renders/stats34.mp4
python tools/qa_scene.py stats34 Split
python tools/lecture_length.py stats34 --floor 50