Stage II · Bachelor's: Methods
Part 19 of 65Learning from Data
How do you predict well, and how do you know how well you predict?
Hamilton and Madison both claimed twelve of the Federalist papers; in 1964 Mosteller and Wallace settle it from the rates of dull words such as 'upon', which is in every one of Hamilton's 51 papers and absent from 11 of Madison's 14. The part turns from parameters to prediction. Polynomials fitted to 30 points show training error falling while test error explodes, and the gap is the optimism 2σ²p/n. Test error splits into noise, squared bias and variance, simulated for k nearest neighbours, and cross-validation estimates it from the data in hand. Nearest neighbours, naive Bayes against logistic regression, trees with pruning, and ridge against the lasso are each tuned that way, and confusion matrices, ROC curves and calibration say what a classifier's errors cost. Naive Bayes then gives all twelve disputed papers to Madison; ridge logistic regression agrees on eleven and leans to Hamilton on No. 55. The part ends with leakage: features selected outside the cross-validation loop make pure noise look predictable.
What you need. Least squares (Part 12), logistic regression (Part 14) and cross-validation's first look (Part 16).
- Hook
- who wrote the disputed Federalist papers?
- Mathematics
- prediction error, CV, k-NN, naive Bayes vs logistic, trees, ridge and lasso, ROC
- Built
- statkit.learn
What you will be able to do
Bachelor's
- Explain why training error understates test error, and read a curve of both against model complexity.
- Run k-fold cross-validation to choose a tuning parameter, and read a confusion matrix and an ROC curve.
Master's
- Derive the bias-variance decomposition and the optimism of a linear fit.
- Derive the lasso's soft threshold and ridge's proportional shrinkage for an orthonormal design.
PhD
- State what k-fold cross-validation estimates, and explain why an interval of CV error plus or minus 1.96 fold standard errors undercovers.
Practice
- Keep every data-dependent step inside the cross-validation loop, and hold out a test set that is used once.
- Choose a classification threshold from the costs of the two errors rather than from accuracy.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 30 min · Master's 54 min · PhD 54 min · Practice 42 min.
- 0Hamilton or Madison? 1964Bachelor's3 min
- 1Prediction errorBachelor's6 min
- 2Bias and varianceMaster's4 min
- 3Cross-validationBachelor's4 min
- 4k-nearest neighboursBachelor's5 min
- 5Naive Bayes vs logistic regressionMaster's4 min
- 6TreesBachelor's4 min
- 7Ridge and lassoMaster's4 min
- 8Classification metricsBachelor's5 min
- 9The Federalist decidedPractice4 min
- 10Leakage and honest evaluationPractice8 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Hamilton or Madison? 1964Bachelor's3 min
In 1787 and 1788, eighty-five essays defended the new Constitution, most first appearing in New York newspapers urging the state to ratify the new Constitution. All were signed Publius. They were written by Alexander Hamilton, James Madison and John Jay, and as The Federalist they became a founding text of American government. But who wrote which? Hamilton, shortly before the duel that killed him, left a list of his authorship. Madison later left another. The lists disagreed about twelve papers.
Here are the eighty-five papers. By the consensus of historians, Hamilton wrote fifty-one, Madison fourteen, Jay five, and three were joint work. The twelve in gold are disputed: numbers forty-nine to fifty-eight, sixty-two and sixty-three. Historians had debated their authorship for a century and a half. Douglass Adair had already argued for Madison in 1944; statistical analysis later quantified the evidence. The two men wrote in the same formal style, on the same subjects, often with the same sentence lengths.
In the 1960s Frederick Mosteller and David Wallace tried something different: count the dullest words. Here are the rates of a few, per thousand words, in Hamilton's papers, in Madison's, and in the disputed twelve. Hamilton writes upon three times in every thousand words; Madison, almost never. Madison writes whilst; Hamilton writes while, and enough. Madison uses on and by far more. And on every one of these words, the disputed papers look like Madison's. Function words like these are used without thought, so they're habits rather than choices, and they don't depend much on the subject.
Paper by paper, upon alone nearly separates them. Hamilton used it in every one of his fifty-one papers, at rates from one to seven and a half per thousand words. Madison didn't use it at all in eleven of his fourteen. And ten of the twelve disputed papers have no upon at all. One word is a hint, not a verdict. But Mosteller and Wallace combined dozens of such words in a careful probability model, and reached a decision we'll reproduce in chapter nine.
This is a different kind of problem from most of the course so far. The goal isn't a parameter with an interval, but a prediction: given these word counts, who wrote this paper? The question that matters is how well a prediction rule works on cases it hasn't seen, and how to find that out without fooling ourselves.
Numbers: 51 Hamilton, 14 Madison, 5 Jay, 3 joint, 12 disputed; upon in 51/51 Hamilton papers, absent in 11/14 Madison and 10/12 disputed
1Prediction errorBachelor's6 min
Prediction starts from examples: pairs of inputs and outputs, from which we build a rule that predicts y from x. The training error measures how well the rule fits the examples it was built from. The test error measures what we actually care about: how well it predicts a new case, drawn from the same source, that it hasn't seen. For familiar fitting procedures, training error is optimistic on average. An individual test set can score better or worse, and the direction is not a universal property of every possible rule.
A small experiment where we know the truth: thirty points from a smooth curve, plus noise. The true curve is the gold one. Now fit polynomials by least squares. A straight line is too stiff: it misses the wave entirely. A cubic follows the truth closely. Degree five begins to wiggle. And degree twelve threads its way through the points, bending wildly between them and at the ends. It fits the thirty examples better than any of the others, and it would predict new points worst.
Here are the two errors for every degree from one to fourteen, on a log scale. The training error falls every time: more flexibility always fits the examples better. The test error, measured on five thousand fresh points, falls at first, then turns and soars. It's smallest at degree three, point one oh. The dashed line is the noise variance, point oh nine: the unpredictable part, which no rule can remove. The cubic is close to it. At degree fourteen, the training error is point oh four, below the noise, as can happen even for a well-specified fitted model, and the test error is three hundred and forty-six.
Why is there a floor? Think of y as a signal f of x plus independent, mean-zero noise with conditional variance sigma squared at every input. The expected error at a point splits into the noise variance plus the squared distance between the rule and the true signal, because the new point's noise is independent of everything the rule learned. The first term is irreducible. Fitting uses some of the training noise, so training error can fall below the noise variance even without excessive flexibility. That alone does not establish harmful overfitting; new-data performance is what matters.
How optimistic is the training error, exactly? Bradley Efron's covariance formula answers: for fresh independent responses at the same fixed training inputs, the expected gap between prediction and training error is two over n times the sum of the covariances between each fitted value and its own observation. A rule that follows its data closely has large covariances. For least squares with p terms, the sum is sigma squared times the trace of the hat matrix, which is p, so the optimism is two sigma squared p over n. Add it back and you have Colin Mallows' C p, from 1973: an estimate of same-input prediction error from the training data alone. This is a Cp-style risk score; the traditional dimensionless Cp uses a different rescaling. Akaike's information criterion is the same idea for likelihoods. It also sharpens the warning sign of a moment ago: even the well-performing cubic approximation, has training error point oh seven one, below the noise variance, because fitting four coefficients absorbs noise. The true signal here is sinusoidal, so the cubic also has approximation error.
Here are the two curves again, with the Cp-style score in gold, computed from the thirty training points and the known noise variance. The blue curve is the exact expected risk at those same fixed inputs, averaged over new training noise and new response noise. It follows the test error at low degrees and chooses degree three, as the test error does. But it misses the explosion at high degree: the two curves target different predictions. The covariance penalty concerns fresh responses at the same fixed inputs; our red test curve uses new random inputs, including gaps between training points. High-degree polynomials can be unstable in those gaps. Even with a misspecified signal, the known-variance penalty is valid for the fixed-design linear projection. Cross-validation can assess new-case performance by holding out inputs as well as responses.
So: Within these nested, unpenalized least-squares polynomial spaces, extra terms cannot increase the minimum training error. This example has the classical U-shaped test curve. Other problems and fitting methods can have different shapes. On the left, rules too stiff to follow the signal underfit; on the right, rules flexible enough to follow the noise overfit. So never judge a prediction rule by how well it fits the data it learned from. Next: where the U comes from.
Numbers: best degree 3 (test 0.100); degree 14: train 0.04, test 346; noise 0.09; cubic train 0.071; Cp picks degree 3
2Bias and varianceMaster's4 min
Start from chapter one: the expected test error at a point is the noise plus the expected squared distance between the rule and the truth. Here the expectation is over everything random, including the training set. Add and subtract the rule's average over training sets. The cross term vanishes, as in Part 9's mean squared error, and the error splits into three: noise, squared bias, and variance. Bias is how far the rule is from the truth on average; variance, how much it changes from one training set to another. Flexibility trades one for the other: in the classical examples, flexibility often lowers bias and raises variance. This is a useful pattern, not a monotonicity theorem for every method.
The usual picture is a dartboard, where each dart is the prediction at one point from a rule fitted to a different training set, and the bullseye is the truth. Low bias and low variance: a tight cluster on the bullseye. Low bias, high variance: centred on the bullseye, but scattered. High bias, low variance: tightly grouped, in the wrong place. And both at once. We never see the darts in practice, only one of them; that's what makes the trade-off hard to manage.
The trade-off can be computed exactly for the simplest of all rules. The k-nearest-neighbour prediction at a point averages the y values of the k training points closest to it. Conditional on the training inputs, its noise variance is sigma squared over k for independent, equal-variance errors. Random training inputs can add variation from the signal values of the selected neighbours. Its bias is the average of the true function over the neighbourhood, minus its value at the point, and larger neighbourhoods reach further away and can increase approximation bias, although cancellation or the signal shape can make that change nonmonotone. Small k is flexible; large k is stiff. k is the dial between bias and variance.
Simulate it: three thousand training sets of a hundred points from chapter one's curve, and the k-nearest-neighbour prediction at x equals a quarter, near the curve's peak. The dots show the conditional noise component, sigma squared over k. The blue curve includes the additional variation caused by random neighbour locations. The squared bias is negligible for small k and climbs steeply once the neighbourhood spreads over the peak. Their sum, plus the noise, is the U. Its bottom is at about twelve neighbours. Nobody would know that from one training set; the next chapter estimates it.
The same calculation covers a whole family. Many rules, nearest neighbours, Part 16's kernels, least squares itself, make fitted values that are fixed weighted sums of the observed y's: a matrix S times y. Then each fitted value's variance is sigma squared times the sum of its squared weights. The trace of S is the smoother's effective number of parameters, its degrees of freedom. For least squares it's the number of coefficients, the trace of Part 12's hat matrix; for k nearest neighbours, about n over k. Part 29 builds on this.
So: test error is noise plus squared bias plus variance. In this example, extra flexibility trades lower bias against higher variance; this is not a universal law. The best balance depends on the noise and the sample size, and with more data the variance falls, so more flexible rules pay. But bias and variance are never observed in practice. What we can estimate directly is the total, and that's cross-validation.
Numbers: 3,000 training sets of 100 at x₀ = 0.25; best k = 12 (total 0.098)
3Cross-validationBachelor's4 min
Part 16 introduced cross-validation; here it does its main job. Split the data into K folds; fit on all but one and predict the one left out, in turn. Do that for every setting of the dial, theta, and average the prediction losses. The spread of the K fold errors gives a rough standard error. Then choose the setting with the smallest cross-validated error. That's how nearly every tuning parameter in machine learning is chosen.
Here's cross-validation choosing k for nearest neighbours, from a single training set of a hundred. The ten-fold CV error, with bars of one standard error, has the U shape: high for k equal to one, falling, then rising as the rule gets too stiff. Because this is a simulation, we can also draw test error on 4,000 new cases of each rule, on four thousand new points. CV tracks it well. CV's minimum is at k equals eight. The truth's is at seven. From a single training set of a hundred, cross-validation found nearly the best rule.
But the CV curve is itself noisy, and near its bottom it's nearly flat, so its minimum is uncertain. A common convention, from the authors of the CART book in 1984, is the one-standard-error rule: choose the simplest model whose CV error is within one standard error of the minimum. Here that's k equals seventeen, a smoother rule than CV's choice of eight. And here it costs accuracy: test error on 4,000 new casess are point one four one against point one one nine. The rule protects against chasing noise in the CV curve, and buys simplicity; it doesn't promise a lower error, and on any one dataset it can be worse.
What exactly does cross-validation estimate? Stephen Bates, Trevor Hastie and Robert Tibshirani studied the difference between average procedure risk and the conditional risk of a particular fit. Their exact independence result concerns homoskedastic Gaussian least squares, not every learner. In general, K-fold CV evaluates fits trained on only K minus one folds, so its target also differs from a rule trained on the entire observed sample. And the usual standard error, the spread of the fold errors, treats the folds as independent, though they share most of their training data. Ignoring that dependence can make CV intervals too narrow, as the next simulation checks.
The Board: two thousand training sets of a hundred, each with ten-fold CV and an interval of plus or minus one point nine six fold standard errors, checked against test error on 4,000 new cases of the rule fitted to that training set. Coverage ninety point one five percent against the exact population risk: broken, modestly. Bates and colleagues propose a specialized nested procedure to estimate uncertainty, with improved coverage in their examples. Ordinary nested tuning, discussed later, is a different use of an outer loop and is not an automatic confidence-interval repair.
With one fold per observation, cross-validation is leave-one-out: often with small training-size bias, with variance that depends on the learner, and for linear smoothers computable from a single fit, as Part 16 showed. Five or ten folds are the usual compromise. The folds must respect the data's structure: blocks of time, as in Part 17's rolling origins; whole clusters, as in Part 18's towns. And every choice made with the data, including which variables to use, has to be repeated inside each fold, or the estimate leaks. Chapter ten shows how badly.
Numbers: CV picks k = 8 (test 0.119); one-SE k = 17 (test 0.141); true optimum k = 7 (0.117); Board 90.15%
4k-nearest neighboursBachelor's5 min
Nearest neighbours classify too. Here are six hundred adults from the World, by income and age, coloured by their vote. Shade each spot of the plane by the vote of its nearest neighbours. With one neighbour, the map is a patchwork: every point claims a little territory, noise included. It interpolates the training labels and can have high variance; that does not make its predictions at new points unbiased. With fifty-one neighbours, the map is smooth, and shows the real pattern: Blue's support grows with income. The vote is hard to predict from income and age alone, and the smoother map is honest about that.
Nearest neighbours rely on there being near neighbours, and in many dimensions there aren't. Spread data uniformly in a unit cube, and ask how big a sub-cube must be to hold ten percent of it. Its edge is point one to the power one over p. In one dimension, a tenth of the axis. In ten dimensions, seventy-nine percent of every axis. In a hundred, ninety-eight. A neighbourhood that holds enough points to average is no longer local at all. Richard Bellman called this the curse of dimensionality, in 1961.
Another way to see it: scatter five hundred random points in a cube, and compare one point's nearest neighbour with its average distance to the others. In one dimension the nearest point is three thousandths as far as the average. In a hundred dimensions it's eighty-one percent as far. Everyone is about equally distant, so the nearest neighbour is barely nearer than a random point, and averaging neighbours is little better than averaging everyone.
And irrelevant variables do real damage. Predict chapter one's curve, which depends on one variable, from that variable plus p minus one that are pure noise. With the relevant variable alone, ten nearest neighbours have a test error of point oh eight six, close to the noise. With ninety-nine irrelevant ones added, point four three, barely better than the point four five of simply predicting the average. The noise dimensions dominate the distances, so the neighbours aren't really neighbours in the dimension that matters. The remedies are to choose variables, or to use methods with more structure, like the linear models, trees and penalties that follow.
Nearest neighbours have one beautiful guarantee, in low dimensions. Take two classes, normal with means zero and one and a half, and the same spread. The best possible rule, the Bayes rule, knows the distributions and cuts halfway between the means. Its error is twenty-two point seven percent, and no rule can do better. One nearest neighbour knows nothing about normal distributions, yet as the data grows its error settles at thirty-one percent. Thomas Cover and Peter Hart proved in 1967 that this limit is never more than twice the Bayes error: two R star times one minus R star, here thirty-five percent. Half the information in the data, they put it, is in the nearest neighbour. And let k grow with n, here the square root of n, and the error falls toward the Bayes rate itself, twenty-two point six percent on this finite test sample at three thousand training points. Sample error can fall slightly below the population Bayes rate by chance. Charles Stone showed in 1977 that with IID observations in a fixed finite-dimensional Euclidean space, consistency holds as k tends to infinity while k over n tends to zero. High dimension can make the required sample size enormous; it affects the rate, rather than invalidating that fixed-dimension limit.
So nearest neighbours impose no parametric response model, while relying on the sampling assumptions and a meaningful distance: they just average locally. In low dimensions with plenty of data, that works remarkably well. In high dimensions, neighbourhoods stop being local. There, structure beats proximity: assumptions about the form of the rule, such as linearity or sparsity, buy back what the dimensions take away. Parts 29, 51 and 52 take this further.
Numbers: cube edge 0.79 at p = 10; distance ratio 0.003 → 0.81; 10-NN error 0.086 → 0.43; 1-NN 30.5% (limit 31.0%, bound 35.1%), √n-NN 22.6%, Bayes 22.7%
5Naive Bayes vs logistic regressionMaster's4 min
There are two ways to build a classifier. The generative way models how the data are produced within each class: how Hamilton's word counts are distributed, how Madison's are, and how common each author is. Bayes's rule, from Parts 2 and 15, then turns that into the probability of each author given the words. The discriminative way skips the words' distribution and models the probability of the class given the words directly. Part 14's logistic regression is the standard example.
Mosteller and Wallace's model was generative. In its simplest form: each word's count in a paper of length t is Poisson, with a rate that depends on the author, and the words are independent of each other. Then the log odds of Madison against Hamilton is a weighted sum of the word counts, each weighted by the log ratio of the two authors' rates, minus a term for the paper's length, plus the prior log odds. Treating the words as independent is the naive part, and it's false: words come in phrases. Fitting means estimating each author's rate for each of ninety-one words from the papers whose authors are known.
Here are the weights for the twelve words that discriminate most. Blue words are evidence for Madison: whilst, although, consequently, innovation. Red ones for Hamilton: while, enough, kind, upon. Each use of upon in a disputed paper multiplies the odds in favour of Hamilton by about seventeen, so a single occurrence counts for a lot. Common words like on and by carry smaller weights, but appear so often that they add up.
How good are they? Leave one known paper out, fit on the other sixty-four, and classify the one left out, sixty-five times. Poisson naive Bayes makes no errors. Logistic regression on the ninety-one word rates, with a ridge penalty to keep its ninety-two coefficients tame, also makes none. On the papers we can check, both are perfect: the function words really are fingerprints.
With fewer training papers, the two differ. Train naive Bayes, and logistic regression, on a few random known papers and test on the rest, two hundred times at each size. With six papers to learn from, naive Bayes misclassifies six percent, logistic regression eleven. Andrew Ng and Michael Jordan showed in 2002 that particular generative and discriminative models can have different sample-complexity regimes. Our fixed-penalty learning curves illustrate a possibility, not a guarantee that all generative models learn faster or all discriminative models eventually win.
A warning before we use it. On the disputed papers, our naive Bayes gives log odds, base ten, as large as twenty: odds of a hundred billion billion to one, which nobody should believe. Independence counts words that travel together as separate pieces of evidence, so the evidence is multiplied many times over. Naive Bayes often classifies well while its probabilities are wildly overconfident. Mosteller and Wallace knew this, and used negative binomial rates, careful priors and extensive checks of sensitivity, to assess how sensitive their odds were to the modelling assumptions. Our plug-in calculation also omits uncertainty in the estimated word rates.
Numbers: 91 words; LOO 0/65 errors each; 6 training papers: 6.1% vs 10.7%; upon odds factor about 17
6TreesBachelor's4 min
A tree asks a sequence of yes-or-no questions. At each step it considers every variable and every cut point, and picks the split that makes the two halves most homogeneous. Homogeneity is measured by squared error for a number, or by the Gini index for a class. The method, CART, was set out by Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone in 1984. Then it splits each half the same way, and so on: a greedy search, choosing the best split at each step rather than the best tree overall. A new case runs down the questions to a leaf, and gets the leaf's average or majority.
A small tree for the World's vote, grown from two thousand adults' income and age. Overall, thirty-nine percent vote Blue. The best first question is whether income is above thirty-one thousand. Below it, only a quarter vote Blue. Above it, forty-seven percent, and the next best question splits again on income, at seventy-six thousand: forty-three percent below, sixty-three above. Income dominates; age never earns a split this early. Read with majority rule, the leaves say Red, Red, Blue: only the richest group is predicted to vote Blue.
In the plane of income and age, the tree is a set of boxes. Every split is a cut parallel to an axis, here two cuts on income. Each box gets a single prediction. A deeper tree cuts the boxes again, perhaps by age within an income band, and so captures interactions without anyone specifying them: the effect of age can differ between rich and poor.
How big should the tree be? CART's answer is to grow it large, here with a maximum depth of six and a minimum leaf size of twenty, giving thirty-five leaves, because a split that looks useless can enable a useful one below it. Then prune, by penalizing size: the error plus alpha times the number of leaves. As alpha grows, the splits that buy the least improvement per leaf are collapsed first, the weakest links, giving a nested sequence of smaller and smaller trees. Our implementation uses cross-validation to choose a maximum leaf budget along these weakest-link paths. The pruning objective here is total Gini impurity, and the held-out score is misclassification error.
The cross-validated error for each pruned size: one leaf, a single guess for everyone, is worst; the minimum occurs at a budget of four leaves. Weakest-link pruning can remove several leaves at once, so the final tree actually has three. Larger budgets generally do worse in this example. On a thousand held-out adults, the pruned tree misclassifies thirty-five point nine percent, and the full thirty-five-leaf tree thirty-eight point five. Predicting Red for everyone would misclassify thirty-seven point six. So the tree helps only a little, which is the truth: in the World, income and age shift the odds of voting Blue, but most of the vote is individual. A good learner is honest about how little can be predicted; the unpruned tree, worse than guessing, is not.
Small trees can be readable and find interactions automatically. Numeric thresholds need no feature scaling; categorical variables still need suitable split rules or encoding. But they're unstable: change a few observations and the first split may move, and everything below it. That's chapter two's variance problem in its purest form. Bagging and random forests average trees fitted to resampled data. Boosting builds a sequential weighted sum, often fitting residuals or reweighted cases; these are related ensemble ideas, not identical algorithms. Breiman's random forests of 2001 and Friedman's gradient boosting of the same year are among the most accurate off-the-shelf predictors there are; Parts 54 and 64 take them up.
Numbers: splits at 31.4k (Blue 25.1%) and 76.4k (42.7% / 63.1%); CV selects a leaf budget of 4; weakest-link pruning gives 3 actual leaves; test 35.9% vs 38.5% (35 leaves); always Red 37.6%
7Ridge and lassoMaster's4 min
Linear models have their own dial. Ridge regression, proposed by Arthur Hoerl and Robert Kennard in 1970, uses centred responses and standardized predictors, leaving the intercept unpenalized. In per-observation units it minimizes squared error divided by two n, plus lambda over two times the squared coefficient norm. The solution adds n lambda to the diagonal of X prime X before inverting, so for positive lambda it is invertible even with collinear predictors and least squares falls apart. Lambda zero is Part 12's least squares; as lambda grows, the penalized coefficient vector tends to zero; individual coordinates need not change monotonically. The shrinkage adds bias and removes variance, chapter two's trade, and with many predictors or noisy data the trade is usually favourable.
Robert Tibshirani's lasso, of 1996, changes one thing: it penalizes the sum of the absolute values of the coefficients instead of their squares. The one-norm. The consequence is striking: as lambda grows, coefficients don't just shrink, many become exactly zero. So the lasso shrinks and selects variables at the same time, and produces a sparse model that can be read.
Why exact zeros? The picture explains it. In the plane of two coefficients, the least-squares estimate sits at the green dot, and the ellipses around it are contours of equal squared error. The lasso, in its equivalent constrained form, keeps the coefficients inside a diamond; ridge keeps them inside a circle. The solution is where the expanding ellipse first touches the region. For the circle, that's a smooth point where both coefficients are non-zero: shrunk, but both present. For the diamond, it's very often a corner, and at a corner one coefficient is exactly zero. Here the lasso keeps beta one and sets beta two to zero; ridge keeps a little of both. In many dimensions the diamond has many corners and edges, and the lasso lands on them constantly.
With standardized orthogonal predictors, X prime X equal to n I, and both losses in the per-observation units just stated, the rules act coefficient by coefficient, and their difference fits in one picture. The lasso soft-thresholds: any least-squares coefficient smaller than lambda becomes zero, and larger ones move toward zero by lambda. Ridge simply scales every coefficient by one over one plus lambda. So the lasso kills small effects and keeps large ones, slightly shrunk; ridge keeps everyone, all a little smaller.
Now a regression with twenty predictors, of which three really matter, in gold, and seventeen are noise, in grey. The lasso path traces every coefficient as lambda decreases from left to right on the negative log lambda axis. At the left, all are zero. As lambda falls, the three real effects enter first, one after another, and only later do the noise variables creep in. The ridge path, for comparison: every coefficient grows smoothly from zero together, with no mechanism that deliberately sets small coefficients exactly to zero.
Choose lambda by ten-fold cross-validation. The minimum keeps eight variables: the three real ones and five passengers, which give a slightly lower observed CV score but do not thereby establish a real prediction benefit. The one-standard-error rule chooses a larger lambda, and keeps three. Exactly the three real effects. Their estimates are shrunk toward zero, the lasso's bias, A least-squares refit removes the explicit shrinkage penalty, but it does not generally remove bias from data-dependent selection or validate ordinary post-selection intervals. Whether selection like this can be trusted in general, and what inference after it means, are questions for Parts 32 and 56.
Numbers: lasso (1.20, 0.00) vs ridge (1.05, 0.58) in the picture; CV keeps 8, one-SE keeps 3; true (3.81, −1.94, 1.61), fitted (3.15, −1.48, 1.48)
8Classification metricsBachelor's5 min
Fit a logistic regression for the World's vote on income and age, and classify two thousand held-out adults, predicting Blue when the probability exceeds a half. The confusion matrix counts the four outcomes. The accuracy is sixty-five percent. That sounds respectable until you notice that predicting Red for everyone scores sixty-three. Of the Blue voters, the rule finds only twenty-four percent: its recall, or sensitivity, from Part 2. Of those it calls Blue, fifty-seven percent are: its precision. With an unbalanced outcome, accuracy alone hides almost everything.
The threshold is a choice. Call Blue whenever the probability exceeds thirty-five percent. Recall rises from twenty-four to sixty-four percent: most Blue voters are now found. Precision falls from fifty-seven to forty-eight. And accuracy falls too, from sixty-five to sixty-one. Which is better depends entirely on what the two kinds of mistake cost: different applications place different costs on missed cases and false alarms; neither priority is universal. Decision theory, Part 45, makes the choice formal.
To see every threshold at once, plot the true positive rate against the false positive rate as the threshold sweeps from one to zero: the ROC curve, from Part 14. Our two thresholds are two points on it. The area under the curve is point six six. It's the probability that a random Blue voter gets a higher score than a random Red voter, plus half the probability of a tied score, Part 16's Mann–Whitney statistic again. Point five is guessing; one is perfect. Point six six says income and age carry real but limited information about the vote.
A second view plots precision against recall. Guessing gives precision equal to the share of Blue voters, thirty-seven percent, whatever the recall. The model's precision starts near eighty percent among the very highest scores, the richest adults, and falls toward the baseline as the threshold drops. When the positives are rare, a rare disease or a fraudulent transaction, this curve shows what the ROC curve can hide: how many of the flagged cases are real.
Finally, are the probabilities honest? Group the held-out adults by their predicted probability, ten groups of two hundred, and compare each group's average prediction with the share who actually voted Blue. The points lie close to the diagonal: when the model says forty percent, about forty percent vote Blue. That is a coarse check compatible with calibration, with sampling uncertainty; it does not establish calibration at every individual score. The Brier score, Part 14's mean squared error of the probabilities, is point two one five. A calibrated model's probabilities can be used directly for decisions. Chapter five's authorship model is a different prediction task. Its extreme probabilities need their own independent calibration check; accurate classifications alone do not validate those probabilities.
Calibration also settles the question we left open: where should the threshold go? Suppose a campaign phones the people it predicts will vote Blue. Missing a Blue voter costs c; a wasted call on a Red voter costs one. With equal costs, the empirical average cost in this held-out sample is smallest near a threshold of a half, as accuracy suggested. If a missed voter costs twice as much, the best threshold falls to about a third, and at five times, to about a sixth. Decision theory predicts exactly this. Call a person when the expected cost of not calling, c times p, exceeds the cost of calling, one minus p: that is, when p is above one over one plus c. The empirical minima are near, but not exactly on, the theoretical thresholds. Sampling variation and imperfect calibration can shift them. These curves are retrospective diagnostics; choose costs and thresholds using validation data before a final independent test. With naive Bayes's probabilities, the formula would put the threshold in the wrong place, however good the ranking.
So: accuracy hides imbalance, so always compare with the base rate. Recall and precision trade off through the threshold, which costs should set. The ROC curve and its area measure ranking quality, free of any threshold. Precision–recall curves matter when positives are rare. And calibration asks whether the probabilities themselves can be trusted.
Numbers: accuracy 65.2% (always Red 62.9%); recall 23.7% → 63.8%, precision 57.5% → 47.7% at t = 0.35; AUC 0.663; Brier 0.215; best t 0.43 / 0.34 / 0.17 for c = 1 / 2 / 5
9The Federalist decidedPractice4 min
Now the verdict. Train chapter five's Poisson naive Bayes on the sixty-five papers of known authorship, using ninety-one words. Its leave-one-out error on those papers is zero. Apply it to the twelve disputed papers, which played no part in training. We'll report the log odds in base ten: plus one means ten to one for Madison, minus one ten to one for Hamilton, with equal prior odds.
Here they are. Every one of the twelve disputed papers comes out for Madison, most by overwhelming margins. The exception is number fifty-five, where the evidence is weak: log odds of point six, about four to one. Remember chapter five's warning: naive Bayes counts correlated words as independent evidence, so these magnitudes are far too extreme. The broad direction is a useful model-dependent indication, and even the direction for fifty-five is uncertain.
A second opinion from the discriminative model: ridge logistic regression on the same word rates. Its probabilities are far more modest, between seventy-four and ninety-nine percent for Madison on eleven papers. On number fifty-five it leans the other way, thirty percent for Madison. Two reasonable methods agree on eleven papers and disagree on one. That's useful information: fifty-five is genuinely the hardest case, and any conclusion about it rests on the model.
Which words did the work? Averaged over the twelve papers, the biggest contribution comes from upon, or rather from its absence: Hamilton's papers would be expected to contain several, and these contain almost none. Next come Madison's heavy use of on and by, his fewer uses of to and would, and whilst. No single word decides it. Dozens of small, unconscious habits all point the same way, and that agreement is what makes the case.
A side check: the three joint papers, eighteen to twenty, which both men had a hand in. The classifier says Madison for all three. Their words look like his. That fits the historical account that Madison wrote them up from research notes the two shared. Where the record exists, the classifier agrees with it, which is some reassurance about where it doesn't.
Mosteller and Wallace's most important check was of robustness: does the answer depend on a few words? In blue, our verdicts with all ninety-one words. Now drop upon, the single strongest word, in teal. Eleven papers still favour Madison, by a little less. But number fifty-five flips, to about a hundred and fifty to one for Hamilton, before chapter five's discount. Drop whilst and there as well, in gold, and the picture is the same: eleven for Madison, one fragile paper, and just one leave-one-out error in sixty-five on the known papers. The eleven are robust; number fifty-five rests on one fact: no upon at all in two thousand words, where Hamilton would average about seven. Their original analysis also identified fifty-five as its weakest case; sensitivity here is a reason to report the modelling dependence.
Mosteller and Wallace's conclusion, in 1964, was that Madison wrote all twelve. Their weakest case was number fifty-five, as ours is, and even there their odds favoured Madison. They got there with more realistic negative binomial rates, priors built from other writings, and extensive checks of how the answer depended on each assumption. Historians now generally accept the verdict. It was one of the first large Bayesian analyses ever carried out, and one of the first triumphs of what we'd now call machine learning.
Numbers: log₁₀ odds 0.6 (No. 55) to 19.7; logistic P(Madison) 0.30 for No. 55, 0.74–0.99 otherwise; joint papers 28, 17, 9; without upon: 11 of 12, No. 55 at −2.2
10Leakage and honest evaluationPractice8 min
Here's an experiment, adapted from Hastie, Tibshirani and Friedman's textbook. Sixty people, two thousand measurements on each, like a gene-expression study, and a yes-or-no outcome. But every measurement is pure noise and the outcome is a coin flip. So there is nothing to learn: a rule that has not seen the new labels has expected accuracy one half on fresh people, with finite-sample variation. A natural analysis: first, keep the twenty measurements most correlated with the outcome, since two thousand is far too many. Then estimate the error of a five-nearest-neighbour classifier on those twenty, by five-fold cross-validation, exactly as chapter three taught.
Do it that way and cross-validation reports an error of eleven point three percent. A classifier that's right nearly nine times in ten, from pure noise. The right way puts the selection inside the loop: in each fold, choose the twenty measurements using only the four training folds, fit on those folds, and predict the fold that was held out. Now cross-validation reports fifty point one percent, which is the truth. Same data, same classifier, same folds. The only difference is whether the held-out people helped choose the measurements.
One data set could be a fluke, so here are a hundred, each pure noise. In red, the wrong way's estimates: every one far below fifty percent, most around ten. In green, the right way's: scattered around fifty, as an honest estimate from sixty people should be. This is not a contrived trap. In 2002 Christophe Ambroise and Geoffrey McLachlan showed that several published classifiers of cancer from gene expression reported near-zero error this way; done properly, the error was far higher.
Why does it happen? Among two thousand noise columns, a few correlate with the outcome by chance; with sixty people the top twenty have correlations between about point three and point four five. But those correlations were computed on all sixty people, including whoever later sits in the test fold. So in that fold the chosen columns still line up with the outcome: the chance pattern they were picked for includes those very people. Cross-validation then measures how well the rule remembers, not how well it predicts. The held-out fold was held out in name only.
Selection is one leak among many. Preprocessing: standardizing, filling in missing values or computing principal components on all the data, before splitting. The size of the effect depends on the data and preprocessing; it can be substantial. Selection, as we've just seen. Tuning on the test set: trying settings until the test error looks good, which turns the test set into a training set. Duplicates and groups: related records that violate the intended evaluation target, such as the same patient's scans on both sides when predicting for new patients. In closed-set authorship, known authors must occur on both sides; repeated fragments or closely related papers still need care. Time: using tomorrow's information to predict today, which a random split of a time series does quietly. And target leakage: a feature recorded because of the outcome, like a treatment that's only given once the disease is diagnosed. A model that uses it predicts perfectly in the data and uselessly in practice.
There's a subtler leak, which catches people who never touch the test set by hand. Picture a prediction competition with a leaderboard: you submit predictions, it reports your accuracy on a holdout of a thousand cases. Suppose the labels are coin flips, and you submit a thousand random guesses. Their scores scatter around fifty percent, and the best is fifty-five. Now combine the five hundred and thirteen that scored above fifty percent by majority vote. That one submission scores seventy-two point four percent on the leaderboard. On fresh labels, it is fifty point four, compatible with the fifty-percent population accuracy. Every score the leaderboard reported was honest; using them to choose and combine was not. Avrim Blum and Moritz Hardt described this attack in 2015, and Cynthia Dwork and colleagues showed how to build controlled reusable-holdout mechanisms, using calibrated randomization and limits on adaptive access; arbitrary noise alone is not a general guarantee.
Even a careful analysis leaks a little in one more way. Chapter three chose k by minimizing the cross-validated error and then, tempting as it is, one reports that minimum as the error of the chosen rule. Here are two hundred training sets of a hundred, with k tuned over nine values. The minimum of the CV curve averages point one oh seven five. The true test error of the rule it picks has exact population risk averaging about point one oh nine four. We integrate over a uniform future input and its independent noise, rather than using a finite reference test set. The minimum of several noisy estimates is biased down, the winner's curse again. Nested cross-validation separates tuning from evaluation: an outer loop holds out a fold, an inner loop tunes k on the rest, and the outer fold scores the tuned rule. It averages point one one five three, higher here, partly because each outer fit trains on eighty observations rather than a hundred. Smaller training size does not guarantee pessimism for every learner. Here the gap between the CV minimum and exact risk is about two percent; with thousands of settings, or a whole menu of models, it can be most of the reported accuracy.
So here is the discipline. Split the data first, into a part for fitting, a part for choosing among fits, and a test set, and lock the test set away before you look at anything. With little data, cross-validation plays the first two roles, nested if it must also report. Everything learned from data, scaling, selection, tuning, goes inside the loop. Split along the data's structure, so that whole people, whole authors, or whole stretches of time are held out together. And use the test set once, reporting its error with a standard error, since a test set of two hundred measures an error rate of twenty percent with a standard error of about three points. It's the same discipline as a preregistered trial. Part 10's garden of forking paths, and this chapter's leaks, are the same problem: the data has been used to choose what it is then asked to judge.
Mosteller and Wallace knew all this. They chose their discriminating words using some papers and checked them on others. And they found exactly what this chapter predicts: words chosen because they separated the authors separated them less well on fresh papers. They measured the selection effect and allowed for it. Our illustration fixes seventy function words and twenty-one additional markers drawn from the literature before fitting. Historical word selection used this same corpus, so zero leave-one-out errors are a conditional reproduction result, not pristine external validation of feature discovery. The lesson of the whole part, in a sentence: an error estimate is only as honest as the separation between what was learned and what it's tested on.
Numbers: 11.3% vs 50.1% (n = 60, p = 2,000, 100 data sets); best random guess 54.9%, vote 72.4% vs 50.4% fresh; min CV 0.1075, true 0.1094, nested 0.1153
Recap, problems, and the road aheadAll tracks3 min
Part nineteen in fourteen lines. Mosteller and Wallace told Hamilton from Madison by the rates of dull words like upon. Prediction has its own measure of success, the test error, and familiar fitted rules have optimistic training error on average. The Cp-style penalty estimates same-input prediction error under its stated assumptions. Test error splits into noise, squared bias and variance, and the effective degrees of freedom of a smoother is the trace of its matrix. Cross-validation estimates the prediction curve from one data set, with the one-standard-error rule for a simpler choice, though the Board found ninety point one five percent coverage for its nominal ninety-five percent interval. Nearest neighbours need no model but suffer the curse of dimensionality. Naive Bayes and logistic regression model the same odds from opposite ends; trees grow and are pruned; ridge and the lasso shrink, and the lasso's diamond sets coefficients to zero. Accuracy is one number among recall, precision, the ROC curve and calibration. Naive Bayes favoured Madison on all twelve disputed papers; ridge logistic agreed on eleven and favoured Hamilton on the fragile fifty-fifth. And selection outside the loop found eleven percent error in pure noise.
Where it comes back. Part 20, the bachelor's capstone, takes one analysis from question to report, with an honest held-out check. Part 28 compares the ways of choosing a model. Part 29 builds the smoothers whose degrees of freedom we met here. Part 32 takes the lasso deep. Part 34 turns prediction errors into intervals with guarantees. Parts 51 and 52 face the curse of dimensionality head on. Part 54 asks why test error can be bounded at all. And Part 56 makes inference honest after the data has chosen the model, which is chapter ten's problem in its general form.
Six problems, with full solutions in the README. The optimism of least squares, exactly; the bias and variance of nearest neighbours for a parabola; the size of a neighbourhood in ten and a hundred dimensions; the odds from a paper without upon; ridge and the lasso for a standardized orthogonal design; and the precision of a good test for a rare condition. Pause here if you want to try them.
The books and papers this part follows: An Introduction to Statistical Learning and The Elements of Statistical Learning, Mosteller and Wallace's book on the Federalist, and Breiman, Friedman, Olshen and Stone on trees, with the papers from Cover and Hart to Bates, Hastie and Tibshirani, and Leo Breiman's essay on the two cultures of statistical modelling.
Nineteen parts of sixty-five, the ninth of Stage II. We can now predict, and say honestly how well we predict. Next, the bachelor's capstone: no new method, but one real question taken all the way, from the data's origins through exploration, a model, its checks, and a held-out test, to a report a reader could trust. Part 20: the analysis.
Where it goes next. The held-out check is used in Part 20; AIC, BIC and cross-validation are compared in Part 28, smoothers return in Part 29, the lasso in Part 32, conformal prediction in Part 34, and learning theory bounds test error in Part 54.
Key results
The part's results in one place, for revision.
Try it
Lab 19 · Leakage: selecting features before cross-validation
Give 60 cases 2,000 noise features and coin-flip labels, keep the 20 features most correlated with the labels, and estimate a 5-nearest-neighbour classifier's error by 5-fold cross-validation twice: with the selection done once on all the data, and with it redone inside every fold.
python -m videos.stats.labs 19
needs numpy, scipy, matplotlib · download lab19.py ·
source on GitHubtrue error of any rule on coin-flip labels 50.0%
CV error, features selected before the loop 10.3% (± 0.5%)
CV error, features selected inside the loop 49.9% (± 1.0%)
leaky CV error at p = 20, 50, 200, 500, 2000 52% 42% 25% 18% 13%
Nothing here can be predicted, yet choosing the features with the held-out labels in view makes cross-validation report an error far below 50%; redoing the selection inside each fold reports the truth.
The code (80 lines; it asserts its own result)
"""Lab 19: cross-validate a classifier on pure noise, with the features chosen outside and then inside the loop."""
import numpy as np
from videos.coursekit import labs
from explainer.stats.kit import learn
TITLE = "Leakage: selecting features before cross-validation"
GOAL = ("Give 60 cases 2,000 noise features and coin-flip labels, keep the 20 features most correlated with the labels, "
"and estimate a 5-nearest-neighbour classifier's error by 5-fold cross-validation twice: with the selection "
"done once on all the data, and with it redone inside every fold.")
TASKS = [
"Lower p from 2,000 to 50 features. How much of the leak's optimism is left, and why?",
"Give the first three features a real effect (add 0.8 * y to them). Do the two estimates now agree more closely?",
"Replace the 5-nearest-neighbour vote by learn.logistic_ridge with lam = 1. Does the leak depend on the classifier?",
]
def top_features(X, y, keep):
Xc, yc = X - X.mean(0), y - y.mean()
c = np.abs(Xc.T @ yc) / np.sqrt((Xc ** 2).sum(0) * (yc ** 2).sum() + 1e-300)
return np.argsort(-c)[:keep]
def cv_errors(X, y, keep, rng):
"""(error with selection before the loop, error with selection inside the loop) for one data set."""
n = len(y)
chosen = top_features(X, y, keep) # the leak: the held-out labels helped to choose these
wrong = right = 0
for fold in learn.kfold(n, 5, rng):
train = np.setdiff1d(np.arange(n), fold)
wrong += np.sum(learn.knn_predict(X[train][:, chosen], y[train], X[fold][:, chosen], 5, classify=True) != y[fold])
inside = top_features(X[train], y[train], keep)
right += np.sum(learn.knn_predict(X[train][:, inside], y[train], X[fold][:, inside], 5, classify=True) != y[fold])
return wrong / n, right / n
def run(seed=0):
rng = np.random.default_rng(seed)
n, p, keep, reps = 60, 2000, 20, 60
lab = labs.Lab()
errs = np.array([cv_errors(rng.standard_normal((n, p)), (rng.random(n) < 0.5).astype(int), keep, rng)
for _ in range(reps)])
wrong, right = errs.mean(0)
se = errs.std(0, ddof=1) / np.sqrt(reps)
lab.row("true error of any rule on coin-flip labels", "50.0%")
lab.row("CV error, features selected before the loop", f"{wrong:.1%} (± {se[0]:.1%})")
lab.row("CV error, features selected inside the loop", f"{right:.1%} (± {se[1]:.1%})")
# how the leak grows with the number of features to choose from
ps = [20, 50, 200, 500, 2000]
curve = []
for q in ps:
e = np.array([cv_errors(rng.standard_normal((n, q)), (rng.random(n) < 0.5).astype(int), min(keep, q), rng)
for _ in range(20)])
curve.append(e.mean(0))
curve = np.array(curve)
lab.row("leaky CV error at p = 20, 50, 200, 500, 2000", " ".join(f"{v:.0%}" for v in curve[:, 0]))
assert wrong < 0.25, "the leak makes noise look predictable"
assert abs(right - 0.5) < 0.05, "honest cross-validation reports a coin flip"
assert curve[-1, 0] < curve[0, 0] - 0.15, "the more features to choose from, the larger the leak"
lab.note = ("Nothing here can be predicted, yet choosing the features with the held-out labels in view makes "
"cross-validation report an error far below 50%; redoing the selection inside each fold reports the truth.")
fig, ax = labs.figure(2, size=(11, 4.2))
bins = np.linspace(0, 0.8, 33)
ax[0].hist(errs[:, 0], bins=bins, color=labs.RED, alpha=0.7, label=f"selected before the loop: mean {wrong:.0%}")
ax[0].hist(errs[:, 1], bins=bins, color=labs.GREEN, alpha=0.7, label=f"selected inside the loop: mean {right:.0%}")
ax[0].axvline(0.5, color=labs.MUTED, ls="--", label="true error 50%")
ax[0].set(title=f"CV error on {reps} pure-noise data sets (n = 60, p = 2,000)", xlabel="5-fold CV error",
ylabel="data sets")
ax[0].legend(loc="upper left")
ax[1].plot(ps, curve[:, 0], "o-", color=labs.RED, label="selected before the loop")
ax[1].plot(ps, curve[:, 1], "o-", color=labs.GREEN, label="selected inside the loop")
ax[1].axhline(0.5, color=labs.MUTED, ls="--")
ax[1].set(xscale="log", ylim=(0, 0.7), title="The leak grows with the number of candidate features",
xlabel="noise features p (20 kept)", ylabel="mean CV error")
ax[1].legend(loc="lower left")
lab.fig = fig
return lab
Now change it
- Lower p from 2,000 to 50 features. How much of the leak's optimism is left, and why?
- Give the first three features a real effect (add 0.8 * y to them). Do the two estimates now agree more closely?
- Replace the 5-nearest-neighbour vote by learn.logistic_ridge with lam = 1. Does the leak depend on the classifier?
Problems, with solutions
Try each problem before opening its solution.
1. The optimism of least squares. OLS with \(p\) terms, fixed \(x\)'s: show \(E[\text{train}] = \sigma^2(1 - p/n)\) and \(E[\text{test at the same } x\text{'s}] = \sigma^2(1 + p/n)\).
Solution
Assume the model is right, so Xβ = f and the hat matrix H projects onto a p-dimensional space.
- Training error. The residual vector is (I − H)y = (I − H)ε, so E[RSS] = σ² tr(I − H) = σ²(n − p). Dividing by n gives E[train] = σ²(1 − p/n).
- Test error at the same x's. For new responses y* = f + ε*, E‖y* − Hy‖² = nσ² + E‖Hε‖² = nσ² + σ² tr H = σ²(n + p). So E[test] = σ²(1 + p/n).
The gap is 2σ²p/n, Mallows' penalty.
2. k-NN for a parabola. \(f(x) = x^2\), neighbours at \(x_0 + jh\), \(j = -m, \dots, m\): the bias and variance of \(k\)-NN, \(k = 2m + 1\).
Solution
The prediction at x₀ is the average of f(x₀ + jh) = x₀² + 2x₀jh + j²h² over j = −m, …, m. The middle term averages to zero.
- Bias. Since Σj² = m(m + 1)(2m + 1)/3, dividing by k = 2m + 1 gives bias = h²m(m + 1)/3, whatever x₀.
- Variance. σ²/k.
- MSE. h⁴m²(m + 1)²/9 + σ²/(2m + 1). The squared bias grows like k⁴ and the variance falls like 1/k.
3. Neighbourhoods in high dimensions. In \(p = 10\) dimensions, the edge of a cube holding 1% of uniform data; and in \(p = 100\).
Solution
The edge is e = 0.01^{1/p}. For p = 10, e = 0.01^{0.1} ≈ 0.63; for p = 100, e ≈ 0.955. To hold 1% of the data, the "neighbourhood" must span 63%, and then 95.5%, of every axis.
4. A paper without upon.
Solution
For a count x in t thousand words, the Poisson log likelihood ratio is log[P_M(x)/P_H(x)] = x log(r_M/r_H) − t(r_M − r_H). With x = 0 and t = 2, it is −2(0.18 − 3.3) = 6.24 nats, or 6.24/ln 10 ≈ 2.71 in base 10: about 500 to 1 for Madison from the absence of a single word. Hamilton would expect 6.6 uses in such a paper, and e^{−6.6} is tiny.
5. Ridge and the lasso for a standardized orthogonal design. Standardized orthogonal design \(X^\top X=nI\): show ridge gives \(\hat\beta / (1 + \lambda)\) and the lasso the soft threshold of \(\hat\beta\) at \(\lambda\).
Solution
Centre the predictors and response and let XᵀX = nI. Then β̂ = Xᵀy/n and SSE/(2n) = constant + ½||β − β̂||².
- Ridge. Adding (λ/2)||β||² and setting the gradient to zero gives β = β̂/(1 + λ).
- Lasso. Adding λ||β||₁ separates into ½(βⱼ − β̂ⱼ)² + λ|βⱼ|. The minimizer is sign(β̂ⱼ)(|β̂ⱼ| − λ)₊.
These use the same per-observation conventions as the scenes. The intercept is not penalized. With XᵀX = I and unnormalized loss, the effective penalty must be rescaled accordingly.
6. A good test for a rare condition. A test with sensitivity 90%, specificity 95%, base rate 1%: its precision, and its accuracy.
Solution
Per 10,000 people: 100 have the condition, of whom 90 test positive; 9,900 don't, of whom 495 test positive.
- Precision. 90/(90 + 495) ≈ 15.4%.
- Accuracy. (90 + 9,405)/10,000 = 94.95%, below the 99% of declaring everyone negative.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| a full analysis with an honest held-out check | 20 |
| AIC, BIC and CV compared | 28 |
| smoothers and their degrees of freedom | 29 |
| the lasso in depth | 32 |
| prediction intervals with guarantees (conformal) | 34 |
| the curse of dimensionality, in theory | 51, 52 |
| why test error can be bounded: learning theory | 54 |
| inference after the data chose the model | 56 |
| the Coverage Board | every part; 65 |
Glossary
- Training error, test error: average loss on the data a rule learned from, and on new data from the same source.
- Overfitting, underfitting: a rule that follows the noise; a rule too stiff to follow the signal.
- Optimism; covariance penalty; Cp; AIC: the expected gap between test and training error, and estimates of test error that add it back.
- Bias–variance decomposition: expected test error = noise + bias² + variance, at each x.
- Linear smoother; effective degrees of freedom: a fit ŷ = Sy; df = tr S.
- Tuning parameter: a setting chosen from the data (k, a degree, λ).
- K-fold and leave-one-out cross-validation: estimating test error by fitting without each fold in turn.
- One-standard-error rule: choose the simplest model within one SE of the best CV error.
- Nested cross-validation: tuning inside an inner loop, scoring in an outer one.
- k-nearest neighbours: predict by averaging (or voting among) the k closest training cases.
- Curse of dimensionality: in many dimensions, neighbourhoods are no longer local and distances concentrate.
- Bayes rule, Bayes error: the best possible classifier when the distributions are known, and its error.
- Generative vs discriminative: modelling p(x | y) and p(y), or P(y | x) directly.
- Naive Bayes: a generative classifier that treats features as independent within each class.
- Classification tree (CART); impurity; cost-complexity pruning: recursive axis-parallel splits, scored by Gini or squared error, cut back by a penalty α per leaf.
- Ridge regression; the lasso; soft thresholding: ℓ₂ and ℓ₁ penalties on coefficients; the lasso's coordinate update.
- Confusion matrix; recall (sensitivity); precision; specificity: the four outcomes of a classifier and the rates built from them.
- ROC curve; AUC: recall against false-positive rate across thresholds, and the area under it.
- Precision–recall curve: precision against recall across thresholds, for rare positives.
- Calibration; Brier score: predicted probabilities that match observed frequencies; their mean squared error.
- Leakage: information from the evaluation data reaching the fitted rule (preprocessing, selection, tuning, duplicates, time, target).
- Holdout reuse; adaptive overfitting: a test set that degrades as its scores guide choices.
Sources
- The Federalist.
- F. Mosteller & D. Wallace, JASA 58 (1963); Inference and Disputed Authorship: The Federalist (1964).
- D. Adair, "The authorship of the disputed Federalist papers", William and Mary Quarterly 1 (1944).
- The texts: Project Gutenberg, eBook 18.
- Prediction error and model choice.
- C. Mallows, Technometrics 15 (1973); H. Akaike (1973).
- B. Efron, JASA 81 (1986) and JASA 99 (2004).
- M. Stone, JRSS B 36 (1974); S. Geisser, JASA 70 (1975).
- S. Bates, T. Hastie & R. Tibshirani, JASA 119 (2024; arXiv 2021).
- S. Geman, E. Bienenstock & R. Doursat, Neural Computation 4 (1992).
- Methods.
- T. Cover & P. Hart, IEEE Trans. Inf. Theory 13 (1967); C. Stone, Ann. Stat. 5 (1977); R. Bellman, Adaptive Control Processes (1961).
- A. Ng & M. Jordan, NIPS 14 (2002).
- L. Breiman, J. Friedman, R. Olshen & C. Stone, Classification and Regression Trees (1984).
- A. Hoerl & R. Kennard, Technometrics 12 (1970); R. Tibshirani, JRSS B 58 (1996).
- L. Breiman, "Statistical modeling: the two cultures", Statistical Science 16 (2001).
- Leakage.
- C. Ambroise & G. McLachlan, PNAS 99 (2002).
- S. Kaufman, S. Rosset, C. Perlich & O. Stitelman, ACM TKDD 6 (2012).
- A. Blum & M. Hardt, ICML (2015); C. Dwork et al., Science 349 (2015).
- Books.
- G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning (2nd ed., 2021).
- T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning (2nd ed., 2009), §7.10.2 for the wrong and right way to cross-validate.
About this partfrom its README
Part 19 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Until now the goal was a parameter: a mean, a slope, an effect. This part turns to prediction: how to predict well, and how to know how well you predict.
It opens with the Federalist papers of 1787–88. Hamilton, Madison and Jay all signed them "Publius", and twelve
were claimed by both Hamilton and Madison. Mosteller and Wallace (1964) settled the question with the rates of dull
words. upon appears in every one of Hamilton's 51 papers, at 1.0–7.5 per 1,000 words. It is absent from 11 of
Madison's 14 and from 10 of the 12 disputed papers. The texts come from Project Gutenberg, counted by
tools/federalist_counts.py.
From there the part covers:
- Prediction error. Training and test error; polynomials of degree 1–14 fitted to 30 points.
- Test error is smallest at degree 3 (0.100), against a noise variance of 0.09.
- At degree 14, the training error is 0.04 and the test error 346.
- Efron's covariance penalty and the optimism 2σ²p/n, derived.
- Mallows' Cp also picks degree 3, but misses the explosion at high degree.
- Bias and variance. Test error = noise + bias² + variance, derived and simulated for k-NN at a point.
- 3,000 training sets; best k = 12.
- Variance σ²/k; df = tr S for linear smoothers.
- Cross-validation.
- 10-fold CV of k picks k = 8 (test error 0.119); the true optimum is k = 7.
- The one-SE rule picks k = 17 (test error 0.141).
- What CV estimates (Bates, Hastie & Tibshirani, online 2023 / volume 2024), with a Board row; leave-one-out.
- k-nearest neighbours.
- Regions for the World's vote with k = 1 and k = 51.
- The curse of dimensionality: a cube holding 10% of the data has edge 0.79 in 10 dimensions. The ratio of nearest to average distance rises from 0.003 to 0.81.
- With irrelevant dimensions, 10-NN error rises from 0.086 to 0.43, against 0.45 for predicting the mean.
- Cover & Hart (1967): 1-NN settles at 31.0%, below the bound of 35.1%. √n-NN falls to 22.6%, close to the Bayes error of 22.7%.
- Naive Bayes vs logistic regression.
- Generative vs discriminative; the Poisson log odds as a weighted word count.
- Leave-one-out: 0 errors in 65 for each.
- Learning curves: with 6 training papers, 6.1% vs 10.7% (Ng & Jordan 2002).
- Naive Bayes is overconfident.
- Trees. CART on the World's vote from income and age.
- Splits at incomes of 31.4k and 76.4k.
- Cost-complexity pruning; CV selects a leaf budget of 4; weakest-link pruning gives 3 actual leaves.
- Test error 35.9% pruned vs 38.5% for the full 35-leaf tree; always guessing Red scores 37.6%.
- Ridge and the lasso.
- The ℓ₁ diamond against the ℓ₂ disc (
L1Geometry). - Soft thresholding and proportional shrinkage.
- Paths for 20 predictors, 3 of them real. CV keeps 8 variables; the one-SE rule keeps exactly the 3 real ones.
- The ℓ₁ diamond against the ℓ₂ disc (
- Classification metrics.
- Confusion matrices at thresholds 0.5 and 0.35: recall 23.7% → 63.8%, precision 57.5% → 47.7%.
- ROC (AUC 0.663), precision–recall, calibration (Brier 0.215).
- Choosing a threshold from costs: t* = 1/(1 + c), found empirically at 0.43, 0.34 and 0.17.
- The Federalist decided.
- Naive Bayes favours Madison on all 12; No. 55 is the weakest, at log₁₀ odds 0.6.
- Ridge logistic gives P(Madison) = 0.30 for No. 55 and 0.74–0.99 for the other eleven.
- The joint papers come out Madison's.
- Robustness: dropping upon flips No. 55 (log₁₀ odds −2.2) and leaves the other eleven for Madison.
- Leakage and honest evaluation.
- Selecting 20 of 2,000 noise features before CV gives 11.3% error; selecting inside the loop gives 50.1%.
- A catalogue of six leaks.
- A reused holdout: the vote of 513 random guesses scores 72.4% on the leaderboard and 50.4% on fresh labels.
- The optimism of the CV minimum, against nested CV.
- The train / validate / test discipline.
Every number on screen is computed in compute.py or inline in a scene:
- word counts are the Museum's Federalist;
- the vote, incomes and ages are the World's survey block;
- everything else is a seeded simulation with a known truth (y = sin 2πx + x/2 + N(0, 0.3²) for the regression examples).
Built in this part:
statkit.learn(explainer/stats/kit/learn.py), checked intests/test_stats_kit_learn.py:- K-fold splits, CV scores with fold SEs, and the one-SE rule;
- k-NN regression and classification;
- Poisson naive Bayes with per-word contributions;
- ridge logistic regression;
- CART growing, cost-complexity pruning paths and pruning;
- standardization, ridge, soft thresholding, and the lasso by coordinate descent with its path;
- confusion matrices, precision–recall curves and AUC.
- The ℓ₁ geometry (
L1Geometryinexplainer/stats/viz.py): least-squares contours with the lasso's diamond and ridge's disc, and the point where they first touch.
The Coverage Board gains one row: a 95% interval for test error.
| Method | Setting | Reps | Achieved | Verdict |
|---|---|---|---|---|
| 10-fold CV ± 1.96 SE | k-NN test error, n = 100 | 2,000 | 90.15% | broken |
Chapter notes
| # | Chapter | Numbers |
|---|---|---|
| 0 | Hamilton or Madison? 1964 | 51 Hamilton, 14 Madison, 5 Jay, 3 joint, 12 disputed; upon in 51/51 Hamilton papers, absent in 11/14 Madison and 10/12 disputed |
| 1 | Prediction error | best degree 3 (test 0.100); degree 14: train 0.04, test 346; noise 0.09; cubic train 0.071; Cp picks degree 3 |
| 2 | Bias and variance | 3,000 training sets of 100 at x₀ = 0.25; best k = 12 (total 0.098) |
| 3 | Cross-validation | CV picks k = 8 (test 0.119); one-SE k = 17 (test 0.141); true optimum k = 7 (0.117); Board 90.15% |
| 4 | k-nearest neighbours | cube edge 0.79 at p = 10; distance ratio 0.003 → 0.81; 10-NN error 0.086 → 0.43; 1-NN 30.5% (limit 31.0%, bound 35.1%), √n-NN 22.6%, Bayes 22.7% |
| 5 | Naive Bayes vs logistic | 91 words; LOO 0/65 errors each; 6 training papers: 6.1% vs 10.7%; upon odds factor about 17 |
| 6 | Trees | splits at 31.4k (Blue 25.1%) and 76.4k (42.7% / 63.1%); CV selects a leaf budget of 4; weakest-link pruning gives 3 actual leaves; test 35.9% vs 38.5% (35 leaves); always Red 37.6% |
| 7 | Ridge and the lasso | lasso (1.20, 0.00) vs ridge (1.05, 0.58) in the picture; CV keeps 8, one-SE keeps 3; true (3.81, −1.94, 1.61), fitted (3.15, −1.48, 1.48) |
| 8 | Classification metrics | accuracy 65.2% (always Red 62.9%); recall 23.7% → 63.8%, precision 57.5% → 47.7% at t = 0.35; AUC 0.663; Brier 0.215; best t 0.43 / 0.34 / 0.17 for c = 1 / 2 / 5 |
| 9 | The Federalist decided | log₁₀ odds 0.6 (No. 55) to 19.7; logistic P(Madison) 0.30 for No. 55, 0.74–0.99 otherwise; joint papers 28, 17, 9; without upon: 11 of 12, No. 55 at −2.2 |
| 10 | Leakage and honest evaluation | 11.3% vs 50.1% (n = 60, p = 2,000, 100 data sets); best random guess 54.9%, vote 72.4% vs 50.4% fresh; min CV 0.1075, true 0.1094, nested 0.1153 |
| 11 | Outro | — |
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: Mosteller & Wallace (1964). Hamilton or Madison? Word rates as features (texts from Gutenberg).
- Prediction error. Training vs test error; overfitting with polynomial degree.
- Bias and variance. The decomposition, derived for k-NN and linear smoothers.
- Cross-validation. k-fold and LOO; the one-SE rule.
- k-nearest neighbours. The curse of dimensionality, first look.
- Naive Bayes vs logistic regression. Generative vs discriminative (Ng & Jordan 2002).
- Trees. Recursive partitioning (CART); pruning.
- Ridge and lasso, first look. Shrinkage; the diamond (
L1Geometry); Part 32 goes deep. - Classification metrics. Confusion matrices, ROC, precision–recall, calibration.
- The Federalist decided. Our classifiers on the disputed papers, with CV error.
- Leakage and honest evaluation.
- Outro.
Built: statkit.learn. Data: the Federalist (Gutenberg).
Build the film
python -m videos.stats.stats19.compute # the part's numbers, into .cache/stats19
python tools/build.py stats19 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats19 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats19. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats19.compute # once (a few minutes; cached in .cache/stats19)
python tools/build.py stats19 -q l # fast 480p preview
python tools/build.py stats19 # 1080p30 -> renders/stats19.mp4
python tools/qa_scene.py stats19 Leakage
python tools/lecture_length.py stats19 --floor 50