AAI, Built

Act II · Learning from Data

Part 6 of 31

Classical ML

Undergraduatestarts at this level51 min of film19 chaptersprerequisites: Part 1, Part 3, Part 4, Part 5

Given a page of a novel, how can a machine learn from examples who wrote it?

The part opens with a 1,000-word page and one task: Austen or Dickens? Each of 639 pages from five novels is described, as Mosteller and Wallace described the Federalist papers, by how often it uses the 70 commonest words, and 191 pages are held out. Every classical method is then written in numpy and run on the pages. Least squares is derived as a projection and shown best among linear unbiased estimators; ridge shrinks it along the weak singular directions and the lasso sets weights exactly to zero. Logistic regression gives probabilities, Newton's method solves it in 8 steps, and on the separable 70-rate pages its weights grow without end. Naive Bayes, Fisher's direction, nearest neighbours and the curse of dimensionality, kernels and the support vector machine, trees, bagging, random forests, AdaBoost and second-order gradient boosting follow, each derived and measured. The part turns to keeping score: ROC area, calibration, log loss and cross-validation. It ends with twelve procedures on the same ten folds, Breiman's two cultures, and why trees and now tabular foundation models win on tables.

What you need. Calculus and matrix algebra; the projection and SVD of Part 3 and the Lagrange multipliers of Part 4.

Mathematics and history
least squares, ridge and lasso, logistic regression, LDA, k-NN, kernels and SVMs, trees, forests, boosting
Models, data
Viola–Jones

What you will be able to do

Undergraduate

  • Fit a line by least squares and a classifier by logistic regression, and read the fitted weights as a rule for telling two authors apart.
  • Explain how k nearest neighbours and a decision tree classify a page, and why accuracy on the training pages overstates accuracy on new ones.

Master's

  • Derive ridge's shrinkage factors through the SVD and the lasso's soft threshold from subgradients.
  • Derive the logistic gradient and Hessian, and show that a Newton step is a weighted least-squares fit.
  • Derive the bagging variance formula, AdaBoost's step size from the exponential loss, and XGBoost's leaf weight and split gain.

Research

  • Prove the Gauss-Markov theorem and the representer theorem, and state what each assumes.
  • State Mercer's condition and decide whether a given kernel's Gram matrices can have negative eigenvalues.

Engineering

  • Compare classifiers on the same cross-validation folds, reporting ROC area, log loss and calibration as well as accuracy.
  • Choose a penalty, a depth or a number of rounds on training folds only, and say when a tree ensemble is the right default for a table.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 16 min · Master's 47 min · Research 51 min · Engineering 22 min.

  1. 0Who wrote this page?Undergraduate3 min
  2. 1Least squaresUndergraduate3 min
  3. 2The best linear unbiased lineMaster's2 min
  4. 3Ridge: shrinking the weak directionsMaster's3 min
  5. 4The lasso: soft thresholds and a pathMaster's3 min
  6. 5Logistic regressionUndergraduate3 min
  7. 6Newton's method, and lines that run awayMaster's2 min
  8. 7Naive Bayes: generative or discriminative?Master's2 min
  9. 8Fisher's directionMaster's3 min
  10. 9Neighbours, and the curse of dimensionalityUndergraduate3 min
  11. 10Kernels: lifting without liftingResearch4 min
  12. 11The widest streetMaster's4 min
  13. 12Trees: twenty questionsUndergraduate3 min
  14. 13Bagging and random forestsMaster's2 min
  15. 14AdaBoost and the exponential lossMaster's2 min
  16. 15Gradient boosting, second orderMaster's2 min
  17. 16Keeping score honestlyEngineering2 min
  18. 17The contest, and two culturesEngineering4 min
  19. Recap, problems, and what comes nextAll tracks2 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.

Who wrote this page?Undergraduate3 min

Here's a page from a novel, a thousand words long, with the punctuation stripped away. Who wrote it: Jane Austen, or Charles Dickens?

You might look for names or places. But in 1964, Mosteller and Wallace settled who wrote the disputed Federalist papers by counting small words, like upon, whilst and also. So describe each page with a fixed dictionary: the seventy commonest words in the full five-novel corpus, chosen without author labels before any split. This page says 'the' a lot and 'not' very little, like Dickens. Austen says 'not', 'very' and 'be' far more often.

Take just two of those numbers, how often a page says 'the' and how often it says 'not', and every page becomes a point. pages from five novels. The two authors mostly sit apart, but they overlap. We'll train on of them, and keep locked away from classifier fitting. These are new chunks of the same five novels, not a test on unseen novels; scalers and classifiers are fitted only on training pages. Telling the authors apart is classification, a central task in machine learning. Draw a line? Bend it? Ask the neighbours? Ask questions? This part tries them all.

The methods are older than the computers that run them. In 1805 Legendre fitted orbits by least squares. In 1936 Ronald Fisher found the direction that best separates species of iris. In 1958 Frank Rosenblatt's perceptron learned a line from examples, and in 1967 Cover and Hart proved how well simply copying your nearest neighbour can do. Then trees that ask questions, Vapnik's support vector machines, boosting, random forests, and Viola and Jones finding faces in real time. Then the competitions: Netflix's million-dollar prize, Kaggle, and XGBoost, which won many of them. And now, transformers trained to read whole tables at once.

This is Part 6 of AI, Built, and the start of act two: learning from data. In it: least squares and why it's the best of its kind, ridge and the lasso; logistic regression, Newton's method and naive Bayes; Fisher's direction and nearest neighbours; kernels and support vector machines; trees, forests and boosting; and how to keep score honestly. Every method is written out in a few lines of numpy, and every number is computed on the pages.

1Least squaresUndergraduate3 min

What is the best line through points that disagree?

The oldest method of all fits a line. Here are three points. For any line, measure how far each point misses it, straight up or down, and square each miss: literally, a square. Least squares picks the line whose squares have the smallest total area. Legendre published it in 1805. Gauss had used it four years earlier, to predict where the lost asteroid Ceres would reappear.

Why squares, and not the plain distances? Gauss's answer, in 1809: suppose each miss is random noise shaped like a bell. The chance of the data is a product of bells, one per point. Take minus its logarithm, and the exponents become a sum of squared misses. So the most likely line is exactly the least-squares line. Squares are what bell-shaped noise asks for; the next chapter shows they're the best linear choice even without bells.

There's a beautiful way to see the answer. Write the three heights as a single point in three dimensions. Every possible line makes three predictions, and all of them together form a plane: everything you can reach by mixing a column of ones, which shifts the line up and down, with the column of x's, which tilts it. The best line is the point of that plane closest to the data. Drop a perpendicular. Perpendicular means the leftover is at right angles to both columns: the misses have no shift and no tilt left in them that the line could still fix. Write that down, and you have the normal equations, which give the best line directly, no searching needed.

Here's least squares on real data. Count every word in part one's books, and rank them, from the commonest down. With logarithmic scales on both axes, the thousand commonest words fall almost exactly on a line. The least-squares slope is -1.08: the r-th commonest word turns up about one over r times as often as the first. That's Zipf's law, and the line explains 99.6 percent of the variation: of all the scatter of the points around their average height, the line accounts for everything but a sliver.

2The best linear unbiased lineMaster's2 min

Why squares, and not something else?

And if the noise isn't a bell? Gauss gave a second answer in 1821, and Markov rediscovered it: least squares is still the best linear unbiased estimate. Take any other estimate that's linear in the data: least squares, plus some matrix D. For it to be right on average, whatever the true line, D times A must vanish. Its spread is sigma squared times the matrix times its transpose. Multiply out: the cross terms contain D A, so they vanish, and what's left is least squares' spread plus D D transpose. That can only add. Every other linear unbiased estimate wobbles more.

Let's check. Twelve points on the same twelve x's, with fresh noise each time. Fit them by least squares, and also by the line through the two end points, which is also linear and unbiased. Over 40,000 data sets, both slopes average out at the truth, but least squares' spread is 0.0103, matching the theory, and the end points' is 2.4 times larger.

Now step outside the rules. Theil and Sen's estimate takes the median of all the pairwise slopes: it isn't linear in the data. With bell-shaped noise it loses, against .

How should a computer solve it? Part 3 built the tools. The normal equations are quick, but forming A transpose A squares the condition number, and each factor of ten costs a digit. On the pages it's mild: 9.7, squared to 93. QR solves the same problem without squaring. And when columns repeat, the pseudoinverse picks the shortest of all the best answers.

Put the word 'not' into the table twice. Now two columns are the same, and A transpose A can't be inverted. The pseudoinverse instead splits 'not's weight exactly in half, and , and makes the same predictions as before.

3Ridge: shrinking the weak directionsMaster's3 min

How do you stop a model leaning on noise?

Seventy weights can lean on accidents of the training pages. Ridge regression puts a price on their size: the squared error, plus lambda times the squared length of the weights. Set the gradient to zero. Adding a positive lambda to the diagonal makes the matrix invertible: that's how Hoerl and Kennard rescued nearly repeating columns in 1970. Now use the singular value decomposition from Part 3. The fit is a sum over directions in the data: each direction's share of the target, times a factor, d squared over d squared plus lambda. Least squares keeps every direction whole. Ridge shrinks each one, and the weak directions, with small singular values, shrink the most.

Here are the seventy directions of the training pages, from the widest to the thinnest. Below, how much of the authorship lies along each: 91 percent of it along the first two. Now raise lambda. At one, nothing much shrinks. At thirty, the thinnest direction keeps 59 percent. At a thousand, the widest keeps 80 percent and the thinnest 4. The sum of the factors counts how many weights are effectively still free.

Here is what ridge does to the seventy weights, from a strong penalty to almost none. The coordinate paths vary smoothly as lambda falls; individual weights can turn or cross zero. The monotone shrinkage applies along the singular directions, not to every coordinate. Ridge has a second reading: it's the most probable set of weights if, before seeing any pages, you believed they were small, with a bell-shaped prior, as in Part 5. In neural networks the same penalty is called weight decay.

Which lambda? Hold some pages back, fit on the rest, and measure the error on the held-back ones; do that ten times, each time with a different tenth held back: ten-fold cross-validation. The error is lowest near lambda , about effective weights instead of seventy, . These pages are easy to tell apart, so the penalty barely matters for accuracy; it matters when there are more words than pages. Ridge keeps every word, only smaller. The next chapter's penalty throws words away.

4The lasso: soft thresholds and a pathMaster's3 min

Can a penalty choose the words?

A penalty is a budget. Here are two weights, and the contour lines of the loss, whose lowest point is out here. Ridge's budget on the squared length is a circle. Tibshirani's lasso, in 1996, budgets the sum of absolute values: a diamond. The answer is where the lowest contour just touches the shape. Shrink the budget. The circle's answer slides smoothly toward zero. The diamond's catches on a corner, where one weight is exactly zero.

How is it solved? One weight at a time. Hold the others fixed, and one weight faces a parabola plus lambda times its absolute value. The absolute value has a corner at zero, where its slope can be anything between minus one and one. So the answer is the soft threshold: slide the least-squares value toward zero by lambda, and stop at zero. Any value inside the band gives exactly zero. Visit the words in turn, thresholding each, until nothing moves: coordinate descent, the way glmnet computes it.

Here's the whole path on the pages: all seventy weights, computed by coordinate descent at penalties, from total to gentle. The first words to come alive are . With just those , the classifier gets percent of the held-out pages right. Cross-validation, choosing the sparsest model within one standard error of the best, keeps words and gets percent.

How many words to keep? Cross-validate the whole path: for every penalty, fit on nine tenths of the training pages and score the tenth, ten times over. The error is lowest with 57 words. But the curve is nearly flat there, and its wobble, one standard error, is as large as the differences. The usual rule takes the sparsest model within one standard error of the best: 46 words.

One weakness. Give the lasso two nearly identical words: 'not', and a noisy copy of it. While the penalty is strong, it uses one twin and ignores the other, an arbitrary choice. Zou and Hastie's elastic net, in 2005, mixes in a little ridge, and shares the weight: at the same penalty, the smaller twin carries 50 percent of the pair's weight.

5Logistic regressionUndergraduate3 min

How do you turn a line into a probability?

The simplest classifier draws a straight line. Give every page a score: a weighted sum of its two rates, plus a constant. Positive means Dickens, negative means Austen, and the line is where the score is exactly zero. But a score isn't a probability. Squash it with the sigmoid: large positive scores go to one, large negative scores to zero, and zero to a half.

Over the whole plane, that makes a sheet: the probability of Dickens, rising from Austen's side to Dickens's. Lift each training page to the height of its true answer: zero for Austen, one for Dickens. The sheet should pass close to them. Fitting it means minimizing the average surprise, part one's cross-entropy. The best sheet leaves 0.51 bits of surprise per page.

Is there a single best sheet? Write down the loss. The sigmoid's slope is the sigmoid times one minus itself, so the gradient is beautifully simple: the features times prediction minus truth, just as in least squares. Differentiate again: X transpose S X, with S holding each page's p times one minus p. In any direction v, that's a weighted sum of squares, never negative. The loss is convex: a single bowl. On the pages, the curvature at the answer is positive in every direction, so the bowl has one bottom.

So follow the slope downhill: gradient descent, the same recipe as every model in this series. It starts with every weight at zero: a coin flip for every page. Each step nudges the weights against the gradient: the line swings toward the gap between the two authors, the loss falls, and by about step 20 it has settled. Convexity rules out a bad local minimum. Here the data gives a unique finite best fit, and with a stable step size gradient descent approaches it from any starting weights.

Now the test: chunks excluded from fitting, from the same five novels. With two rates, the line gets percent of them right. Give it all seventy rates instead, and the same method gets of the test pages right. This test does not establish accuracy on a previously unseen novel.

6Newton's method, and lines that run awayMaster's2 min

How do you reach the bottom of the bowl fast?

Gradient descent takes small steps. Newton's method uses the curvature too: fit a parabola to the loss where you stand, and jump to its bottom. With chapter five's gradient and curvature, the step is X transpose S X, inverted, times X transpose y minus p. Rearrange, and each step is a weighted least-squares problem, fitted to a working response. Pages the model is unsure of weigh the most. Nelder and Wedderburn made this the engine of every generalized linear model, in 1972.

Race them, from the same start. After one step, Newton's line is already near the answer; after , it's there. Gradient descent, after the same number of steps, is still swinging into place. With all seventy rates, minimize mean cross-entropy in nats plus half lambda times the squared weight norm, with lambda . The gap subtracts the minimum of this penalized objective. Newton needs steps to reach it to the last digit; gradient descent needs steps to get within a millionth. Near the bottom, Newton doubles the number of correct digits at every step. The price: a by system, including the intercept, to solve each time, which is why giant models stay with gradients.

Why is Newton so fast at the end? Near the bottom, the loss is almost exactly a parabola, and each step's error is about the square of the last one. Square a small number and its zeros double. On the seventy rates, step by step,

7Naive Bayes: generative or discriminative?Master's2 min

Model the author, or model the writing?

Logistic regression models the answer directly. Naive Bayes models the writing. Pretend each author writes by drawing words independently, Dickens with probabilities theta D. Bayes' rule turns that around. Take the log of the odds. It's a weighted sum of the word counts plus a constant: a straight line, the same family as logistic regression, but with weights read off from counting, not fitted. Add one to every count, Laplace's rule from Part 1, so no word is impossible. Two philosophies: generative models how the data is made; discriminative models only the decision.

Here's what it learned, by counting. Each word's weight is the log of how much more often Dickens uses it than Austen. Austen's strongest words: 'mrs', 'she', 'very'. Dickens's: 'out', 'up', 'me'. Every occurrence of a word adds its weight to the page's log-odds.

Which is better? Ng and Jordan's answer: it depends on how much data you have. Train both on random sets of pages, from four up to all of them, many times over, and test on the held-out pages.

There's a second difference. When a model says seventy percent, is it right seventy percent of the time? Group the pages by the probability given, and plot how often they really were Dickens. Honest probabilities lie on the diagonal. Logistic regression's are close: average error 0.039. Naive Bayes counts every word as independent evidence, so it's wildly sure of itself: 90 percent of pages get odds beyond a million to one. Platt's fix, in 1999, fits a one-variable logistic regression to its scores on training pages, and the error falls from 0.042 to 0.011.

8Fisher's directionMaster's3 min

Which way do the two authors look most different?

In 1936, Ronald Fisher, separating species of iris by the sizes of their petals, asked a different question. Along which direction do the two groups look most different? Pick a direction, and squash every page onto it. Each author becomes a pile. Turn the direction, and the piles slide together, or apart. Fisher's score is the gap between the piles' centres, squared, divided by how spread out they are.

The best direction has a formula: the difference between the two centres, corrected by the inverse of the pooled spread within the authors. First whiten the pooled covariance with its inverse square root, W. In that space the pooled ellipses are round; connect the transformed means. Then pull that normal back with W transpose. The two inverse-square-root maps together give the full inverse in Fisher's formula, up to an overall scale. Here, it leans mostly on 'not'. Cut halfway between the piles, and you have a classifier. It gets percent of the test pages right When each group is a bell of the same shape, this cut, nudged for the authors' unequal numbers of pages, is the best one possible.

Why is that cut the best possible one? Suppose each author's pages are a bell, both bells the same shape. Bayes' rule gives the log-odds of Dickens. Expand the two quadratic forms: the terms in x times x cancel, because the shapes match, and what's left is a straight line in x. The probability is a sigmoid of a line, exactly logistic regression's form, with Fisher's direction as its weights. LDA is generative, like naive Bayes: it estimates the two bells and divides, where logistic regression fits the line directly.

Where does the formula come from? Fisher's score is a ratio of two quadratic forms: the spread between the authors over the spread within them. Set its gradient to zero, and you get a generalized eigenproblem. With positive within-class scatter and different means, choose its largest positive eigenvalue; zero-eigenvalue stationary directions do not maximize the separation. But S B has rank one: it only ever points along the difference of the means. So the answer is S W inverse times that difference. On all seventy rates, the eigensolver finds one nonzero eigenvalue, and its eigenvector agrees with the formula to . It leans hardest on , and gets percent of the held-out pages right.

9Neighbours, and the curse of dimensionalityUndergraduate3 min

What if there is no line at all?

Here's a method with no line at all, written down by Fix and Hodges in 1951. To classify a page, find the training pages most like it, its nearest neighbours, and let them vote. Take this page from the test set. Its fifteen nearest neighbours: 5 by Austen, 10 by Dickens. The majority wins. There's no training at all: the model is the data.

Colour every point of the plane by how its neighbours would vote, and you see the method's whole answer. With one neighbour, the regions are a ragged patchwork that copies the training pages: percent of them right, but only percent of new ones. More neighbours smooth it out. On the held-out pages the best is k equals , percent.

How good can copying a neighbour be? Cover and Hart answered in 1967. Let eta of x be the chance a page at x is Dickens. The nearest neighbour's label is an independent coin with its own eta, so an error is a disagreement. With enough data the neighbour sits on top of x, and the error becomes two eta times one minus eta. That's at least the smaller of eta and one minus eta, the best any rule can do there, and by Jensen's inequality, on average at most twice the best possible error. Check it on two overlapping bells, where the best possible error is 21.2 percent. With 10,000 points the single neighbour errs 29.5 percent of the time, near its limit of 29.2, inside the bound of 33.4. Let k grow with n, and the error falls toward the best: 21.5.

There's a catch, and Richard Bellman named it: the curse of dimensionality. In many dimensions, everything is far from everything, and equally far. Scatter points in a cube: in one dimension the nearest is a tiny fraction of the average distance; in a thousand dimensions, 94 percent of it. To hold a tenth of the data, a cube in ten dimensions needs sides 0.79 long: a neighbourhood that isn't local any more. On the pages, add columns of pure noise. Nearest neighbours fall from 98 to 88 percent, because every noise column counts as much as a real word. Logistic regression learns to ignore them, and falls only from 99 to 97.

10Kernels: lifting without liftingResearch4 min

What if no line can do it?

In 1958 Frank Rosenblatt's perceptron learned a line from examples: each time it misclassifies a page, add that page to the weights. If some line separates the data with a margin, Novikoff proved it stops after at most R over gamma, squared, mistakes. But some patterns have no line at all. Exclusive or: the perceptron never stops, 400 mistakes in a hundred passes. Minsky and Papert's 1969 book made limits like this famous, and helped bring on a winter for neural networks. There are two ways out. Learn new features, which is Part 9's story. Or add them by hand: give each point a third number, x one times x two, and the perceptron separates XOR after 4 mistakes.

Here's the same idea with circles. No straight line separates the inside from the ring. Lift each point to a height equal to its squared distance from the centre. Now a flat plane separates them: this one was found by the next chapter's support vector machine, working on the lifted points. Seen from above, the plane cuts out a circle: a straight line in the lifted space is a curve in the original one.

The lift can be expensive: with many numbers per point, the lifted features multiply. The kernel trick avoids it. Take these six features of a point in the plane. Their dot product, multiplied out, is just x dot z plus one, squared: computed from the two original numbers, never the six. Any method that only needs dot products, like the support vector machine, can run in the lifted space for free. The Gaussian kernel goes further. Expand it, and its features are every power of the coordinates: infinitely many. For a one-dimensional check with gamma one, keep the first powers. On a sixty-one by sixty-one grid with both inputs between minus one point five and one point five, the largest error is below .

Which similarity scores are allowed? For a real symmetric similarity function, a feature-space dot product exists exactly when every Gram matrix is positive semidefinite: it has no negative eigenvalues. On the 448 training pages, the Gaussian kernel's smallest eigenvalue is zero, up to rounding. A popular impostor, the hyperbolic tangent of a dot product, has 138 negative eigenvalues: no features could produce it, and an SVM built on it is no longer solving a convex problem.

One more guarantee makes kernels practical. Fit any function with any loss, plus a positive penalty on its squared size. Split the function into a part built from the kernel at the training points, and a part perpendicular to all of them. At the training points, the perpendicular part is invisible: it changes no prediction. It only adds to the size. So it must be zero, and the answer is a weighted sum of kernels at the training points: the representer theorem. Check it: solve ridge regression in 2,000 explicit random features of the pages, and the answer lies in the span of the pages' own features, to the last digit.

11The widest streetMaster's4 min

Which line, of all the lines that work?

Many lines separate these two groups. Vapnik's question: which is best? His answer: the one with the widest empty street on both sides. A point's distance to the line is the score over the length of w. Rescale w so the nearest points score exactly one; then the street is two over the length of w wide, and the widest street is the shortest w that keeps every point on its side. The street's edges rest on just points, the support vectors. Moving another point leaves this solution unchanged as long as that point stays outside the same margin.

Real authors overlap, so no street is empty. In 1995 Cortes and Vapnik let points stand in the street, or on the wrong side, at a price. The price is the hinge loss: zero for a page safely on its side, growing in a straight line as it crosses. Compare it with being right or wrong, which is difficult to optimize by gradients, and with logistic regression's loss. Both are convex substitutes for counting mistakes; logistic loss is smooth, while hinge loss has a corner at margin one. The constant C sets the price: large C, a narrow street that fights for every page; small C, a wide, forgiving one.

This is a constrained problem, and Part 4's Lagrange multipliers turn it inside out. Give each page's constraint a multiplier alpha. Setting the derivatives to zero says the weights are a mix of the training pages themselves, and each alpha lies between zero and C. Substitute back, and the problem is about the alphas alone, and the pages appear only through dot products: swap in a kernel, and the street becomes curved. The KKT conditions finish it: alpha is zero for every page safely off the street. Only the support vectors count. Platt's SMO solves it two alphas at a time, and that's what we'll run.

Now the pages, with a Gaussian kernel, solved by SMO. At C equals , standing in the street is cheap: of the pages are support vectors, and the boundary barely bends. Raise C, and the street narrows: at , support vectors, and the boundary bends around the pages. Every solution is checked numerically: the displayed relative primal-dual gaps show the approximation. At C equals one, outside or bound points fail the margin checks at a tolerance of one thousandth; the maximum free-margin residual is shown separately. Ten-fold cross-validation picks C equals and a kernel width of , and gets percent of the held-out pages right; with all seventy rates, . From 1995 until deep networks took over around 2012, this was the method to beat.

Where did C and gamma come from? A grid: 5 prices times 5 kernel widths, each pair scored by ten-fold cross-validation on the training pages. The best pair averages 83.9 percent, but 12 of the 25 settings are within a point of it. Only a tiny C, a street so cheap to stand in that the boundary barely bends, falls to 55 percent. On two numbers per page, the method matters less than the data.

12Trees: twenty questionsUndergraduate3 min

What if you just keep asking questions?

A decision tree plays twenty questions. The first question it learned: does the page say 'not' at most 8.5 times per thousand words? Each answer splits the pages, and each group gets its own next question. Every question cuts the plane with a straight line, parallel to an axis, so the plane becomes boxes, and each box votes by its majority.

How does the tree choose its question? It measures how mixed each box is. Three measures of impurity: Gini's, the entropy from Part 1, and the plain error rate. A question's gain is the parent's impurity minus its children's, weighted by size. The parent's share of Dickens is the average of its children's, so if the impurity curves strictly downward, Jensen's inequality makes every gain positive whenever the children differ. The error rate is a tent, linear on each side: different child class proportions can still give zero gain if both lie on the same side of one half. Scan every threshold.

Keep asking questions, and the boxes fit the training pages better and better. But new pages tell a different story. They're best at depth 4, 83 percent right. Grown all the way down, the tree gets 94 percent of its own pages right, and only 74 percent of new ones. Cross-validation on the training pages, without peeking, picks depth 3. Breiman, Friedman, Olshen and Stone's CART, in 1984, grew trees deep and pruned them back the same way.

One more weakness. Grow the same small tree on resamples of the training pages, drawn with replacement, 20 times. The first question changes: 3 different words come first, 'not' most often, in 10 of the 20 trees. Below it, the trees disagree even more. And on the held-out pages they score anywhere from 80 to 93 percent. A tree is a high-variance learner, and the next chapter turns that weakness into a strength.

13Bagging and random forestsMaster's2 min

Why does a crowd of trees beat one?

Why does averaging trees help? Write the variance of an average of B trees, each with variance sigma squared, and every pair correlated by rho. It's the sum over every pair of their covariance: B variances, and B times B minus one covariances. So: rho sigma squared, plus the rest divided by B. More trees remove the second part, but never the first: correlation sets a floor. Check it by simulation: with rho a half, 100 averaged copies keep 0.512 of the variance, against the formula's 0.505.

On the pages, the trees' correlation comes from sharing the same training pages. Draw training sets of pages, grow trees on resamples of each, and measure sigma squared and rho at the held-out pages. Bagged trees, Breiman's 1996 recipe, are correlated: rho is , and that floor stops the averaging. Breiman's 2001 twist lets each question choose among only a few random words.

Grow a forest of 300 on all the training pages. One full tree gets 94 percent of the held-out pages right. The forest climbs to 100.0: 191 of 191. And it grades itself for free: each training page left out of a tree's resample is a test page for that tree. That out-of-bag estimate says 98 percent, without touching the held-out pages.

14AdaBoost and the exponential lossMaster's2 min

Can many weak rules make a strong one?

Boosting asks a different question: can many weak rules make a strong one? Freund and Schapire's AdaBoost, in 1997, said yes. Start with every training page weighted equally, and find the best single question, a stump. It gets 18 percent of the weight wrong. Now make the pages it got wrong heavier, and find the best stump for the reweighted pages. Repeat. The weight piles up on the hard pages, along the border between the authors, and the committee's vote, each stump weighted by alpha, carves the plane.

Why those weights, and that alpha? Friedman, Hastie and Tibshirani found the answer in 2000. AdaBoost greedily minimizes the exponential loss: e to the minus the margin. Add one stump, scaled by alpha. Split the exponential, and the old committee's part is exactly each page's weight. Pages the stump gets right contribute e to the minus alpha, pages it gets wrong e to the alpha. Set the derivative to zero, and alpha is half the log of the odds of being right. Searching for alpha numerically agrees with the formula to within a few millionths here.

On all seventy rates, run four hundred rounds. The exponential loss falls steadily. It's always above the training error, since e to the minus the margin is at least one for any mistake.

Boosting's most famous success came in 2001. Paul Viola and Michael Jones found faces in video in real time, on an ordinary 700 megahertz PC. Each weak rule was a stump on one rectangle feature: the brightness of one band minus its neighbour, like the dark eyes under a lighter forehead. AdaBoost chose the best few among more than a hundred and sixty thousand. And they chained the committees into a cascade: a tiny one throws out most windows at once, and only the hard ones reach the big committees. For years afterwards, that's how cameras found faces.

15Gradient boosting, second orderMaster's2 min

How does XGBoost choose a split?

Friedman saw, in 2001, that boosting is gradient descent, taken in the space of functions: each new tree is a small step downhill on the loss. XGBoost, in 2016, took the step to second order. Expand the loss around the current model: each page contributes its gradient g, prediction minus truth, and its curvature h, p times one minus p, plus a price on leaves and their weights. A tree gives every page in a leaf the same weight, so the sums collect leaf by leaf. Each leaf is a parabola in its weight: its best weight is minus G over H plus lambda, a Newton step. And a split's gain is how much those parabolas' bottoms drop when one leaf becomes two.

Check the formula on the pages. In round one every page sits at probability a half. The best first question is: does the page use '' at most times? Sum the gradients and curvatures on each side. The gain formula gives ; evaluating the second-order objective leaf by leaf gives The true drop in the loss is :

Watch it learn on the two plotted rates. One tree: a few boxes. Ten, thirty: the boundary sharpens where the authors meet. The training loss keeps falling, but the held-out pages are best after rounds, at percent.

On all seventy rates, compare the two kinds of step with the same trees and the same learning rate. On the held-out pages, the second-order booster reaches percent, the first-order one .

16Keeping score honestlyEngineering2 min

What does "83% right" really tell you?

A classifier gives a score; we chose to cut at a half. Every cut is a trade. Start strict, calling nothing Dickens. Lower the threshold: you find more of Dickens's pages, the hits, but start calling Austen's pages Dickens, the false alarms. The path traced out is the ROC curve, from radar operators in the Second World War. Its area has a beautiful meaning: the chance that a random Dickens page scores higher than a random Austen page, plus half the chance of a tie. Count all pairs: , the area exactly.

Now make Dickens rare, as fraud or disease usually is. Keep all of Austen's pages, and only of Dickens's. A rule that always says Austen is now percent accurate, and useless. The ROC curve barely notices: its area is still about , because it measures each author's pages separately. Precision and recall ask what you care about: of the pages you call Dickens, how many are?

Accuracy only counts right and wrong. A proper score, like part one's log loss, also charges for confidence.

And how sure is any single number? Logistic regression on two rates, scored again and again. On a hundred different random splits into training and test pages, its accuracy ranges from to percent: the luck of the split. Ten-fold cross-validation uses every page for testing once. Each fold alone wobbles by about points, but their average is steady: twenty different shuffles all land between and . The rule that keeps the whole contest honest: make every choice on the training pages, and look at the test pages once, at the end. This measures new chunks from the same five novels, with a fixed full-corpus dictionary; it does not measure transfer to an unseen novel.

17The contest, and two culturesEngineering4 min

Which method wins, and why do trees still rule tables?

Here's the contest: twelve named procedures on the same ten folds of these same-five-novel pages, with a fixed full-corpus dictionary and settings fixed in advance. With two rates, every method lands between and percent for these tested procedures on these folds. With all seventy, A single tree manages . The lesson of classical machine learning: the description of the data mattered more than the cleverness of the method. Choosing seventy small words did most of the work.

In 2001 Leo Breiman, who had left statistics for consulting and come back, described two cultures. Most statisticians assumed a model of how the data was made, and estimated it. A few, mostly outside statistics, treated nature as a black box, and judged a method only by how well it predicted new data. This part has belonged to the second culture. Competitions made it the norm. In 2006 Netflix offered a million dollars for predicting ratings ten percent better; a blend of hundreds of models won in 2009. Kaggle turned the contest into a profession, and in 2015, seventeen of the twenty-nine winning solutions on Kaggle's blog used XGBoost.

Deep learning took over images, sound and language. Why not tables? In 2022, Grinsztajn, Oyallon and Varoquaux tested forty-five tabular data sets of around ten thousand rows, and tree ensembles still beat deep networks. Their reasons: tables carry useless columns, which trees simply never ask about; each column means something, and networks blur them together; and the answers jump in steps, which trees draw easily. The challenger is a transformer trained only on millions of synthetic tables, which reads your training rows as its prompt and predicts in one pass. TabPFN's second version, in Nature in January 2025, beat a four-hour tuned ensemble in under three seconds in its reported classification benchmark configuration, on tables of up to ten thousand rows. Its successors reach fifty thousand rows, then, in May 2026, a million rows at two hundred features, top of the TabArena leaderboard by their makers' report. A broader June 2026 benchmark included model authors among its coauthors and tested TabPFN two point six, not TabPFN three. Foundation models were strong on small and medium IID tables; traditional tree and deep models exposed boundary cases on non-IID, large or very wide data. These are version- and task-specific comparisons, with both tree and deep models necessary baselines.

None of this went away; it moved inside the big models. The last layer of every language model is a logistic regression over its vocabulary. Linear probes, fitted by least squares, read concepts out of a network, and ridge's penalty is weight decay. The lasso's absolute-value penalty is how sparse autoencoders pull features out of a model. Kernels describe very wide networks, and attention is a kernel smoother. Nearest neighbours became retrieval. And boosted trees still run the world's tables and search rankings, while the question naive Bayes raised, whether a model's probabilities mean anything, is asked of every chatbot.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. Least squares is a projection, and among linear unbiased estimates the best. Ridge shrinks the weak directions; the lasso's soft thresholds choose words. Logistic regression is a convex bowl, and Newton's method finds its bottom in a few steps. Naive Bayes learns fast but stays wrong, and overconfident on these pages. In the large-sample limit, a single neighbour errs at most twice as often as the best rule, but neighbours drown in many dimensions. Kernels lift without lifting, and the support vector machine's dual needs only them. Averaging trees cuts variance down to a floor set by their correlation; boosting walks down the exponential loss, and XGBoost takes Newton steps. And an honest score needs the right curve and untouched test pages.

All of it comes back. Cross-entropy, gradients and curvature are how every network in Parts 9 and 11 is trained, and the softmax is logistic regression with many classes. Part 7 builds the statistical models: principal components, mixtures, Bayes. Part 8 asks why a model generalizes at all, and meets the neural tangent kernel, a network that behaves like a kernel machine. Part 13 reads attention as a kernel smoother, and Part 31 asks the same question of language models that we asked of naive Bayes: are its probabilities honest?

Here are eight problems to try, from Gauss-Markov to XGBoost's gain. Pause here, and work through them; full solutions are in this part's notes.

Next time: statistical machine learning. Every method in this part was told who wrote each training page. Part 7 takes the labels away and asks what structure is there anyway: the directions the pages spread along, the clusters they fall into, and the hidden causes behind them.

For more, The Elements of Statistical Learning by Hastie, Tibshirani and Friedman covers every method here, by three of the people who built them; Bishop's Pattern Recognition and Machine Learning gives the probabilistic view; and Schölkopf and Smola's Learning with Kernels the kernels. Thanks for watching, and see you in Part 7.

Where it goes next. Cross-entropy, gradients and curvature train every network of Parts 9 and 11, and the softmax is logistic regression with many classes. Part 7 takes the labels away; Part 8 asks why any of these fits generalizes and reuses the pages, the margins and the runaway logistic weights; attention is read as a kernel smoother in Part 13, and calibration returns for language models in Part 31.

Key results

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

Normal equations\(\displaystyle X^\top X\hat\beta=X^\top y,\qquad\allowbreak \hat y=X\hat\beta\ \perp\ y-\hat y\)
Ridge through the SVD\(\displaystyle \hat y_\lambda=\sum_j u_j\,\frac{d_j^2}{d_j^2+\lambda}\,u_j^\top y\)
The soft threshold\(\displaystyle w=\operatorname{sign}(z)\,\max(|z|-\lambda,\,0)\)
Logistic gradient and Hessian\(\displaystyle \nabla L=\tfrac1n X^\top(p-y),\qquad\allowbreak \nabla^2L=\tfrac1n X^\top SX\succeq 0\)
Bagging B correlated trees\(\displaystyle \operatorname{Var}\Bigl(\tfrac1B\sum_b T_b\Bigr)=\rho\sigma^2+\frac{1-\rho}{B}\,\sigma^2\)
AdaBoost's step\(\displaystyle \alpha=\tfrac12\log\frac{1-\varepsilon}{\varepsilon}\)

Try it

Lab 6 · Newton against gradient descent on logistic regression

Simulate two overlapping classes with correlated features, check the gradient X'(p - y)/n against the series' autodiff, then minimize the cross-entropy by Newton's method (weighted least squares) and by gradient descent.

Figure produced by Lab 6: Newton against gradient descent on logistic regression
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 6 needs numpy, scipy, matplotlib · download lab06.py · source on GitHub
gradient: autodiff against X'(p - y)/n         largest difference 5.6e-17
Hessian X'SX/n at the minimum                  eigenvalues 0.0160 to 0.539   (all positive: convex)
Newton: correct digits after each step         -0.4  -0.0  0.4  1.3  3.0  6.4  13.3
Newton: steps to 10 correct digits             6
gradient descent: steps to a loss gap of 1e-6  304
cross-entropy at the minimum                   0.598 bits per example

Newton's correct digits roughly double with every step once it is close, so a handful of weighted least-squares fits do what gradient descent needs hundreds of steps for.
The code (98 lines; it asserts its own result)
"""Lab 6: fit a logistic regression by Newton's method and by gradient descent, and count the correct digits."""

import numpy as np

from videos.coursekit import labs
from explainer.ai.autodiff import Tensor

TITLE = "Newton against gradient descent on logistic regression"
GOAL = ("Simulate two overlapping classes with correlated features, check the gradient X'(p - y)/n against the series' "
        "autodiff, then minimize the cross-entropy by Newton's method (weighted least squares) and by gradient descent.")
TASKS = [
    "Raise the features' correlation rho from 0.8 to 0.98. Which method's step count changes, and why?",
    "Move the class means apart (shift = 6) until a line separates the sample. Watch the weights' norm grow with every Newton step.",
    "Add a ridge penalty lam/2 |w|^2 to the loss, the gradient and the Hessian, and plot the weights' norm against lam.",
]


def loss_and_grad(X, y, w):
    """The mean cross-entropy in nats and its gradient, by reverse-mode autodiff."""
    wt = Tensor(w, requires_grad=True)
    z = Tensor(X) @ wt
    loss = ((z.exp() + 1.0).log() - z * y).mean()
    loss.backward()
    return float(loss.data), wt.grad


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, d, rho, shift = 400, 5, 0.8, 0.5
    cov = rho * np.ones((d, d)) + (1 - rho) * np.eye(d)
    y = (rng.random(n) < 0.5).astype(float)
    X = rng.multivariate_normal(np.zeros(d), cov, n) + shift * np.outer(y - 0.5, np.linspace(1, -1, d))
    X = np.column_stack([np.ones(n), X])
    sigmoid = lambda z: 1 / (1 + np.exp(-z))

    # the formula of chapter 5 against the autodiff of Part 4
    w0 = 0.3 * rng.standard_normal(d + 1)
    _, g_auto = loss_and_grad(X, y, w0)
    g_formula = X.T @ (sigmoid(X @ w0) - y) / n
    grad_gap = np.abs(g_auto - g_formula).max()

    def hessian(w):
        p = sigmoid(X @ w)
        return (X * (p * (1 - p))[:, None]).T @ X / n

    # Newton = iteratively reweighted least squares
    w, newton = np.zeros(d + 1), []
    for _ in range(12):
        newton.append(w.copy())
        _, g = loss_and_grad(X, y, w)
        w = w - np.linalg.solve(hessian(w), g)
    w_star = w
    f_star, g_star = loss_and_grad(X, y, w_star)
    eigs = np.linalg.eigvalsh(hessian(w_star))
    digits = [-np.log10(max(np.abs(v - w_star).max(), 1e-16)) for v in newton]
    newton_steps = next(k for k, v in enumerate(newton) if np.abs(v - w_star).max() < 1e-10)

    # gradient descent with the safe step 1/L, L = the largest eigenvalue of X'X/(4n)
    step = 1 / (np.linalg.eigvalsh(X.T @ X / (4 * n))[-1])
    w, gd_gap = np.zeros(d + 1), []
    for _ in range(1500):
        f, g = loss_and_grad(X, y, w)
        gd_gap.append(f - f_star)
        w = w - step * g
    gd_gap = np.array(gd_gap)
    gd_steps = int(np.argmax(gd_gap < 1e-6)) if (gd_gap < 1e-6).any() else len(gd_gap)
    newton_gap = np.array([loss_and_grad(X, y, v)[0] - f_star for v in newton])

    lab = labs.Lab()
    lab.row("gradient: autodiff against X'(p - y)/n", f"largest difference {grad_gap:.1e}")
    lab.row("Hessian X'SX/n at the minimum", f"eigenvalues {eigs[0]:.4f} to {eigs[-1]:.3f}   (all positive: convex)")
    lab.row("Newton: correct digits after each step", "  ".join(f"{v:.1f}" for v in digits[:newton_steps + 1]))
    lab.row("Newton: steps to 10 correct digits", f"{newton_steps}")
    lab.row("gradient descent: steps to a loss gap of 1e-6", f"{gd_steps}" + ("+" if gd_steps == len(gd_gap) else ""))
    lab.row("cross-entropy at the minimum", f"{f_star / np.log(2):.3f} bits per example")
    lab.note = ("Newton's correct digits roughly double with every step once it is close, so a handful of weighted "
                "least-squares fits do what gradient descent needs hundreds of steps for.")

    assert grad_gap < 1e-12, "autodiff agrees with the derived gradient"
    assert eigs[0] > 0 and np.abs(g_star).max() < 1e-12, "a convex loss, minimized"
    assert newton_steps <= 8, "Newton converges in a handful of steps"
    late = [k for k in range(1, newton_steps) if 1.0 < digits[k] < 7.0]
    assert late and all(digits[k + 1] > 1.6 * digits[k] for k in late), "quadratic convergence: the digits double"
    assert gd_steps > 20 * newton_steps, "gradient descent needs far more steps"
    assert np.all(np.diff(gd_gap) < 1e-12), "with step 1/L gradient descent never goes uphill"

    fig, ax = labs.figure(2, size=(11, 4.2))
    ax[0].semilogy(np.arange(len(gd_gap)) + 1, np.maximum(gd_gap, 1e-16), color=labs.BLUE, label="gradient descent, step 1/L")
    ax[0].semilogy(np.arange(len(newton_gap)) + 1, np.maximum(newton_gap, 1e-16), "o-", color=labs.GOLD, label="Newton (IRLS)")
    ax[0].set(xscale="log", title="Loss above the minimum", xlabel="step (log scale)", ylabel="nats per example", ylim=(1e-16, 2))
    ax[0].legend()
    k = np.arange(newton_steps + 1)
    ax[1].bar(k, digits[:newton_steps + 1], color=labs.GOLD, width=0.6)
    for i in k:
        ax[1].text(i, max(digits[i], 0) + 0.3, f"{digits[i]:.1f}", ha="center", color=labs.INK, fontsize=9)
    ax[1].set(title="Newton: correct digits of the weights", xlabel="Newton steps taken", ylabel="correct decimal digits")
    lab.fig = fig
    return lab

Now change it

  1. Raise the features' correlation rho from 0.8 to 0.98. Which method's step count changes, and why?
  2. Move the class means apart (shift = 6) until a line separates the sample. Watch the weights' norm grow with every Newton step.
  3. Add a ridge penalty lam/2 |w|^2 to the loss, the gradient and the Hessian, and plot the weights' norm against lam.

Problems, with solutions

Try each problem before opening its solution.

  1. For y_i = β₀ + β₁x_i + ε_i, show that the slope through the two end points is unbiased with variance 2σ²/(x_n − x₁)², and that least squares' is σ²/Σ(x_i − x̄)². Which is smaller?

    Solution

    两者都对y是线性的。端点斜率是(y_n − y₁)/(x_n − x₁),均值为β₁;y_n与y₁独立、方差均为σ²,所以方差是 2σ²/(x_n − x₁)²。最小二乘斜率是Σ(x_i − x̄)y_i / Σ(x_i − x̄)²,因为Σ(x_i − x̄) = 0,其均值为β₁,方差为 σ²/Σ(x_i − x̄)²。由于Σ(x_i − x̄)² ≥ (x₁ − x̄)² + (x_n − x̄)² ≥ (x_n − x₁)²/2,最小二乘的方差从不更大:这是 高斯–马尔可夫定理的缩影。本章1到10上的12个点:0.0104σ²对0.0247σ²。

  2. Show that ridge's fit is Σ_j u_j d_j²/(d_j² + λ) u_jᵀy, and that tr Z(ZᵀZ + λI)⁻¹Zᵀ = Σ_j d_j²/(d_j² + λ).

    Solution

    设Z = UDVᵀ,则ZᵀZ + λI = V(D² + λI)Vᵀ,所以w = V(D² + λI)⁻¹DUᵀy,Zw = Σ_j u_j d_j²/(d_j² + λ) u_jᵀy。 帽子矩阵H = U diag(d_j²/(d_j² + λ)) Uᵀ,它的迹就是这些因子之和;λ = 0时等于秩,即权重的个数。

  3. Derive the soft threshold from subgradients, and show that the lasso's weights are all zero exactly when λ ≥ max_j |z_jᵀy|/n.

    Solution

    单个坐标最小化½(z − w)² + λ|w|。最优处0 ∈ w − z + λ∂|w|,其中w ≠ 0时∂|w| = {sign w},在0处为[−1, 1]。 若w > 0,则w = z − λ,要求z > λ;若w < 0,则w = z + λ,要求z < −λ;w = 0恰在|z| ≤ λ时成立。合起来就是 w = sign(z) max(|z| − λ, 0)。对整个套索回归(1/2n)‖y − Zw‖² + λ‖w‖₁,w = 0最优当且仅当对每个j都有 |z_jᵀy|/n ≤ λ。

  4. Show that the logistic loss's Hessian XᵀSX/n is positive semidefinite, and that if a line separates the training data, no finite weights minimize the loss.

    Solution

    记p_i = σ(x_iᵀw),黑塞矩阵为(1/n)Σ p_i(1 − p_i) x_i x_iᵀ,所以vᵀHv = (1/n)Σ p_i(1 − p_i)(x_iᵀv)² ≥ 0。若对所有i 有y_i(wᵀx_i) > 0(标签取±1),则沿tw方向,损失Σ log(1 + e^{−t y_i wᵀx_i})随t → ∞严格减小并趋于0,但对每个有限的 t都为正,所以不存在有限的最小值点:这就是第6章里跑掉的权重。

  5. Show that the Gram matrix of K(x, z) = (x·z + 1)² is positive semidefinite, and find a Gram matrix of tanh(x·z − 1) with a negative eigenvalue.

    Solution

    在二维中(x·z + 1)² = φ(x)·φ(z),φ = (x₁², x₂², √2x₁x₂, √2x₁, √2x₂, 1)(任意维同理),所以 aᵀKa = ‖Σ_i a_iφ(x_i)‖² ≥ 0。对tanh:取单个点x = 0,K = tanh(−1) < 0,就是一个有负特征值的1×1格拉姆矩阵; 本章在训练页上找到了138个负特征值。

  6. Derive the dual of the soft-margin SVM, and use complementary slackness to show that α_i = C for every training point strictly inside the street.

    Solution

    拉格朗日函数L = ½‖w‖² + CΣξ_i − Σα_i[y_i(w·x_i + b) − 1 + ξ_i] − Σμ_iξ_i,α, μ ≥ 0。∂L/∂w = 0得 w = Σα_iy_ix_i;∂L/∂b = 0得Σα_iy_i = 0;∂L/∂ξ_i = 0得α_i + μ_i = C,所以0 ≤ α_i ≤ C。代回:在这些约束下最大化 Σα_i − ½ΣΣα_iα_jy_iy_j x_i·x_j。互补松弛:μ_iξ_i = 0,且α_i[y_if(x_i) − 1 + ξ_i] = 0。严格位于街道内部的点有 y_if(x_i) < 1,所以ξ_i > 0,于是μ_i = 0,α_i = C。

  7. Derive Var((1/B)Σ_b T_b) = ρσ² + (1 − ρ)σ²/B, and AdaBoost's α = ½ log((1 − ε)/ε) from the exponential loss.

    Solution

    Var((1/B)ΣT_b) = (1/B²)Σ_{b,c}Cov(T_b, T_c) = (1/B²)(Bσ² + B(B − 1)ρσ²) = ρσ² + (1 − ρ)σ²/B。对AdaBoost, 权重w_i ∝ e^{−y_iF(x_i)}归一化后,加权错误率为ε,L(α) ∝ (1 − ε)e^{−α} + εe^{α};令L′(α) = 0得 e^{2α} = (1 − ε)/ε。

  8. For the logistic loss, derive XGBoost's leaf weight −G/(H + λ) and split gain, and show that a single leaf at p = ½ moves the log-odds by −4G/(n + 4λ).

    Solution

    记g_i = p_i − y_i,h_i = p_i(1 − p_i),权重为w的一片叶子贡献Gw + ½(H + λ)w²,在w* = −G/(H + λ)处取最小值 −½G²/(H + λ)。一次分割把一片叶子换成两片,所以增益是 ½[G_L²/(H_L + λ) + G_R²/(H_R + λ) − (G_L + G_R)²/(H_L + H_R + λ)] − γ。在p = ½时每个h_i = ¼,H = n/4, w* = −G/(n/4 + λ) = −4G/(n + 4λ)。

Notes and sources

Glossary

English 中文
least squares, normal equations 最小二乘,正规方程
Gauss–Markov theorem, best linear unbiased estimator (BLUE) 高斯–马尔可夫定理,最佳线性无偏估计
Theil–Sen estimator 泰尔–森估计
pseudoinverse (Moore–Penrose) 伪逆(摩尔–彭罗斯)
ridge regression, shrinkage factor, effective number of weights 岭回归,收缩因子,有效权重数
lasso, soft threshold, coordinate descent, regularization path 套索回归(Lasso),软阈值,坐标下降,正则化路径
subgradient 次梯度
one-standard-error rule 一个标准误规则
elastic net 弹性网络
logistic regression, sigmoid, convex 逻辑回归,S形函数(sigmoid),凸的
Hessian 黑塞矩阵
Newton's method, iteratively reweighted least squares (IRLS), working response 牛顿法,迭代重加权最小二乘(IRLS),工作响应
generalized linear model 广义线性模型
separable data 可分数据
naive Bayes, Laplace smoothing 朴素贝叶斯,拉普拉斯平滑
generative, discriminative 生成式,判别式
calibration, reliability diagram, expected calibration error, Platt scaling 校准,可靠性图,期望校准误差,普拉特缩放
Fisher's linear discriminant (LDA), within-class / between-class scatter 费希尔线性判别(LDA),类内散度、类间散度
generalized eigenproblem, Rayleigh quotient 广义特征值问题,瑞利商
k nearest neighbours, Bayes error, Cover–Hart bound k近邻,贝叶斯错误率,科弗–哈特界
curse of dimensionality 维数灾难
perceptron, Novikoff's bound, XOR 感知机,诺维科夫界,异或
kernel, kernel trick, feature map, Gram matrix 核函数,核技巧,特征映射,格拉姆矩阵
Mercer's theorem, positive semidefinite 默瑟定理,半正定
Gaussian (RBF) kernel, random Fourier features 高斯(RBF)核,随机傅里叶特征
representer theorem, kernel ridge regression 表示定理,核岭回归
support vector machine, margin, support vector 支持向量机,间隔,支持向量
hinge loss, soft margin 铰链损失,软间隔
dual problem, KKT conditions, complementary slackness, duality gap 对偶问题,KKT条件,互补松弛,对偶间隙
sequential minimal optimization (SMO) 序列最小优化(SMO)
decision tree, Gini impurity, split gain 决策树,基尼不纯度,分割增益
bagging, bootstrap resample, out-of-bag estimate 装袋法(bagging),自助重抽样,袋外估计
random forest 随机森林
boosting, AdaBoost, decision stump, exponential loss 提升法,AdaBoost,决策树桩,指数损失
cascade (Viola–Jones), rectangle (Haar-like) feature 级联(维奥拉–琼斯),矩形(类哈尔)特征
gradient boosting, second-order (Newton) boosting, leaf weight 梯度提升,二阶(牛顿)提升,叶子权重
ROC curve, AUC, hit rate, false-alarm rate ROC曲线,曲线下面积(AUC),命中率,误报率
precision, recall, average precision 精确率,召回率,平均精确率
cross-validation, held-out set 交叉验证,留出集
the two cultures (data modeling, algorithmic modeling) 两种文化(数据建模,算法建模)
tabular foundation model 表格基础模型

Sources

Books: T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (2009); C. M. Bishop, Pattern Recognition and Machine Learning (2006); K. P. Murphy, Probabilistic Machine Learning: An Introduction (2022); B. Schölkopf & A. Smola, Learning with Kernels (2002).

Papers, by chapter: Mosteller & Wallace, JASA (1963) and Inference and Disputed Authorship (1964); Legendre (1805); Gauss, Theoria Motus (1809) and Theoria Combinationis (1821–23); Markov (1900); Moore (1920); Penrose (1955); Theil (1950); Sen (1968); Hoerl & Kennard (1970); Tibshirani (1996); Zou & Hastie (2005); Friedman, Hastie & Tibshirani, Regularization Paths for GLMs via Coordinate Descent (2010); Berkson (1944); Nelder & Wedderburn (1972); Soudry et al., The Implicit Bias of Gradient Descent on Separable Data (2018); Platt, Probabilistic Outputs for SVMs (1999); Ng & Jordan, On Discriminative vs. Generative Classifiers (2002); Fisher, The Use of Multiple Measurements in Taxonomic Problems (1936); Fix & Hodges (1951); Cover & Hart, Nearest Neighbor Pattern Classification (1967); Bellman, Dynamic Programming (1957); Rosenblatt (1958); Novikoff (1962); Minsky & Papert, Perceptrons (1969); Mercer (1909); Aizerman, Braverman & Rozonoer (1964); Kimeldorf & Wahba (1971); Schölkopf, Herbrich & Smola, A Generalized Representer Theorem (2001); Boser, Guyon & Vapnik (1992); Cortes & Vapnik, Support-Vector Networks (1995); Platt, Sequential Minimal Optimization (1998); Fan, Chen & Lin (2005); Breiman, Friedman, Olshen & Stone, CART (1984); Quinlan (1986); Breiman, Bagging Predictors (1996); Ho (1995); Breiman, Random Forests (2001); Freund & Schapire (1997); Schapire, Freund, Bartlett & Lee, Boosting the Margin (1998); Friedman, Hastie & Tibshirani, Additive Logistic Regression (2000); Viola & Jones, Rapid Object Detection using a Boosted Cascade of Simple Features (CVPR 2001); Friedman, Greedy Function Approximation (2001); Chen & Guestrin, XGBoost (KDD 2016); Breiman, Statistical Modeling: The Two Cultures (2001); Grinsztajn, Oyallon & Varoquaux, Why do tree-based models still outperform deep learning on typical tabular data? (NeurIPS 2022); Hollmann et al., Accurate predictions on small data with a tabular foundation model (Nature 637, Jan 2025); Prior Labs, TabPFN-2.5 (arXiv 2511.08667, Nov 2025) and TabPFN-3 (arXiv 2605.13986, May 2026); Purucker et al., Beyond IID: How General Are Tabular Foundation Models, Really? (arXiv 2606.30410, June 2026).

About this partfrom its README

Part 6 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan), and the start of Act II, Learning from Data. One task runs through it: who wrote this page, Jane Austen or Charles Dickens? Pages are 1,000-word chunks of five of Part 1's novels (639 pages: Pride and Prejudice and Emma; A Tale of Two Cities, Great Expectations and A Christmas Carol), each described, as Mosteller and Wallace described the Federalist papers, by how often it uses the 70 commonest words; 30% of the pages (191) are held out. The 70-word lexicon is fixed from the complete five-novel corpus without author labels before splitting; this is an unsupervised benchmark definition shared with Parts 7, 8 and 11. Classifier parameters and learned scalers use training pages only. The holdout evaluates new chunks from these same five novels, not previously unseen novels. The pictures use two of the numbers: how often a page says "the", and how often it says "not". Every method is written out in numpy in compute.py (no machine-learning library), every random choice is seeded, and every number on screen or in the narration is computed there. The numbers below are from the reference run (Linux, numpy 2.5); another machine can move the last digits, and the narration follows its own run.

About 51 minutes; a hook, seventeen chapters and an outro.

The evaluation is conditional on that fixed dictionary and five-novel corpus. Training/test curves over penalties, depths or rounds are descriptive diagnostics; they are not independent test sets at every point. Training-only cross-validation chooses the stated settings. The final contest compares twelve named, fixed procedures on the same folds; it is not a comparison at equal computational budgets, and tied mean scores are reported as ties.

The LDA inset whitens the actual pooled within-author covariance with its inverse square root. It connects the means in whitened coordinates, then pulls that normal back with the transpose of the whitening map, giving the full inverse-covariance mean direction. Agreement with least squares means coefficient direction, not necessarily the same intercept or decision threshold. The positive maximizing eigenpair is distinct from zero-eigenvalue stationary directions. The Gaussian-kernel truncation check is one-dimensional, with gamma 1 and both inputs on a 61-point grid in [-1.5, 1.5]; its error is not a dimension-independent/global approximation guarantee.

ROC area credits a tied positive/negative score pair by one half. Log loss is computed stably from out-of-fold logits in nats per page without a probability-clipping cap; probabilities are still used for reliability diagrams and Brier scores. The large-sample qualifier on the nearest-neighbor error bound also applies to the recap.

Chapter notes
  • Hook: who wrote this page? A page; its fingerprint of small words (Mosteller & Wallace, 1963–64); the 639 pages as points; how we got here, from Legendre (1805) to TabPFN (2025); the plan.
  • 1. Least squares. Three points and the squares on their misses (Legendre 1805; Gauss and Ceres, 1801); the fit as Gauss's maximum likelihood under bell-shaped noise (1809), derived; as a perpendicular projection onto the plane of every line's predictions (3D), and the normal equations (Part 3 owns the projection mechanics); Zipf's law on Part 1's 4.33 million words: slope −1.08, R² = 0.996.
  • 2. The best linear unbiased line. The Gauss–Markov theorem (Gauss 1821, Markov 1900) derived: Var β̃ = σ²(AᵀA)⁻¹ + σ²DDᵀ. Checked by 40,000 simulated data sets: least squares' slope variance 0.0103 (theory 0.0104), the end-point slope's 0.0244 (theory 0.0247), both unbiased. Outside the theorem: Theil–Sen (median of pairwise slopes, not linear) loses with Gaussian noise (0.0115) and wins with heavy-tailed noise of the same variance (0.0067 against 0.0101). Solving it: κ(A) = 9.7 on the pages squares to 93 in AᵀA; normal equations and QR agree to 2 × 10⁻¹⁵; with "not" duplicated (rank 71 of 72), the normal equations return weights of size 10¹⁵, while the pseudoinverse splits the weight exactly in half. Least squares as a classifier: 191 of 191 held-out pages.
  • 3. Ridge. Hoerl & Kennard (1970). Derived through the SVD: the fit along direction j is scaled by d_j²/(d_j² + λ). The 70 singular values of the standardized pages (63.4 down to 6.6), with 91% of the authorship signal along the first two directions; the shrinkage factors as λ grows; effective weights Σ d²/(d² + λ); the 70 coefficient paths (smooth, but not necessarily monotone in each coordinate); ridge as the MAP estimate under a Gaussian prior, and weight decay. The near-zero count refers to sampled coefficient/penalty pairs below a numerical tolerance, not mathematically exact zeros. Ten-fold cross-validation (mean ± 1 s.e.) picks λ ≈ 75 (54 effective weights), 99.5% on the held-out pages.
  • 4. The lasso. Tibshirani (1996): the diamond's corner; the soft threshold derived from subgradients; coordinate descent (Friedman, Hastie & Tibshirani, glmnet 2010) along 61 penalties, KKT conditions checked at every one (worst violation 1.6 × 10⁻⁹); the first eight words (not, she, very, be, out, such, to, mrs) give 90%; the ten-fold cross-validated error curve (± 1 s.e.) is lowest at 57 words and nearly flat there, and the one-standard-error rule keeps 46 words (99.5%). Zou & Hastie's elastic net (2005) on a near-copy of "not": the lasso picks one twin, the elastic net shares.
  • 5. Logistic regression. Score, line and sigmoid; the probability sheet with the pages lifted to 0 and 1 (3D); cross-entropy 0.51 bits per page; convexity derived (gradient Xᵀ(p − y), Hessian XᵀSX/n ⪰ 0; eigenvalues at the answer 0.043, 0.050, 0.119); gradient descent replayed, the line swinging into place; 82% with two rates, 190 of 191 with seventy.
  • 6. Newton's method. Newton = iteratively reweighted least squares (Nelder & Wedderburn 1972), derived; Newton against gradient descent on the plane, step by step; on all 70 rates Newton reaches the minimum to machine precision in 8 steps, gradient descent needs 1,000 steps to get within 10⁻⁶; the correct digits per Newton step (… 4.3, 7.1, 12.6: roughly doubling, quadratic convergence). With 70 rates the training pages are separable: as the penalty weakens 10⁶-fold the weights grow from 1.2 to 12.0 without end (Soudry et al. 2018: gradient descent then turns toward the max-margin direction).
  • 7. Naive Bayes. Multinomial naive Bayes derived: its log-odds are linear in the word counts; generative against discriminative; what it learned by counting (Austen: mrs, she, very; Dickens: out, up, me). Ng & Jordan (2002) reproduced: over many random training sets, naive Bayes has the lower error up to 8 pages, logistic regression from 12 pages on, ending at 0.5% against 5.8%. Calibration (ten-fold cross-validated probabilities): logistic regression's expected calibration error 0.039; naive Bayes gives 90% of pages odds beyond a million to one (ECE 0.042), and Platt scaling (1999) brings it to 0.011.
  • 8. Fisher's direction. Fisher (1936): the separation along every direction, the best one; S_W⁻¹ pictured as rounding the clouds; why the cut is Bayes-optimal for two equal-shaped Gaussians (log-odds linear: logistic regression's form with Fisher's direction); the generalized eigenproblem S_B w = J S_W w derived; on 70 rates one nonzero eigenvalue (S_B has rank 1), its eigenvector equal to the formula and to least squares on a 0/1 target (cosines 1.000000); 82% with two rates, 100% with seventy.
  • 9. Neighbours, and the curse of dimensionality. Fix & Hodges (1951); a 15-neighbour vote; regions as k grows (k = 1: 93% of training pages, 68% of new ones; best on held-out pages at k = 15, 84%; cross-validation picks k = 125, 82%). Cover & Hart (1967) sketched: R* ≤ E 2η(1 − η) ≤ 2R*(1 − R*), checked on two Gaussians (R* = 21.2%, limit 29.2%, bound 33.4%; 1-NN at n = 10,000: 29.5%; √n neighbours: 21.5%). The curse (Bellman 1957): the nearest of 2,000 points in a cube is 0.1% of the average distance in 1D and 94% in 1,000D; a cube holding 10% of the data has side 0.79 in 10D; adding 1,000 noise columns drops 15-NN from 98% to 88%, logistic regression only from 99.5% to 97%.
  • 10. Kernels. Rosenblatt's perceptron (1958) and Novikoff's bound (1 mistake on the toy, bound 15); XOR: 400 mistakes in 100 passes; Minsky & Papert (1969); add x₁x₂ and it separates after 4. Circles lifted onto a paraboloid (3D), the separating plane found by a hard-margin SVM. The trick: (x·z + 1)² = φ(x)·φ(z), checked to 10⁻¹⁴; the Gaussian kernel's infinite Taylor features (20 kept: 7 × 10⁻⁸). Mercer (1909): the Gaussian Gram matrix on the 448 training pages has no negative eigenvalues (smallest −2 × 10⁻¹⁴, rounding); tanh(x·z − 1) has 138. The representer theorem (Kimeldorf & Wahba 1971; Schölkopf, Herbrich & Smola 2001) derived, and checked: ridge in 2,000 random Gaussian features lies in the span of the pages' features to 2 × 10⁻¹⁴.
  • 11. The widest street. The margin derived (min ½‖w‖²); the toy's 3 support vectors; hinge, logistic, exponential and 0–1 losses; the dual derived with Lagrange multipliers and KKT (Part 4 owns them); complementary slackness; SMO (Platt 1998; Fan, Chen & Lin's working-set rule) written out and run on the pages with a Gaussian kernel: C from 0.01 to 100, support vectors 407 → 169, relative primal-dual gaps up to 3.8 × 10⁻⁶. At C = 1, outside/bound margin checks have zero violations at tolerance 10⁻³; the maximum free-margin residual is 5.6 × 10⁻⁵. the ten-fold cross-validated grid over C and γ (best 83.9%, 12 of the 25 settings within a point of it, worst 54.9% at tiny C); cross-validation picks C = 0.1, γ = 0.1 (81% held out); 99.5% with all 70 rates. Cortes & Vapnik (1995).
  • 12. Trees. The learned depth-3 tree and its boxes; Gini, entropy and error rate; why a strictly concave impurity always rewards a useful split (Jensen), and the scan of every threshold on "not" (all three pick 8.5); accuracy against depth (best held out at depth 4, 83%; cross-validation picks 3; grown fully: 94% train, 74% new). CART (Breiman, Friedman, Olshen & Stone 1984). Fragility: depth-3 trees on 20 bootstrap resamples (70 rates) start with 3 different words (not 10, mrs 7, she 3) and score 80–93% held out.
  • 13. Bagging and random forests. Var = ρσ² + (1 − ρ)σ²/B derived and checked by simulation (ρ = ½, B = 100: 0.512 against 0.505); measured on the pages over 30 training sets of 150 pages: bagging ρ = 0.109, σ² = 0.118; eight random words ρ = 0.013, σ² = 0.146; two words ρ = 0.007. A forest of 300 (Breiman 2001, after Ho 1995): one tree 93.7%, bagging 99.5%, forest 100% (191 of 191); out-of-bag estimate 98%.
  • 14. AdaBoost. Freund & Schapire (1997); the weights piling onto hard pages (2 rates); the exponential-loss derivation of α = ½ log((1 − ε)/ε) (Friedman, Hastie & Tibshirani 2000), checked against a numerical search (3 × 10⁻⁶); on 70 rates the training error reaches 0 at round 19, with held-out error 3.7%. The observed held-out minimum is 0.5% at round 45; the final value at round 400 is 1.6%, so the improvement is not monotone (margins: Schapire et al. 1998). Viola & Jones (2001): rectangle features, a boosted cascade, 384 × 288 at 15 frames a second on a 700 MHz Pentium III (schematic).
  • 15. Gradient boosting, second order. Friedman (2001); XGBoost's second-order objective, leaf weight −G/(H + λ) and split gain derived (Chen & Guestrin 2016), checked on the first split ("mrs" ≤ 0.5: formula 92.797, direct evaluation 92.797, true drop 100.55); boosting on the two rates as it learns (best after 4 rounds, 83.2%, slipping to 77.5% by 200); on 70 rates Newton leaves reach 0.0066 bits against 0.042 for first-order leaves, 99.0% against 95.8% held out.
  • 16. Keeping score. The ROC curve traced by sweeping the threshold (cross-validated logistic regression on two rates): AUC 0.9095, equal to the share of correctly ranked (Dickens, Austen) pairs (Mann–Whitney); with Dickens made rare (15 pages against 288), "always Austen" is 95% accurate, the ROC area stays 0.91, average precision falls from 0.93 to 0.57; accuracy against log loss (ten-fold cross-validated probabilities): Platt scaling leaves naive Bayes' 95.6% accuracy unchanged but cuts its log loss from 0.478 to 0.088 nats per page (logistic regression on 70 rates: 0.034); one 70/30 split's accuracy ranges 77.5–88.5% over 100 splits, ten-fold cross-validation over 20 shuffles 82.9–83.7%.
  • 17. The contest, and two cultures. Every method on the same ten folds of all 639 pages (mean ± s.d.): with 2 rates, the tested procedures score 76–83% on these folds, an empirical comparison rather than an information ceiling; with 70, logistic regression and the Gaussian SVM 99.5%, the lasso 99.4%, LDA and least squares 99.2%, AdaBoost 99.1%, the forest 98.4%, gradient boosting 98.3%, k-NN 98.3%, naive Bayes 95.8%, one tree 93.0%. Breiman's two cultures (2001); the Netflix Prize (2006–09), Kaggle (2010), XGBoost in 17 of 29 Kaggle-blog winners of 2015; why trees still win on tables (Grinsztajn, Oyallon & Varoquaux 2022); foundation models for tables: TabPFN (Hollmann et al., Nature, Jan 2025; the reported \(2.8\)-second comparison is its classification benchmark configuration, against an ensemble tuned for four hours), TabPFN-2.5 (Nov 2025), and TabPFN-3 (May 2026; its million-row capacity claim is at 200 features, and its TabArena lead is the authors' report). These dates identify the cited publications or preprint submissions. The broader June 2026 Beyond IID benchmark tests TabPFN-2.6, not TabPFN-3, and includes model authors among its coauthors (see its Competing Interests disclosure). Foundation models are strong on small and medium IID tables; traditional tree and deep baselines expose boundary cases on non-IID, large or high-dimensional data. These findings are version- and task-specific. The chapter then shows how the classics live on inside today's models (the softmax, linear probes and weight decay, sparse autoencoders' L1, the neural tangent kernel and attention as a kernel smoother, retrieval, calibration).
  • Outro. Twelve pictures from the part's results; where it comes back (Parts 7, 8, 9, 11, 13, 31); eight problems; Part 7's teaser; references.
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Least squares as projection (3D column space); Gauss–Markov; pseudoinverse and QR.
  2. Ridge as SVD shrinkage σ²/(σ²+λ); lasso via soft-thresholding and its computed path; elastic net.
  3. Logistic regression: convexity (XᵀSX), Newton/IRLS; calibration.
  4. Naive Bayes vs logistic (generative vs discriminative).
  5. Fisher's LDA as a generalized eigenproblem.
  6. k-NN and the Cover–Hart bound; the curse of dimensionality.
  7. Kernels: the trick, Mercer, RBF feature space, the representer theorem.
  8. SVM: margin, hinge, the dual via KKT, support vectors.
  9. Trees: Gini/entropy splits.
  10. Bagging's ρσ² + (1−ρ)σ²/B and random forests.
  11. Boosting: AdaBoost as exponential loss; gradient boosting with XGBoost's second-order split gain.
  12. Metrics: ROC/AUC, precision-recall, cross-validation; the authorship contest.
  13. History: Fisher (1936), the SVM era (Vapnik 1995), Viola–Jones (2001): boosting finds faces in real time.

Visuals: a kernel lifting circles to 3D, where a plane separates them; decision boundaries morphing with k and C.

Build the film

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

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

Build it

From the repo root:

python tools/make.py ai6                 # everything: Part 1's books if missing, the numbers, both languages
python -m videos.ai.ai6.compute          # only the numbers (about 15 CPU-minutes, one core; resumable)
python tools/build.py ai6                # English
python tools/build.py ai6 --lang zh      # Chinese
EXPLAINER_TTS=silent python tools/build.py ai6 -q l --fps 15   # a quick silent preview

compute.py items are cached in .cache/ai6/; the two longest (bagging, board) save each piece as it finishes and resume. Other parts read load("pages"), split() and standardize() from here (Parts 7, 8 and 11).