CComputer Science, Built

Act XI · The Research Frontier

Part 57 of 61

Learning Theory

Researchstarts at this level49 min of film12 chaptersprerequisites: Part 20, Part 23, Part 29, Part 44

When can a machine learn from examples, and how many does it need?

The part opens on a linear model fitted to fifty noisy examples: its test error explodes when the number of features reaches fifty and then falls below every smaller model's, which no count of parameters explains. Valiant's definition makes the question exact, and a hidden rectangle is learned with (4/epsilon) ln(4/delta) examples. For infinite classes one number decides, the VC dimension: half-planes shatter three points and no four, and Sauer-Shelah turns that into a polynomial count of labellings. Margins, not dimensions, govern the perceptron, whose mistakes stay flat from a hundred dimensions to a thousand, and AdaBoost, whose test error keeps falling after the training error is zero. Against an adversary the measure is regret: Hedge keeps it under the square root of T ln N / 2 while follow the leader loses almost every round, and bandits pay a logarithm for what they do not see. The part then turns to what cannot be learned efficiently, with cryptography and with statistical queries that cannot find a parity, and returns to the opening curve through the minimum-norm interpolator. It ends with learning as compression and with Warmuth's conjecture that every class of VC dimension d has a compression scheme of size O(d).

What you need. Probability to Hoeffding's inequality and the union bound; linear algebra to the pseudo-inverse. AI, Built shows the learners themselves.

Mathematics, ideas and history
PAC, VC dimension and Sauer–Shelah, Rademacher and margins, boosting, online learning and regret, bandits, SQ lower bounds, benign overfitting
What we build or compute
learning curves against VC bounds; regret curves

What you will be able to do

Degree

  • State what probably approximately correct means, with its epsilon and its delta.
  • Compute the sample size that suffices for a finite class, and learn a rectangle by the tightest box.

Graduate

  • Find the VC dimension of a simple class by exhibiting a shattered set and proving that no larger set is shattered.
  • Run the perceptron and bound its mistakes by Novikoff's argument.
  • Run Hedge and UCB1 by hand for a few rounds and state the regret each guarantees.

Research

  • Prove the Sauer-Shelah lemma, and Hedge's regret bound with Hoeffding's lemma.
  • Prove that a statistical query of tolerance tau is informative about at most 1/tau^2 parities.
  • State the sample compression conjecture and what Moran and Yehudayoff proved.

Industry

  • Choose a stopping round for boosting from training and test curves when labels are noisy.
  • Choose between explore-then-commit, UCB1 and Thompson sampling for an experiment, and say what regret to expect.
  • Say why a parameter count does not predict the test error of an interpolating model.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 9 min · Graduate 19 min · Research 49 min · Industry 19 min.

  1. 0When is learning possible?Degree2 min
  2. 1Probably approximately correctDegree5 min
  3. 2VC dimensionResearch5 min
  4. 3Margins and Rademacher complexityResearch5 min
  5. 4BoostingIndustry5 min
  6. 5Learning onlineResearch5 min
  7. 6BanditsIndustry5 min
  8. 7What cannot be learnedResearch5 min
  9. 8More parameters than dataResearch5 min
  10. 9Learning is compressionResearch4 min
  11. 10Frontier: compression schemes and in-context learningResearch2 min
  12. Recap, problems, and where this comes backAll 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.

When is learning possible?Degree2 min

Here is a puzzle that learning theory had to face. We fit fifty noisy examples with a linear model that uses p features. With few features the model is too simple. As p grows, the error on new data rises, slowly and then steeply, the classical picture of overfitting. At p equal to fifty the model can fit anything, noise included, and the test error explodes. And then, past that point, adding still more parameters makes the error fall again, to below where it started: at 200 features it is lower than any model with fewer parameters than examples. This is double descent. To understand it we first need the classical theory: when is learning possible at all, and how many examples does it take?

AI, Built showed machines that learn. This part asks what can be proved about them. How many examples does a learner need before its answers are probably approximately correct? Leslie Valiant made the question precise in 1984, and the answer is a single number, the VC dimension. What if no distribution exists and an adversary picks every example? Then the right measure is regret, and the answers include the bandits of Part 44. And what can never be learned efficiently, however much data there is? There the answers come from cryptography.

1Probably approximately correctDegree5 min

In 1984 Leslie Valiant asked what it should mean for a machine to learn from examples. Nature fixes a distribution over inputs, which the learner never sees, and a target from a class the learner knows: here, a hidden rectangle. The learner receives m examples, each drawn from the distribution with its label, and returns a hypothesis: here, the tightest box around the positive points. Its error is the probability of the region where hypothesis and target disagree, shaded red. Valiant asked that, with probability at least one minus delta over the sample, the error be at most epsilon, for every distribution and every target, using examples and computation polynomial in one over epsilon and one over delta. Probably, approximately, correct.

Start with a finite class that contains a perfect hypothesis, the realizable case, and call a hypothesis bad if its error exceeds epsilon. A fixed bad hypothesis survives each random example with probability less than one minus epsilon, so it survives all m of them with probability at most e to the minus epsilon m. By the union bound of Part 2, the chance that any bad hypothesis survives is at most the class size times that. Ask for this to be at most delta, and solve: m at least one over epsilon, times the log of the class size plus the log of one over delta. For a thousand hypotheses, with epsilon and delta both five hundredths, a hundred and ninety-nine examples suffice, whichever consistent hypothesis is returned. The class size enters only through its logarithm.

Usually no hypothesis is perfect. The agnostic model asks only that the learner come within epsilon of the best one in the class, and the natural learner minimizes its error on the sample. For a fixed hypothesis, the sample error averages m independent coin flips, and Hoeffding's inequality from Part 20 says it strays more than epsilon from the truth with probability at most two e to the minus two m epsilon squared. A union bound covers the whole class, and solving gives m of order the log of the class size over epsilon squared. Then the best hypothesis on the sample is within two epsilon of the best of all. Noise costs a square: for the same thousand hypotheses, two thousand one hundred and twenty examples, more than ten times as many.

Most interesting classes are infinite, rectangles for instance, and yet rectangles can be learned, by the argument that opens Kearns and Vazirani's textbook. The learner returns the tightest box around the positive examples, which sits inside the target. Draw four strips along the target's sides, each of probability epsilon over four. If an example lands in every strip, the box misses only parts of the strips, so its error is at most epsilon. One strip is missed by all m examples with probability one minus epsilon over four, to the m. A union bound over the four strips, set below delta, gives four over epsilon times the log of four over delta examples, with no class size anywhere.

How loose is that? Our instrument learned this rectangle two hundred times at each of eight sample sizes. The mean error falls like one over m. The ninety-fifth percentile is the error beaten with probability one minus delta, which is what the theorem bounds. The bound lies above it everywhere; from a hundred examples on, by a factor of two to three. That constant is the price of a guarantee for every distribution, not just the uniform one we sampled.

So what replaces the size of the class? For half-planes, as for rectangles, it is infinite. But a learner only meets what the class does on its sample. Ten points can be labelled in a thousand and twenty-four ways. Half-planes produce only ninety-two of them; our instrument checked every labelling with a linear program. That count of behaviours, the growth function, can take the place of the class size, and Chapter two shows that one number, the VC dimension, controls it.

2VC dimensionResearch5 min

In 1971 Vladimir Vapnik and Alexey Chervonenkis measured an infinite class not by its size but by how many ways it can label points. Take three points in the plane, not on a line, and colour each green or red: there are eight ways. For every one of them a line puts the greens on one side and the reds on the other; our instrument checked each with a linear program. A class that realizes every labelling of a set is said to shatter it, and the VC dimension is the size of the largest set the class shatters. For half-planes it is at least three.

Can half-planes shatter four points? At the corners of a square, fourteen of the sixteen labellings are separable, but not the two that colour opposite corners alike. A half-plane holding both green points holds the segment between them; the other side holds the red segment; the diagonals cross, so no line works. If one point lies inside the triangle of the others, colour it apart, and the same argument applies. Every four points fall into one of these cases: Radon's theorem of 1921, which in d dimensions splits any d plus two points. So half-planes have VC dimension three, half-spaces in d dimensions d plus one, and rectangles four. A lower bound needs one shattered set; an upper bound must defeat every set.

Behind the VC dimension is a function. The growth function counts, for each m, the most labellings the class produces on any m points. A class that shattered everything would follow two to the m, the grey line: a thousand and twenty-four at ten points. Half-planes, counted labelling by labelling, follow it up to three points, the VC dimension, and then fall away, to ninety-two, which is m squared minus m plus two. The yellow curve is the bound we are about to prove from the VC dimension alone. Past the VC dimension, growth is only polynomial.

Norbert Sauer and Saharon Shelah proved independently, in 1972, why. If the VC dimension is d, the growth function is at most the number of subsets of size at most d. Here are the fourteen labellings of the square's corners, grouped by the first three points. The rows form H one; the boxed rows, which occur with both labels of the last point, form H two. Fourteen is eight plus six. Induct. H one shatters at most d points; H two at most d minus one, or the class would shatter that set plus the last point. Write both bounds as sums, and Pascal's rule adds them into the sum for m: for m at least d, at most e m over d, to the d. A polynomial.

The growth function can now replace the class size, through a ghost sample. Draw m more points. If a consistent hypothesis has true error above epsilon, with probability at least a half it errs on epsilon m over two ghost points. So the bad event costs at most twice an event about two m points. On those, the class has at most the growth function of two m behaviours, and a random swap between the halves hides all k mistakes of one in the ghost half with probability at most two to the minus k. Set this to delta and solve, and Sauer and Shelah turn the growth function into d times a logarithm. For rectangles d is four: the bound is valid, but an order of magnitude above our measurement. It knows only the VC dimension.

Together these give the fundamental theorem of PAC learning, made explicit by Blumer, Ehrenfeucht, Haussler and Warmuth in 1989. For binary classification, four things are equivalent: finite VC dimension, uniform convergence, learnability by any sample-error minimizer, and agnostic learnability. The examples needed are pinned down: about d over epsilon when a perfect hypothesis exists, d over epsilon squared when none does. The converse is the no free lunch argument: if the class shatters two m points, a learner that has seen m of them knows nothing about the rest. Some target forces error at least an eighth with probability at least a seventh. With infinite VC dimension, no amount of data is enough.

3Margins and Rademacher complexityResearch5 min

The oldest learning machine is the one Part 7 put inside a processor. Frank Rosenblatt's perceptron, from 1958, predicts with the sign of a weighted sum. When it is wrong, it adds the example, with its sign, to the weights; otherwise it does nothing. Watch it on points that some line separates. Each mistake swings the yellow line, until no point is on the wrong side. What controls the number of mistakes? Not the number of points, and not the dimension, but the margin: the width of the empty band around the best separator, against the radius of the data. Albert Novikoff proved in 1962 that the perceptron makes at most R over gamma, squared, mistakes, however long it runs.

The proof watches two quantities. Assume every example has length at most R, and a unit vector w star separates them with margin gamma. First, progress. A mistake adds y x, whose projection on w star is at least gamma, so after k mistakes the projection is at least k gamma: linear growth. Second, length. The squared length grows by twice y w dot x, which is not positive on a mistake, plus at most R squared. So after k mistakes the length is at most root k times R: square-root growth. A projection never exceeds a length. So k gamma is at most root k R, and k is at most R over gamma, squared. A line cannot stay under a square root for long: with radius one and margin a tenth, a hundred mistakes at most.

Our instrument tested the claim. It placed two thousand points on the unit sphere, all at least a tenth from a random hyperplane, in two, ten, a hundred and a thousand dimensions, and ran the perceptron to a clean pass. The mistakes were four, twenty-three, thirty-eight and thirty-four: all under Novikoff's hundred, and flat from a hundred dimensions to a thousand. A VC bound for half-spaces grows with the dimension; the margin bound sees only the geometry. Part 7's branch predictor runs this update in hardware, but branch histories are rarely separable, so there the guarantee does not hold, and only the mistake rate can be measured.

Margins need a complexity measure that is not a count. Rademacher complexity asks how well the class can fit pure noise. Flip a fair coin for each sample point to get random labels, find the hypothesis that agrees with them best, and average that agreement over the coins. For thresholds on a line, the best threshold catches only part of each draw's noise. A class that shatters the sample matches every draw perfectly; it can explain anything, so its fit to real data proves nothing. The theorem, in the form of Peter Bartlett and Shahar Mendelson in 2002: with probability one minus delta, every hypothesis's true error is at most its sample error, plus twice the Rademacher complexity, plus a term of order one over root m. Massart's lemma bounds the complexity by the growth function, so the VC bounds follow; with margins it can be far smaller.

For linear classifiers with bounded weights, the Rademacher complexity takes five lines. The supremum over weights of length at most lambda, of w dotted with the sum of signed points, is lambda times the length of that sum, by Cauchy and Schwarz. Jensen's inequality moves the expectation inside a square root. Expanding the square, the cross terms vanish, because independent signs are uncorrelated, and what remains is lambda R over root m. The dimension never appears. Vladimir Koltchinskii and Dmitry Panchenko made this a margin bound in 2002: true error is at most the fraction of sample points with margin below rho, plus a term in R over rho, over root m. R over rho, squared, plays the part of a dimension: exactly Novikoff's quantity. Support vector machines, from Corinna Cortes and Vapnik in 1995, maximize that margin directly. Boosting, as we will see next, does too.

4BoostingIndustry5 min

A strong learner reaches any error with any confidence. A weak learner promises only an error a little below a half, on every distribution. Here no single rule will do: four hundred points, green inside a circle. Our weak learner draws decision stumps, one threshold on one coordinate. With equal weights, the best stump says outside everywhere, wrong on the green twenty-eight and a half per cent. Change the weights and the best stump changes: now it cuts at about point six, with weighted error a third. Michael Kearns and Leslie Valiant asked whether weak learning is really weaker. In 1990 Robert Schapire proved it is not.

Freund and Schapire's AdaBoost, from 1995, made boosting practical. Keep a weight on every example, equal at first. Each round, ask the weak learner for a rule with small weighted error, and give it a vote that grows as its error shrinks. Then re-weight: examples it got wrong are multiplied up, the rest down, and the weights are normalized. Watch after one, two, five and twenty rounds: easy points far from the circle shrink, and weight piles up on the boundary, where the heaviest point carries about four and a half times its first share. The final classifier is a weighted majority vote.

Freund and Schapire proved that the training error falls exponentially. Unroll the update: each final weight is e to the minus y F, F being the weighted vote, over m and the product of the normalizers. On a training mistake y F is not positive, so e to the minus y F is at least one, and the training error is at most the average of e to the minus y F. The final weights sum to one, so that average is the product of the normalizers. With AdaBoost's vote, each normalizer is two root epsilon times one minus epsilon. With error a half minus the edge gamma, that is root of one minus four gamma squared, at most e to the minus two gamma squared. So the training error is at most e to the minus twice the sum of squared edges. On our circle it first hit zero at round fifty-seven, and stayed there from round a hundred and eight.

Freund and Schapire also showed that boosting is a game. Make a matrix with a row per example and a column per weak rule, green where the rule is right. The booster picks a distribution over rows; the weak learner answers with the best column. Weak learnability says some column always has an edge of two gamma. Von Neumann's minimax theorem then gives a weighted vote of columns that is right by a margin of two gamma on every row. AdaBoost's re-weighting is multiplicative weights, from Part 23, played on the rows: watch weight move onto the rows the last chosen rule got wrong. Its vote approaches the minimax one.

Then came a surprise. Training error is zero for good from round a hundred and eight, and classical intuition says more rounds only add complexity, so test error should rise. It does not: it hovers near three per cent for two hundred more rounds. The explanation, from Schapire, Freund, Peter Bartlett and Wee Sun Lee in 1998, is the margin: how decisively the normalized vote gets an example right. Here are the training margins after five, twenty, a hundred and three hundred rounds: long after every point is correct, boosting keeps pushing the smallest up. Their theorem bounds test error by the fraction of training margins below theta, plus a term in the weak rules' VC dimension and theta, not the number of rounds.

The same mechanism is boosting's weakness. Flip five per cent of the labels. Every sensible rule gets a flipped point wrong, so its weight is multiplied up round after round. By round twenty the twenty-three flipped points, under six per cent of the data, hold eighteen per cent of the weight. Test error, on equally noisy test labels, is lowest at round twenty-seven and then creeps up, as boosting memorizes the mistakes. The remedies are to stop early or shrink each vote; Jerome Friedman's gradient boosting of 2001 extended the idea to any loss. AdaBoost won Freund and Schapire the Gödel Prize in 2003.

5Learning onlineResearch5 min

Now drop the distribution. An adversary picks each example, we predict its label, then see the truth, and we count mistakes. Suppose one of N hypotheses is perfect. The halving algorithm keeps those still consistent and predicts with their majority. A mistake means the majority was wrong, so at least half are thrown away, and the true one never is. So there are at most log two of N mistakes: for a thousand and twenty-four thresholds, ten. On random examples it made two in two hundred rounds. An adversary who asks about the middle of the survivors forces all ten. Nick Littlestone showed in 1988 that the best mistake bound of a class is one number, its Littlestone dimension. For thresholds on the whole line it is infinite, though their VC dimension is one.

Usually no expert is perfect. Littlestone and Manfred Warmuth's weighted majority, published in 1994, starts every expert at weight one, predicts with the weighted vote, and halves every expert that is wrong. If the algorithm errs, at least half the weight voted wrong and is halved, so the total falls to three quarters at most. The best expert, with m mistakes, still holds a half to the m. Take logarithms: at most about two point four times the best expert's mistakes, plus log two of N. No deterministic rule can do much better, since an adversary can make it wrong every round. So we randomize.

Freund and Schapire's Hedge, from 1997, plays expert i with probability proportional to its weight, and multiplies each weight by e to the minus eta times that expert's loss. Regret is its expected loss minus the best expert's. Watch the log of the total weight. From below: the total is at least the best expert's weight. From above: each round, by Hoeffding's lemma, the log falls by eta times our expected loss, give or take eta squared over eight. Add up the rounds, put the two together, and choose eta as the root of eight log N over T: the regret is at most the root of T log N over two. Per round it goes to zero. It is Part 23's multiplicative weights again.

Hedge against twenty experts with random losses for two thousand rounds, one slightly better than the rest. The dashed line is the guarantee for this eta, reaching fifty-four point seven. The measured regret climbs while Hedge finds the best expert, then flattens at thirty point seven. On losses this random, following the leader does even better: nine. But an adversary can ruin it: two experts whose losses alternate, so the leader is always the one about to lose. Follow the leader loses almost every round, each expert half of them, and its regret grows linearly.

Could a cleverer algorithm beat root T? No. Take two experts and flip a fair coin each round to decide which one loses. Whatever we play, we lose a half per round on average: T over two. But the luckier expert loses T over two minus the distance expert one's count has wandered. That is a random walk; here are ten. Its average distance is about the root of T over two pi, so every algorithm suffers regret of about point four root T. With N experts the same idea gives Hedge's own root of T log N over two: its constant cannot be improved.

The experts are one case of a larger game. Each round we choose a point, then the adversary reveals a convex loss. Martin Zinkevich showed in 2003 that Part 23's gradient descent works here: step against this round's gradient, and project back into the allowed set. Here the losses are parabolas whose centres jump about, and our point chases them. With D the set's diameter and G a bound on the gradients, the regret is at most D squared over two eta plus eta G squared T over two; with the best eta, D G root T. And online turns into batch: feed a training set in one example at a time and average the points played. By convexity the average's expected risk exceeds the best by at most the regret over T.

6BanditsIndustry5 min

Herbert Robbins posed this problem in 1952. A row of slot machines, each paying out with its own hidden probability. Each round we pull one arm and see only its reward. To find the best arm we must explore; to earn, we must exploit. The measure is regret: what always pulling the best arm would earn, minus what we earn. Grouped by arm, it is each arm's gap times how often we pull it. Our four arms pay a half, point four five, point four and point three. Part 44's A/B test explores evenly for a fixed time, then commits, paying for every pull of a worse arm. A bandit algorithm adapts as it goes.

The first strategy is optimism. For each arm keep the average reward, plus a bonus that shrinks as the arm is pulled: the root of two log t over its pull count. Pull the arm whose index, its plausible best case, is highest. By Hoeffding, the true mean exceeds the average by epsilon with probability at most e to the minus two n epsilon squared. With this bonus, the index falls below the truth with probability at most t to the minus four. The bad arms' bars shrink as they are tried, until they no longer reach the best arm's; after that they are tried only as often as log t grows.

Peter Auer, Nicolò Cesa-Bianchi and Paul Fischer proved in 2002 that this index, UCB1, has regret growing only like log T. Picture a bad arm, a gap delta below the best. Its average is at most w above its mean, and its index adds another w. If we pull it, its index beat the best arm's, which is above mu star. So mu i plus two w reaches mu star, barring a rare failure. Solve: at most eight log T over delta squared pulls. Multiply by the gaps and add a constant for the failures. For our arms over five thousand rounds that is about two thousand four hundred, against a measured hundred and fifty-nine: true, but loose.

The second strategy is older. William Thompson proposed it in 1933, with medical treatments in mind. Keep a posterior for each arm's mean: with a uniform prior, a beta distribution set by its wins and losses. Well-tried arms are narrow, rarely tried ones wide. Each round, draw one guess from every posterior and pull the arm whose guess is highest. Then each arm is pulled with exactly the probability that it is the best, given the data, so uncertain arms still get their chances. In 2012 it was proved to meet the optimal rate for such arms.

Here are the three strategies on our arms, averaged over a hundred runs of five thousand rounds. Epsilon-greedy explores at random one round in twenty, and pays for that forever: its regret ends up linear. UCB1 and Thompson sampling bend over. How far can anyone bend? Tze Leung Lai and Robbins proved in 1985 that any policy good on every problem must pull each bad arm about log T over the divergence between its coin and the best coin. For our arms that is seventeen point four log T. UCB1, at a hundred and fifty-nine, sits above it; Thompson, at about fifty, below it at this T, which the theorem allows: it is about the rate as T grows.

Why can nobody beat log T? Take a bad arm paying point four five. In another world it pays point five and is the best. After twenty pulls the worlds look alike; after two hundred they part; after two thousand they are clear. The chance of confusing them falls like e to the minus n times their divergence. Confusion in the second world costs a share of every round, so that chance must be about one over T, and n at least log T over the divergence. And if an adversary sets the gap at root K over T, T rounds cannot find the best arm: regret about root K T. Bandits now run recommendation and ad allocation, at the price of a cleaner experiment.

7What cannot be learnedResearch5 min

Data is rarely what limits learning. There are at most two to the order s log s circuits of size s, so chapter one's bound says polynomially many examples suffice. The trouble is time: finding a hypothesis that fits. Take formulas that are an or of three ands, like this one. Leonard Pitt and Valiant proved in 1988 that finding such a formula consistent with the data is NP-hard. But distribute the or over the ands: the same function is an and of clauses, each taking one literal from each term. Clauses of three literals are few, and Valiant's elimination learns them in polynomial time. The class is easy; its own representation was hard. So real limits must hold whatever the learner outputs.

Michael Kearns and Leslie Valiant found such limits in cryptography; the journal version appeared in 1994. Take a public-key cryptosystem. Anyone with the public key can encrypt random bits, so anyone can make labelled examples: a ciphertext, and the bit inside it. The target concept is the decryption function. If some class of functions can compute decryption, a learner for that class, fed these examples, returns a hypothesis that decrypts a fresh challenge better than chance. That breaks the cryptosystem. So, if RSA or factoring is hard, no efficient algorithm learns small Boolean formulas or finite automata, whatever it outputs. And if pseudorandom functions exist, from Part 29, small circuits cannot be learned even by asking questions.

Kearns also defined a gentler kind of learner. A statistical-query learner never looks at single examples; it asks for the average of some function of an example and its label, and gets it to within a tolerance tau. Such learners survive noisy labels, and gradient descent on an average loss is one. Now let the label be the parity of an unknown set of k bits. Different parities are orthogonal. Any query splits into a part that ignores the label and a part that correlates with it, and only the second depends on the set. By Bessel's inequality those correlations have squares summing to at most one, so each query is informative about at most one over tau squared sets. The rest look identical, so finding the set takes at least tau squared times n choose k queries.

Here are sparse parities of three bits among n, from four hundred random examples. No single bit correlates with the label beyond the sampling noise. A search over sets of three bits must try up to n choose three of them, and it did: fifteen hundred and eight of fifteen hundred and forty at n equal to twenty-two. Yet parity is easy for algebra. Each example is a linear equation over the field of two elements, and Gaussian elimination, from Part 52, done over that field, solves it from about two n examples in under a millisecond. Parity is learnable, just not by statistics. Flip a few labels and elimination breaks. Learning parity with noise is believed hard; the best known algorithm, by Avrim Blum, Adam Kalai and Hal Wasserman, takes time two to the n over log n. It is Part 7's parity branch again: no single history bit predicts it.

So the map of what can be learned has three walls. The outer wall is statistical: a class with infinite VC dimension cannot be learned from any amount of data. Inside it, the computational wall. Small formulas, automata and circuits need few examples, but learning them would break cryptography. Inside that, the statistical-query wall. Conjunctions and halfspaces with a margin sit inside it and survive noise; parities sit between, learnable only by algebra that a single wrong label spoils. Avrim Blum and colleagues showed in 1994 that this wall is set by one number, the statistical-query dimension: how many nearly orthogonal functions a class contains.

8More parameters than dataResearch5 min

Here is the experiment of the hook again, with both errors. Fifty noisy examples; a linear model on the first p of two hundred Gaussian features, fitted by least squares, choosing the smallest solution when there are many. The training error falls as p grows, and from p equal to fifty on it is zero, up to the rounding of Part 4's floating point: the model interpolates, noise and all. The test error rises to fifty-two at the threshold, then falls, to point seven eight at two hundred parameters, below the one point oh three of the smallest model. Mikhail Belkin, Daniel Hsu, Siyuan Ma and Soumik Mandal named this double descent in 2019. In this simple setting there is no first valley at all: a classical textbook would have stopped at the smallest model, and missed the better one beyond.

Why is this a puzzle? Chapter three measured a class by how well it fits pure noise: random signs, and the best correlation the class can achieve with them. A model with at least as many parameters as examples fits any labelling at all, so that complexity takes its largest value, one. And the bound becomes useless: test error at most the training error, zero, plus one, plus more. Chiyuan Zhang and colleagues showed in 2017 that real networks are like this. Standard image networks fitted CIFAR-10 with random labels to zero training error, and then of course predicted at chance; on the true labels the same networks generalize well. So the answer is not in the class. It is in which interpolating solution the algorithm picks.

Past the threshold there are more unknowns than equations. Draw the smallest case: one example, two parameters. Every point on this line fits the example exactly; in general the solutions form a flat of dimension p minus n. Our experiment picks the one of smallest length. Grow a circle from the origin until it touches the line. It touches where the radius is perpendicular to the line, that is, along the example itself. In general the minimum-norm solution is a combination of the rows of X. Substitute that into the equations and solve: X transpose, times the inverse of X X transpose, times y. This is the pseudo-inverse, and the one in our experiment.

Nobody trains a network by calling the pseudo-inverse. But they do run gradient descent. On the squared error, each step subtracts X transpose times the residual: a combination of the rows. Start at zero, and you never leave the row space. Watch: the yellow path runs straight along the example's direction and stops on the line at the smallest solution. Started elsewhere, it lands somewhere else on the line. So from zero, the limit fits the data and lies in the row space, and only one solution does both. The algorithm chose the smallest norm by itself: an implicit bias. For the logistic loss on separable data, gradient descent heads for the maximum margin, chapter three's margins again.

Why does the error explode at the threshold, and fall after it? The fitted parameters miss the true ones by a bias and by the pseudo-inverse applied to the noise, where the noise includes the features the model cannot see. With fewer parameters than examples, the noise term's average is the noise variance times p over n minus p minus one: the mean of an inverse Wishart matrix. With more, the same argument transposed gives n over p minus n minus one. Both blow up as p approaches n, where X is square and its smallest singular value is near zero: Part 52's ill-conditioning. The formula's curves, drawn for a target of norm one, follow our measurements on both sides of the peak. Past it, the spare directions share the noise, and the smallest solution damps it.

9Learning is compressionResearch4 min

William of Ockham said not to multiply entities beyond necessity. Learning theory makes it a theorem. Describe each hypothesis in a prefix-free code, like the leaves of this tree. Kraft's inequality says two to the minus the lengths add up to at most one. So share out the failure probability delta in those proportions: a short hypothesis gets a large share. By chapter one's argument, a hypothesis with error above epsilon survives m examples with probability e to the minus epsilon m; set that equal to its share. Solve: its error is at most its length in bits, times log two, plus log of one over delta, all over m. The union bound spends at most delta. Anselm Blumer, Andrzej Ehrenfeucht, David Haussler and Manfred Warmuth called this Occam's razor, in 1987. Short descriptions generalize, not because nature is simple, but because there are few of them.

Nick Littlestone and Manfred Warmuth turned this around in 1986. Two hundred points, labelled by a hidden rectangle. Keep only four: the extreme positive points. From them alone, rebuild the tightest box, and it labels all two hundred correctly. That is a compression scheme of size four. Why does it generalize? Fix which four positions are kept. The box depends only on those, so the other hundred and ninety-six are fresh examples it happened to fit. Take the union bound over at most m to the k choices, and solve: k log m plus log one over delta, over m minus k. Here that is point one two three. The box's true error is point zero one seven; the bound is safe, and of the same order as chapter one's.

Compression explains chapter three's puzzle too. Keep only the examples the perceptron got wrong, in the order it met them. Run it on those alone: it makes the same mistakes in the same order and finishes with the same weights, which fit everything. So the perceptron is a compression scheme whose size is its number of mistakes, at most one over the margin squared, a hundred here, whatever the dimension. On two thousand points the VC dimension climbs to a thousand, while the scheme never needs more than thirty-eight. The compression bound stays under about a seventh, even in a thousand dimensions, where no VC bound says anything. Margins, not dimensions, decide, because a large margin means a short description.

There is a third way to say the same thing, as a message. The receiver has the two hundred points and needs their labels. Sent one by one, that is two hundred bits. Coded by their frequency, forty-one positives in two hundred, about a hundred and forty-six. But send the four indices of the box's points, about thirty-one bits, and the receiver rebuilds the box and every label follows. Feed those thirty-one bits to Occam's bound and it says point one two one: the compression bound's answer, seen as a message. Jorma Rissanen's minimum description length principle, from 1978, chooses the hypothesis that minimizes the bits to describe it plus the bits to describe its exceptions. It is the bargain of Part 21's compressors: every regularity claimed must pay for itself in bits.

Put the bounds side by side. The finite class of chapter one, the bits of Occam's razor, the kept points of a compression scheme, and the VC dimension of chapter two. Each says the same thing: error falls like the complexity, times a logarithm, over the number of examples. Compression implies learning. Does learning imply compression, with a scheme as small as the VC dimension? Littlestone and Warmuth asked in 1986, and it is still open. That is the frontier. Each measure, in the end, counts what the learner must remember.

10Frontier: compression schemes and in-context learningResearch2 min

Is learning exactly compression? A learner that generalizes must, in some sense, have compressed its data. Here are 200 points labelled by a hidden rectangle. Keep just four of them: the leftmost, rightmost, lowest and highest positive points. The tightest box through those four labels every one of the 200 points correctly. Nick Littlestone and Manfred Warmuth called this a sample compression scheme, and showed in 1986 that a scheme of size k gives a learning bound much like VC dimension k. Warmuth conjectured that every class of VC dimension d has a scheme of size proportional to d. In 2016 Shay Moran and Amir Yehudayoff proved that a scheme of size exponential in d always exists. Whether linear size is always possible is still open.

The newest puzzle comes from language models. Shown a few input-output examples in its prompt, a trained model can predict the answer for a new input, without any change to its weights. In 2022 Shivam Garg and colleagues trained transformers on prompts of linear regression problems and found they matched least squares, and constructions show that attention can carry out steps of gradient descent. What theory still lacks is a bound that says when this works and how many examples a prompt needs. Double descent's second dip, benign overfitting, is now well understood for linear models like ours; for deep networks, only partly.

Open problems. A bound on the generalization of deep networks that is not vacuous at the sizes people actually use. A theory of what prompts can teach. Whether parity can be learned efficiently when some labels are flipped, which much of modern cryptography assumes is impossible. And matching upper and lower bounds for bandits with structure. This part's research problem is Warmuth's: does every class of VC dimension d have a compression scheme of size proportional to d?

Recap, problems, and where this comes backAll tracks2 min

What we built in this part. PAC learning, where a finite class needs examples in proportion to the logarithm of its size. The VC dimension, the Sauer–Shelah lemma, and the fundamental theorem: a class is learnable exactly when its VC dimension is finite. Margins, which bound the perceptron's mistakes and explain boosting, whatever the dimension. Online learning against an adversary, where regret grows like a square root, and bandits that balance exploring against exploiting. Problems such as sparse parity that no statistical learner can find quickly. And double descent and compression. One idea runs through it: learning is possible exactly when the hypotheses are simple enough to be pinned down by the data.

Where this comes back. Part 58 asks what programs mean, and how to prove two of them the same. Part 59 studies what many machines can compute together. Part 60 builds the hardware that trains and runs learned models. And Part 61 asks how to measure a result honestly, and returns to the bridge between this series and AI, Built.

In practice. Hold out data the model never sees, and never tune on the test set. When the model is already flexible, more data usually beats a cleverer model. Control capacity with margins, weight decay and early stopping. Use bandits for online choices; Thompson sampling is a strong default. And when a result looks too good, look for leakage first.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: implement two bandit algorithms and compare their regret with the Lai–Robbins rate. The last, marked with a star, is a research problem: whether every class of VC dimension d can be compressed to a number of points proportional to d.

Next time, Part 58: semantics. What does a program mean? Three answers: the steps a machine takes, the mathematical object a program denotes, and the laws it obeys, with a theorem that writes code's properties for free.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 58 asks what programs mean and how to prove two of them the same, Part 59 what many machines can compute together, and Part 60 builds the hardware that trains and runs learned models. Part 61 asks how to measure a result honestly and returns to the bridge between this series and AI, Built.

Key results

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

Finite class, realizable\(\displaystyle m\ \ge\ \frac{\ln|H|+\ln(1/\delta)}{\varepsilon}\ \Longrightarrow\ P\bigl(L_D(h)>\varepsilon\bigr)\le\delta\)
Sauer-Shelah\(\displaystyle \Pi_H(m)\ \le\ \sum_{i=0}^{d}\binom{m}{i}\ \le\ \Bigl(\frac{em}{d}\Bigr)^{d}\quad\allowbreak (m\ge d)\)
Novikoff's bound\(\displaystyle \text{perceptron }\allowbreak \text{mistakes}\ \le\ \Bigl(\frac{R}{\gamma}\Bigr)^{2}\)
AdaBoost's training error\(\displaystyle \widehat{\operatorname{err}}(H_T)\ \le\ \exp\Bigl(-2\sum_{t=1}^{T}\gamma_t^{2}\Bigr),\qquad\allowbreak \gamma_t=\tfrac12-\epsilon_t\)
Hedge\(\displaystyle \text{regret}_T\ \le\ \frac{\ln N}{\eta}+\frac{\eta T}{8}\ =\ \sqrt{\tfrac{T\ln N}{2}}\quad\allowbreak \text{at } \eta=\sqrt{8\ln N/T}\)
Lai-Robbins\(\displaystyle \liminf_{T\to\infty}\frac{\text{regret}_T}{\ln T}\ \ge\ \sum_{i:\Delta_i>0}\frac{\Delta_i}{\operatorname{KL}(\mu_i,\mu^{*})}\)

Try it

Lab 57 · Bounds against measurements: PAC, VC, margins, regret

Learn a hidden rectangle 200 times at each sample size and compare the error with (4/m) ln(4/delta); count the labellings half-planes realize against Sauer-Shelah; count the perceptron's mistakes against (R/gamma)^2; and run Hedge and follow the leader on random losses and against an alternating adversary.

Figure produced by Lab 57: Bounds against measurements: PAC, VC, margins, regret
Produced by the lab below, seed 0, in 0.8 s.
python -m videos.cs.labs 57 needs numpy, scipy, matplotlib · download lab57.py · source on GitHub
rectangle, m =   100: error                     mean 0.0387   95th percentile 0.0699   bound (4/m) ln(4/delta) 0.1753   VC bound 0.673
rectangle, m =  2000: error                     mean 0.0020   95th percentile 0.0040   bound (4/m) ln(4/delta) 0.0088   VC bound 0.051
half-planes on 7 points: labellings             44 realized (m^2 - m + 2 = 44)   Sauer-Shelah 64   all 128
perceptron, margin 0.1: mistakes                d = 2: 4   d = 10: 23   d = 100: 38   d = 400: 42   bound (R/gamma)^2 = 100
random losses, 20 experts, 2000 rounds: regret  Hedge 30.7   follow the leader 9.0   bound sqrt(T ln N / 2) = 54.7
two alternating experts, 2000 rounds: regret    Hedge 13.4   follow the leader 1000.0   bound sqrt(T ln 2 / 2) = 26.3

Each bound holds with room to spare: the rectangle bound is about twice the measured quantile, the VC bound far looser, Novikoff's independent of the dimension. Only Hedge's guarantee survives an adversary.
The code (102 lines; it asserts its own result)
"""Lab 57: set four learning bounds against measurements: a PAC curve, a growth function, the perceptron, and regret."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import math

import numpy as np

from explainer.cs.learn import theory

TITLE = "Bounds against measurements: PAC, VC, margins, regret"
GOAL = ("Learn a hidden rectangle 200 times at each sample size and compare the error with (4/m) ln(4/delta); count "
        "the labellings half-planes realize against Sauer-Shelah; count the perceptron's mistakes against "
        "(R/gamma)^2; and run Hedge and follow the leader on random losses and against an alternating adversary.")
TASKS = [
    "Change delta from 0.05 to 0.01 in theory.rectangle_curves. How much does the bound move, how much does the measured quantile move, and why so little?",
    "In adversary() give Hedge the learning rate 10 * eta and then eta / 10. Which term of ln N / eta + eta T / 8 grows in each case, and does the measured regret follow it?",
    "Run theory.perceptron_margin with gamma = 0.05 and 0.2. Do the mistakes scale like 1/gamma^2, and does the dimension matter?",
]

T_ROUNDS, N_EXPERTS = 2000, 20


def adversary(T, eta):
    """Two experts whose losses alternate after a first half-loss: the leader is always the one about to lose."""
    L = np.zeros((T, 2))
    L[0] = (0.5, 0.0)
    L[1::2, 1] = 1.0
    L[2::2, 0] = 1.0
    w, cum, hedge, ftl, cum_h, cum_f = np.ones(2), np.zeros(2), [], [], 0.0, 0.0
    for t in range(T):
        cum_h += (w / w.sum()) @ L[t]
        cum_f += L[t, int(np.argmin(cum))]
        cum += L[t]
        w *= np.exp(-eta * L[t])
        hedge.append(cum_h - cum.min())
        ftl.append(cum_f - cum.min())
    return np.array(hedge), np.array(ftl)


def run(seed=0):
    lab = labs.Lab()

    # 1. PAC: the tightest box around the positives, against the rectangle bound
    ms = (20, 50, 100, 200, 500, 1000, 2000)
    rect = theory.rectangle_curves(ms=ms, trials=200, seed=seed)["rows"]
    for r in rect:
        assert r["p95"] <= r["rect_bound"], "with probability 95% the error is under (4/m) ln(4/delta)"
        if r["m"] >= 100:
            assert 2.5 < r["mean"] * r["m"] < 4.5 and r["rect_bound"] < r["vc_bound"], "the error falls like 4/m"
    for r in (rect[2], rect[-1]):
        lab.row(f"rectangle, m = {r['m']:>5}: error", f"mean {r['mean']:.4f}   95th percentile {r['p95']:.4f}   "
                f"bound (4/m) ln(4/delta) {r['rect_bound']:.4f}   VC bound {r['vc_bound']:.3f}")

    # 2. VC: half-planes on m random points, every labelling tried by a linear program
    growth = theory.growth(ms=range(1, 8), trials=1, seed=seed)
    for g in growth:
        assert g["realized"] == g["exact_general"] <= g["sauer"] <= g["all"]
    assert growth[2]["realized"] == 8 and growth[3]["realized"] < 16, "three points are shattered, four are not"
    g = growth[-1]
    lab.row(f"half-planes on {g['m']} points: labellings", f"{g['realized']} realized (m^2 - m + 2 = {g['exact_general']})"
            f"   Sauer-Shelah {g['sauer']}   all {g['all']}")

    # 3. margins: the perceptron's mistakes do not grow with the dimension
    perc = theory.perceptron_margin(dims=(2, 10, 100, 400), seed=seed)
    assert all(0 < p["mistakes"] <= p["bound"] + 1e-9 for p in perc), "Novikoff: at most (R/gamma)^2 mistakes"
    lab.row("perceptron, margin 0.1: mistakes", "   ".join(f"d = {p['d']}: {p['mistakes']}" for p in perc)
            + f"   bound (R/gamma)^2 = {perc[0]['bound']:.0f}")

    # 4. regret: Hedge under its bound on random losses and against an adversary; follow the leader is not
    h = theory.hedge(T=T_ROUNDS, N=N_EXPERTS, seed=seed)
    bound_random = math.sqrt(T_ROUNDS * math.log(N_EXPERTS) / 2)
    assert max(h["regret"]) <= bound_random
    eta = math.sqrt(8 * math.log(2) / T_ROUNDS)
    adv_hedge, adv_ftl = adversary(T_ROUNDS, eta)
    bound_adv = math.sqrt(T_ROUNDS * math.log(2) / 2)
    assert np.all(adv_hedge <= math.log(2) / eta + eta * np.arange(1, T_ROUNDS + 1) / 8) and adv_hedge.max() <= bound_adv
    assert adv_ftl[-1] > 0.45 * T_ROUNDS > 10 * bound_adv
    lab.row(f"random losses, {N_EXPERTS} experts, {T_ROUNDS} rounds: regret", f"Hedge {h['regret'][-1]:.1f}   follow the leader "
            f"{h['follow_the_leader'][-1]:.1f}   bound sqrt(T ln N / 2) = {bound_random:.1f}")
    lab.row(f"two alternating experts, {T_ROUNDS} rounds: regret", f"Hedge {adv_hedge[-1]:.1f}   follow the leader "
            f"{adv_ftl[-1]:.1f}   bound sqrt(T ln 2 / 2) = {bound_adv:.1f}")
    lab.note = ("Each bound holds with room to spare: the rectangle bound is about twice the measured quantile, the VC "
                "bound far looser, Novikoff's independent of the dimension. Only Hedge's guarantee survives an adversary.")

    fig, ax = labs.figure(2, size=(11, 4.3))
    m = np.array([r["m"] for r in rect])
    ax[0].loglog(m, [r["vc_bound"] for r in rect], color=labs.PURPLE, label="VC bound, d = 4")
    ax[0].loglog(m, [r["rect_bound"] for r in rect], color=labs.RED, label="(4/m) ln(4/delta)")
    ax[0].loglog(m, [r["p95"] for r in rect], "o-", color=labs.GOLD, ms=4, label="measured, 95th percentile")
    ax[0].loglog(m, [r["mean"] for r in rect], "o-", color=labs.BLUE, ms=4, label="measured, mean")
    ax[0].set(title="Learning a rectangle: error against sample size", xlabel="examples m", ylabel="error")
    ax[0].legend(loc="lower left")
    t = np.arange(1, T_ROUNDS + 1)
    ax[1].plot(t, math.log(2) / eta + eta * t / 8, color=labs.RED, label="Hedge's guarantee: ln 2 / eta + eta t / 8")
    ax[1].plot(t, adv_hedge, color=labs.GREEN, label="Hedge")
    ax[1].plot(t, adv_ftl, color=labs.GOLD, label="follow the leader")
    ax[1].set(title="Regret against two alternating experts", xlabel="round t", ylabel="regret", yscale="log",
              ylim=(0.3, 2000))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Change delta from 0.05 to 0.01 in theory.rectangle_curves. How much does the bound move, how much does the measured quantile move, and why so little?
  2. In adversary() give Hedge the learning rate 10 * eta and then eta / 10. Which term of ln N / eta + eta T / 8 grows in each case, and does the measured regret follow it?
  3. Run theory.perceptron_margin with gamma = 0.05 and 0.2. Do the mistakes scale like 1/gamma^2, and does the dimension matter?

Problems, with solutions

Try each problem before opening its solution.

  1. VC dimension. Show that half-planes in the plane have VC dimension 3, and axis-aligned rectangles have VC dimension 4.

    Solution

    A lower bound needs one shattered set; an upper bound must defeat every set. Half-planes, at least 3: take three points not on a line. If all three get one label, a line missing their triangle does it; otherwise one point is the odd one out, it is a vertex of the triangle, and a line crossing the two edges at that vertex cuts it off. All 8 labellings are realized (our instrument checks each by a linear program on (0, 0), (2, 0.3), (0.8, 1.8)). At most 3: by Radon's theorem any four points in the plane split into two groups whose convex hulls meet: either one point lies in the triangle of the other three, or the four are in convex position and the two diagonals cross (three collinear points are a degenerate case of the first, the middle point lying in the segment of the other two). Label one group +1 and the other −1. A half-plane and its complement are convex, so one would contain the hull of the +1 group and the other the hull of the −1 group, which meet: impossible. On the square's corners 14 of the 16 labellings are separable, and the two failures colour opposite corners alike. Rectangles, at least 4: take the diamond (1, 0), (0, 1), (−1, 0), (0, −1). For any subset, the bounding box of the subset (or an empty box away from the points) contains none of the others, since each point is the unique extreme one in its own direction. At most 4: among five points pick a leftmost, a rightmost, a lowest and a highest one; that is at most four points, so some fifth point remains, and its coordinates lie between the extremes. Label the chosen points +1 and the fifth −1: any rectangle containing the chosen points contains their bounding box, hence the fifth point.

  2. Sauer–Shelah. Prove the Sauer–Shelah lemma by induction on m + d.

    Solution

    Write Φ_d(m) = Σ_{i=0}^{d} C(m, i); the claim is that a class of VC dimension at most d realizes at most Φ_d(m) labellings on any m points. Base cases: if d = 0, two different labellings of S differ at some point x and the class would shatter {x}, so at most 1 = Φ_0(m); if m = 0, there is one (empty) labelling and Φ_d(0) = 1. Step: let S = {x_1, …, x_m}, S′ = S \ {x_m}, and H_S the labellings of S. Let H₁ be the labellings of S′ that extend to some labelling in H_S, and H₂ those that extend in both ways. Each labelling in H_S is a row of H₁ with one label for x_m, and the rows in H₂ appear twice, so |H_S| = |H₁| + |H₂|. H₁ is a class on m − 1 points with VC dimension at most d. H₂ has VC dimension at most d − 1: if it shattered T ⊆ S′, every labelling of T would come with both labels of x_m, and H_S would shatter T ∪ {x_m}, of size |T| + 1 ≤ d. Both cases have smaller m + d, so |H_S| ≤ Φ_d(m − 1) + Φ_{d−1}(m − 1) = Σ_{i≤d} [C(m − 1, i) + C(m − 1, i − 1)] = Σ_{i≤d} C(m, i) by Pascal's rule. On the square's corners: H₁ has 8 rows (at most Φ_3(3) = 8), H₂ has 6 (at most Φ_2(3) = 7), and 14 ≤ 15 = Φ_3(4). For m ≥ d, (d/m)^d Φ_d(m) ≤ Σ_{i≤d} C(m, i)(d/m)^i ≤ (1 + d/m)^m ≤ e^d, so Φ_d(m) ≤ (em/d)^d: for half-planes on ten points, 92 ≤ 176 ≤ 744, against 2^10 = 1,024.

  3. Novikoff's bound. Prove that the perceptron makes at most (R/γ)² mistakes on separable data.

    Solution

    Assume ‖x_i‖ ≤ R for all i and a unit vector w* with y_i w* · x_i ≥ γ > 0 (a bias is absorbed by an extra constant coordinate, at the cost of a larger R). Start from w_0 = 0 and let w_k be the weights after the k-th mistake, whatever the order of the examples and however many passes. Progress: a mistake on (x, y) sets w_{k+1} = w_k + yx, so w_{k+1} · w* = w_k · w* + y x · w* ≥ w_k · w* + γ, and by induction w_k · w* ≥ kγ. Length: ‖w_{k+1}‖² = ‖w_k‖² + 2y w_k · x + ‖x‖² ≤ ‖w_k‖² + R², because on a mistake y w_k · x ≤ 0; so ‖w_k‖² ≤ kR². By Cauchy–Schwarz with ‖w*‖ = 1, kγ ≤ w_k · w* ≤ ‖w_k‖ ≤ √k R, hence √k ≤ R/γ and k ≤ (R/γ)². The bound contains no dimension and no number of examples. With R = 1 and γ = 0.1 it is 100; our instrument's runs on 2,000 points made 4, 23, 38 and 34 mistakes in 2, 10, 100 and 1,000 dimensions.

  4. Hedge. Show that Hedge with the right learning rate has regret at most √((T/2) ln N).

    Solution

    Hedge keeps weights w_1(i) = 1, plays p_t(i) = w_t(i)/W_t and updates w_{t+1}(i) = w_t(i) e^{−η ℓ_t(i)} with losses ℓ_t(i) ∈ [0, 1]; the regret is Σ_t p_t · ℓ_t − min_i L_i, with L_i = Σ_t ℓ_t(i). From below: for every i, W_{T+1} ≥ w_{T+1}(i) = e^{−η L_i} and W_1 = N, so ln(W_{T+1}/W_1) ≥ −η L_i − ln N. From above: W_{t+1}/W_t = Σ_i p_t(i) e^{−η ℓ_t(i)} = E[e^{−ηX}] for X = ℓ_t(I), I ~ p_t, a variable in [0, 1]; Hoeffding's lemma gives ln E[e^{−ηX}] ≤ −η E[X] + η²/8 = −η p_t · ℓ_t + η²/8. The logarithms telescope over the T rounds: ln(W_{T+1}/W_1) ≤ −η Σ_t p_t · ℓ_t + η²T/8. Combining, Σ_t p_t · ℓ_t − L_i ≤ ln N/η + ηT/8 for every i. The right side is smallest at η = √(8 ln N/T), where both terms equal √(T ln N/8) and the sum is √(T ln N/2). The argument never assumed the losses were random, so it holds against any sequence chosen before each round's play is revealed. For N = 20 and T = 2,000: η = 0.109, ln N/η = ηT/8 = 27.4, and the guarantee is 54.7; our run's regret was 30.7. If T is not known in advance, the doubling trick restarts with T = 1, 2, 4, … at the cost of a constant factor.

  5. Build. Implement UCB1 and Thompson sampling for Bernoulli arms, and compare their regret with the Lai–Robbins rate.

    Solution

    Solution notes. Keep, per arm, the pull count n_i and the reward sum s_i. UCB1 pulls each arm once, then the arm maximizing s_i/n_i + √(2 ln t / n_i); Thompson sampling draws θ_i ~ Beta(s_i + 1, n_i − s_i + 1) for every arm and pulls the largest. Record the pseudo-regret Σ_t (μ* − μ_{a_t}), which has far less variance than realized rewards, and average over runs; drawing one T × K table of rewards per run and giving it to every algorithm (common random numbers, as bandits in explainer/cs/learn/theory.py does) makes the comparison sharper. The Lai–Robbins constant is Σ_i Δ_i / KL(μ_i, μ*) with KL(p, q) = p ln(p/q) + (1 − p) ln((1 − p)/(1 − q)). For our arms (0.5, 0.45, 0.4, 0.3) the three terms are 9.98, 4.97 and 2.43, so 17.38 ln T, 148.0 at T = 5,000; by Pinsker, KL ≥ 2Δ², so the constant is at most Σ 1/(2Δ_i) = 17.5, nearly tight for coins near a half. Over 100 runs of 5,000 rounds our instrument measures UCB1 158.8, Thompson 49.7 and ε-greedy (ε = 0.05) 75.1. Plot regret against ln t: the theorem is about slopes. A bad arm stops being pulled once √(2 ln t / n_i) < Δ_i, that is after about 2 ln t/Δ_i² pulls, so UCB1's slope should approach Σ 2/Δ_i = 70, four times the optimum; a fit to the cached curve over t ≥ 1,000 gives 68.2. Thompson's fitted slope is 13.3, still below 17.4 at this horizon, which the asymptotic theorem allows; ε-greedy's regret is linear. Check against UCB1's finite-time bound (2,386 here), test that the best arm gets most pulls, and as an extension add KL-UCB, whose index uses the KL divergence itself and meets the Lai–Robbins constant (Garivier and Cappé 2011).

  6. ★ Research. The sample compression conjecture: does every concept class of VC dimension d have a compression scheme of size O(d)?

    Discussion. Open. Littlestone and Warmuth (1986) showed that a scheme of size k gives a PAC bound like VC dimension k (chapter 9's (k ln m + ln 1/δ)/(m − k)), and asked for the converse; Floyd and Warmuth (1995) built schemes of size d for maximum classes, and Warmuth posed the general question as an open problem in 2003. The difficulty is that a scheme is a single global object: one reconstruction function must work for every sample of every size, while VC theory only counts behaviours. Moran and Yehudayoff (2016) proved that a scheme of size exponential in d always exists, by compressing to a few small subsamples on which a boosted vote of ERM hypotheses is consistent (the minimax argument of chapter 4); the exponential enters through the dual VC dimension, which can be about 2^d. Rectangles (size 4 = d) and half-spaces (the at most n + 1 support vectors of the maximum-margin separator, d = n + 1) show the conjecture's bound is natural. A good partial answer would reduce 2^{O(d)} to a polynomial in d, prove size O(d) for a broad family (classes of small VC dimension, or geometric classes), or exhibit classes forcing size above d, with an exact search for schemes on small finite classes (a SAT encoding solved by Part 26's CDCL solver) to test conjectured constants.

Notes and sources

Glossary

  • PAC learning, realizable and agnostic, empirical risk minimization (ERM), sample complexity — error at most ε with probability 1 − δ; a perfect hypothesis exists or not; returning the hypothesis best on the sample; how many examples a guarantee needs.
  • union bound, Hoeffding's inequality and lemma — the tools behind every finite-class bound and the Hedge proof.
  • shattering, VC dimension, growth function, Sauer–Shelah lemma, ghost sample — realizing every labelling; the largest set shattered; the most labellings on m points; its polynomial bound; the symmetrization behind the VC bound.
  • Radon's theorem — any d + 2 points in ℝ^d split into two groups whose convex hulls meet.
  • fundamental theorem of PAC learning, no free lunch — finite VC dimension if and only if learnable; a shattered set the learner has half seen forces error.
  • margin, perceptron, Novikoff's bound — the distance of the data from a separator; the mistake-driven linear learner; at most (R/γ)² mistakes.
  • Rademacher complexity, Massart's lemma, margin bound — a class's fit to random signs; its bound by the growth function; generalization in terms of R/ρ rather than dimension.
  • weak and strong learning, boosting, AdaBoost, decision stump, edge — error just below a half on every distribution; combining weak rules into a strong one; one threshold on one coordinate; how far below a half.
  • minimax theorem, multiplicative weights — the game behind boosting; the update shared by AdaBoost and Hedge.
  • mistake bound, halving algorithm, Littlestone dimension, weighted majority — online learning counted in mistakes.
  • experts problem, Hedge, regret, follow the leader — choosing among N advisers against an adversary; the loss above the best adviser in hindsight.
  • online gradient descent, online-to-batch conversion — regret D G √T for convex losses; averaging the iterates turns a regret bound into a risk bound.
  • multi-armed bandit, explore and exploit, UCB1, Thompson sampling, Lai–Robbins lower bound — learning while earning; optimism; probability matching; the ln T / KL rate no consistent policy beats.
  • representation-dependent and cryptographic hardness of learning — hardness from the hypothesis we must output; hardness whatever is output, from a cryptosystem.
  • statistical query (SQ), SQ dimension, sparse parity, learning parity with noise (LPN) — learners that see only averages; the number of nearly orthogonal functions in a class; the classic hard case.
  • interpolation threshold, double descent, minimum-norm interpolant, pseudo-inverse, implicit bias, benign overfitting — p = n; the second fall of test error; the smallest exact fit and what gradient descent from zero finds; fitting noise without paying for it.
  • Occam's razor bound, Kraft's inequality, sample compression scheme, minimum description length (MDL) — short descriptions generalize; a sample reduced to k points from which a consistent hypothesis is rebuilt; model bits plus exception bits.
  • in-context learning, sample compression conjecture — learning inside a forward pass; schemes of size O(d)?

Sources

  • S. Shalev-Shwartz and S. Ben-David, Understanding Machine Learning: From Theory to Algorithms (2014); M. Mohri, A. Rostamizadeh and A. Talwalkar, Foundations of Machine Learning (2nd ed., 2018); M. Kearns and U. Vazirani, An Introduction to Computational Learning Theory (1994).
  • N. Cesa-Bianchi and G. Lugosi, Prediction, Learning, and Games (2006); T. Lattimore and C. Szepesvári, Bandit Algorithms (2020).
  • L. Valiant, "A theory of the learnable", Commun. ACM 1984; V. Vapnik and A. Chervonenkis, "On the uniform convergence of relative frequencies of events to their probabilities", Theory Probab. Appl. 1971; N. Sauer, "On the density of families of sets", J. Combin. Theory A 1972; S. Shelah, "A combinatorial problem; stability and order for models and theories in infinitary languages", Pacific J. Math. 1972.
  • A. Blumer, A. Ehrenfeucht, D. Haussler and M. Warmuth, "Occam's razor", Inf. Process. Lett. 1987, and "Learnability and the Vapnik–Chervonenkis dimension", J. ACM 1989.
  • F. Rosenblatt, "The perceptron: a probabilistic model for information storage and organization in the brain", Psychological Review 1958; A. Novikoff, "On convergence proofs on perceptrons", Symposium on the Mathematical Theory of Automata 1962; C. Cortes and V. Vapnik, "Support-vector networks", Machine Learning 1995.
  • P. Bartlett and S. Mendelson, "Rademacher and Gaussian complexities: risk bounds and structural results", JMLR 2002; V. Koltchinskii and D. Panchenko, "Empirical margin distributions and bounding the generalization error of combined classifiers", Ann. Statist. 2002.
  • R. Schapire, "The strength of weak learnability", Machine Learning 1990; Y. Freund and R. Schapire, "A decision-theoretic generalization of on-line learning and an application to boosting", J. Comput. Syst. Sci. 1997; R. Schapire, Y. Freund, P. Bartlett and W. S. Lee, "Boosting the margin: a new explanation for the effectiveness of voting methods", Ann. Statist. 1998; J. Friedman, "Greedy function approximation: a gradient boosting machine", Ann. Statist. 2001.
  • N. Littlestone, "Learning quickly when irrelevant attributes abound: a new linear-threshold algorithm", Machine Learning 1988; N. Littlestone and M. Warmuth, "The weighted majority algorithm", Inf. Comput. 1994; N. Cesa-Bianchi, Y. Freund, D. Haussler, D. Helmbold, R. Schapire and M. Warmuth, "How to use expert advice", J. ACM 1997; M. Zinkevich, "Online convex programming and generalized infinitesimal gradient ascent", ICML 2003.
  • W. Thompson, "On the likelihood that one unknown probability exceeds another in view of the evidence of two samples", Biometrika 1933; H. Robbins, "Some aspects of the sequential design of experiments", Bull. AMS 1952; T. L. Lai and H. Robbins, "Asymptotically efficient adaptive allocation rules", Adv. Appl. Math. 1985; P. Auer, N. Cesa-Bianchi and P. Fischer, "Finite-time analysis of the multiarmed bandit problem", Machine Learning 2002; P. Auer, N. Cesa-Bianchi, Y. Freund and R. Schapire, "The nonstochastic multiarmed bandit problem", SIAM J. Comput. 2002; E. Kaufmann, N. Korda and R. Munos, "Thompson sampling: an asymptotically optimal finite-time analysis", ALT 2012; A. Garivier and O. Cappé, "The KL-UCB algorithm for bounded stochastic bandits and beyond", COLT 2011.
  • L. Pitt and L. Valiant, "Computational limitations on learning from examples", J. ACM 1988; M. Kearns and L. Valiant, "Cryptographic limitations on learning Boolean formulae and finite automata", J. ACM 1994; O. Goldreich, S. Goldwasser and S. Micali, "How to construct random functions", J. ACM 1986; M. Kearns, "Efficient noise-tolerant learning from statistical queries", J. ACM 1998; A. Blum, M. Furst, J. Jackson, M. Kearns, Y. Mansour and S. Rudich, "Weakly learning DNF and characterizing statistical query learning using Fourier analysis", STOC 1994; A. Blum, A. Kalai and H. Wasserman, "Noise-tolerant learning, the parity problem, and the statistical query model", J. ACM 2003.
  • C. Zhang, S. Bengio, M. Hardt, B. Recht and O. Vinyals, "Understanding deep learning requires rethinking generalization", ICLR 2017; M. Belkin, D. Hsu, S. Ma and S. Mandal, "Reconciling modern machine-learning practice and the classical bias–variance trade-off", PNAS 2019; T. Hastie, A. Montanari, S. Rosset and R. Tibshirani, "Surprises in high-dimensional ridgeless least squares interpolation", Ann. Statist. 2022 (arXiv 2019); D. Soudry, E. Hoffer, M. S. Nacson, S. Gunasekar and N. Srebro, "The implicit bias of gradient descent on separable data", JMLR 2018; P. Bartlett, P. Long, G. Lugosi and A. Tsigler, "Benign overfitting in linear regression", PNAS 2020.
  • N. Littlestone and M. Warmuth, "Relating data compression and learnability", technical report 1986; S. Floyd and M. Warmuth, "Sample compression, learnability, and the Vapnik–Chervonenkis dimension", Machine Learning 1995; M. Warmuth, "Compressing to VC dimension many points", COLT 2003 (open problem); S. Moran and A. Yehudayoff, "Sample compression schemes for VC classes", J. ACM 2016; J. Rissanen, "Modeling by shortest data description", Automatica 1978.
  • S. Garg, D. Tsipras, P. Liang and G. Valiant, "What can transformers learn in-context? A case study of simple function classes", NeurIPS 2022.
About this partfrom its README

Part 57 of a sixty-one-part course in computer science (see the series plan and the syllabus), the second part of Act XI, The Research Frontier. AI, Built showed machines that learn; this part asks what can be proved about them. How many examples a learner needs is decided by one number, the VC dimension; margins, not dimensions, govern the perceptron and boosting; against an adversary the measure is regret, which grows like a square root; and some classes, parity among them, need little data but cannot be learned efficiently by statistics. Every bound is set against a measurement, down to a linear model that fits its noise exactly and still predicts well.

The instruments are in explainer/cs/learn/ (tested in tests/test_cs57_learning.py):

  • theory.py: shattering by half-planes, every labelling checked by a feasibility linear program (SciPy's HiGHS); the growth function of half-planes on random points (counted labelling by labelling up to m = 10, the general-position count m² − m + 2 beyond) against 2^m and the Sauer–Shelah sum; PAC learning curves for an axis-aligned rectangle learned by the tightest box (200 trials at each of eight sample sizes) against (4/m) ln(4/δ) and the VC bound with d = 4; the finite-class sample bound; the perceptron on separable data with margin 0.1 on the unit sphere in 2 to 1,000 dimensions; AdaBoost with decision stumps on a ring, without and with 5% label noise (training and test error per round, margins, example weights); Hedge and follow the leader against twenty experts; the halving algorithm over 1,024 thresholds; ε-greedy, UCB1 and Thompson sampling on four Bernoulli arms against the Lai–Robbins rate; sparse parity, subset search against Gaussian elimination over GF(2); double descent of ridgeless least squares on Gaussian features; and a size-4 sample compression scheme for rectangles. (The scenes' illustrative pictures, such as the sixteen hypotheses of the agnostic bound, thresholds fitting random signs, the boosting game, weighted majority, follow the leader against an adversary, the random walks of the lower bound, online gradient descent, the UCB run, the Thompson posteriors, the statistical-query grid and the two-parameter plane of the minimum-norm interpolator, are computed inline with NumPy.)
Chapter notes
  • Hook. Double descent: fifty noisy examples, a linear model on the first p of 200 Gaussian features (minimum-norm least squares, median of 50 trials). Test error is 1.03 at p = 5, explodes to 52.1 at p = n = 50, where the model can fit anything, noise included, and falls to 0.78 at p = 200, lower than any model with fewer parameters than examples. Three questions and three kinds of answer: PAC learning and the VC dimension (Valiant 1984); regret and the bandits of Part 44 when an adversary picks the examples; cryptography and statistical queries for what cannot be learned efficiently. The plan.
  • 1. Probably approximately correct. The learning game on twelve points and a hidden rectangle [0.2, 0.7] × [0.3, 0.75]: an unknown distribution D, a target c, the error L_D(h), and Valiant's ε–δ definition. The finite class by the union bound (Part 2): m ≥ (ln|H| + ln 1/δ)/ε, 199 examples for |H| = 1,000 and ε = δ = 0.05. The agnostic case by Hoeffding (Part 20) and a union bound: ln(2|H|/δ)/(2ε²) = 2,120 examples for the same class, the best on the sample within 2ε of the best in the class (sixteen illustrative hypotheses at m = 40 and 800). Rectangles by four strips of probability ε/4 (Kearns and Vazirani's opening argument): m ≥ (4/ε) ln(4/δ), with no class size. Measured over 200 trials at eight sample sizes from 10 to 2,000: the mean error falls like 1/m, and from m = 100 on the bound is 2.2 to 2.6 times the 95th percentile. What replaces ln|H|: ten points have 1,024 labellings, half-planes realize 92 of them.
  • 2. VC dimension. Shattering: three points, all 8 labellings separable, each checked by a linear program. No four points: at the corners of a square 14 of 16 labellings are separable, and with one point inside a triangle also 14 of 16; Radon's theorem (1921) covers every case, so half-planes have VC dimension 3, half-spaces in ℝ^d d + 1, axis-aligned rectangles 4. The growth function up to m = 10: 2^m reaches 1,024, half-planes give 92 = m² − m + 2, the Sauer–Shelah sum Σ_{i≤3} C(m, i) gives 176. Sauer–Shelah proved by induction on the square's fourteen labellings, 14 = 8 + 6, with (em/d)^d for m ≥ d. The ghost-sample bound ε ≤ (2/m)(d log₂(2em/d) + log₂(2/δ)): for rectangles at m = 2,000 it gives 0.051 against a measured 0.0040, 13× loose, knowing only d. The fundamental theorem of PAC learning (four equivalent conditions; sample sizes of order d/ε realizable and d/ε² agnostic, Shalev-Shwartz and Ben-David's Theorem 6.8; Blumer et al. 1989) and the no free lunch converse: error at least 1/8 with probability at least 1/7.
  • 3. Margins and Rademacher complexity. Rosenblatt's perceptron on illustrative separable points; Novikoff's proof by two inequalities, kγ ≤ w_k · w* ≤ ‖w_k‖ ≤ √k R, so at most (R/γ)² mistakes: 100 for R = 1, γ = 0.1. Measured on 2,000 points with margin 0.1 in 2, 10, 100 and 1,000 dimensions: 4, 23, 38 and 34 mistakes, flat from a hundred dimensions to a thousand, while the VC dimension grows with d; Part 7's perceptron branch predictor runs the same update, but branch histories are rarely separable. Rademacher complexity as the fit to random signs (thresholds on ten points, illustrative); the bound of Bartlett and Mendelson (2002) and Massart's lemma back to VC bounds. For linear classes with ‖w‖ ≤ Λ, five lines give ΛR/√m with no dimension; the margin bound of Koltchinskii and Panchenko (2002), where (R/ρ)² plays the part of a dimension; support vector machines.
  • 4. Boosting. 400 points, green inside radius 0.6; decision stumps. With equal weights the best stump says "outside" everywhere (error 0.285, the share of green points); re-weighted, the next cuts at x₁ = 0.60 with weighted error 0.33, an edge of about 0.17; weak learning implies strong (Schapire 1990). AdaBoost's weights after 1, 2, 5 and 20 rounds pile up on the circle, the heaviest point at about 4.5 times its first share. The training error is at most exp(−2Σγ_t²): first zero at round 57, zero for good from round 108. Boosting as a zero-sum game (an illustrative 8 × 8 matrix), von Neumann's minimax theorem and Part 23's multiplicative weights. After zero training error the test error does not rise: 0.030 at round 108, 0.028 at round 125, 0.032 at round 300, while the smallest training margin climbs from −0.572 (round 5) and −0.088 (round 20) to +0.012 (round 100) and +0.023 (round 300); the margin theorem of Schapire, Freund, Bartlett and Lee (1998). With 5% of labels flipped, the 23 flipped points (5.8% of the data) hold 18% of the weight by round 20, and test error is lowest, 0.107, at round 27 and 0.130 by round 300: stop early, shrink the votes, or use gradient boosting (Friedman 2001).
  • 5. Learning online. The halving algorithm: at most log₂ 1,024 = 10 mistakes; on random examples it made 2 in 200 rounds with 9 thresholds still alive, and an adversary asking about the middle forces all 10; the Littlestone dimension (infinite for thresholds on the line, whose VC dimension is 1). Weighted majority (Littlestone and Warmuth 1994): M ≤ 2.41(m + log₂ N) (eight illustrative experts). Hedge proved, from below and from above with Hoeffding's lemma, regret at most √(T ln N / 2). Measured against 20 experts over 2,000 rounds (η = 0.109): the guarantee reaches 54.7, Hedge's regret flattens at 30.7, and follow the leader does better on these random losses (9.0) but loses almost every round to two alternating experts (after six rounds A 2.5, B 3, the leader 5.5). The lower bound: two experts and a fair coin give regret about √(T/2π) ≈ 0.4√T, and with N experts Hedge's constant cannot be improved. Online gradient descent (Zinkevich 2003): regret D G √T, and online-to-batch conversion.
  • 6. Bandits. Four Bernoulli arms paying 0.5, 0.45, 0.4 and 0.3 (gaps 0.05, 0.10, 0.20); regret as the gaps times the pulls; Part 44's A/B test as explore-then-commit. UCB: the index μ̂_i + √(2 ln t / n_i), wrong with probability at most t⁻⁴ by Hoeffding (an illustrative run). UCB1's bound (Auer, Cesa-Bianchi and Fischer 2002), Σ 8 ln T/Δ_i + (1 + π²/3)ΣΔ_i: 2,386 at T = 5,000 against a measured 159. Thompson sampling (1933) from beta posteriors, probability matching. Measured over 100 runs of 5,000 rounds: ε-greedy (ε = 0.05) 75.1, UCB1 158.8, Thompson 49.7, against the Lai–Robbins rate 17.4 ln T (KL from AI, Built 1): UCB1 above it, Thompson below it at this T, which the asymptotic theorem allows. Why nobody does better: two worlds, 0.45 against 0.5, separated only as fast as e^{−n KL}; and an adversarial gap of √(K/T) forces regret of order √(KT).
  • 7. What cannot be learned. Circuits of size s need only O((s log s + ln 1/δ)/ε) examples; time is the limit. Finding a consistent 3-term DNF is NP-hard (Pitt and Valiant 1988), but the same function as a 3-CNF is learned by Valiant's elimination. A learner would be a code-breaker: if RSA or factoring is hard, small Boolean formulas and finite automata cannot be learned efficiently whatever the hypothesis (Kearns and Valiant 1994); pseudorandom functions (Goldreich, Goldwasser and Micali 1986; Part 29) rule out small circuits even with queries. Statistical queries cannot find a parity: different parities are orthogonal, and by Bessel's inequality a query of tolerance τ = 0.25 is informative about at most 16 of the C(10, 3) = 120 candidate sets, so at least τ² C(n, k) queries. Measured on 400 examples with k = 3 and n = 10, 14, 18, 22: the best single bit correlates 0.080, 0.115, 0.155 and 0.090 with the label; the subset search tried 113 of 120, 206 of 364, 515 of 816 and 1,508 of 1,540 sets; elimination over GF(2) from 2n examples found every set (on this machine, search 1.3 to 15.2 ms against elimination 0.25 to 0.75 ms). Learning parity with noise and Blum, Kalai and Wasserman's 2^{O(n/log n)}; Part 7's parity branch (the perceptron predictor 49% right). The landscape: finite VC dimension, polynomial time, statistical queries, and the SQ dimension (Blum et al. 1994).
  • 8. More parameters than data. Both errors of the hook's experiment (noise 0.5): training error is zero up to rounding (below 10⁻²⁸) from p = 50 on; test error 1.03 at p = 5, 52.1 at the threshold, 0.78 at p = 200; double descent (Belkin, Hsu, Ma and Mandal 2019). A class that fits every labelling has Rademacher complexity 1 and a vacuous bound; Zhang, Bengio, Hardt, Recht and Vinyals (2017) fitted CIFAR-10's random labels. The minimum-norm interpolator in a plane of two parameters, X⁺y = Xᵀ(XXᵀ)⁻¹y; gradient descent from zero stays in the row space and finds it, an implicit bias (AI, Built 8), and on separable data with the logistic loss heads for the maximum margin (Soudry et al. 2018). Why the peak: the noise term is σ̃² p/(n − p − 1) below the threshold and σ̃² n/(p − n − 1) above it (inverse Wishart means), with the unseen features as extra noise; the formula's curves against the measured medians; Part 52's ill-conditioning at p = n.
  • 9. Learning is compression. Occam's razor as a theorem (Kraft's inequality and a failure budget shared by code length; Blumer et al. 1987): ε_h = (|h| ln 2 + ln 1/δ)/m. A compression scheme of size 4 on 200 points: the four extreme positives rebuild a box that labels every point correctly; Littlestone and Warmuth's bound (k ln m + ln 1/δ)/(m − k) = 0.123, against a true error of 0.0173, the rectangle bound's 0.088 and the VC bound's 0.377 at m = 200. The perceptron is a compression scheme of size its mistakes: on 2,000 points the bound is 0.017, 0.090, 0.149 and 0.133 for d = 2, 10, 100 and 1,000, where no VC bound says anything. Minimum description length (Rissanen 1978): the 200 labels cost 200 bits raw, 146.4 bits entropy-coded (41 positive), 30.6 bits as four indices, and Occam's bound on those 30.6 bits is 0.121; Part 21's compressors. One shape, four measures: complexity times a logarithm over m.
  • 10. Frontier: compression schemes and in-context learning. The four kept points again; Warmuth's conjecture (2003) of schemes of size O(d), and Moran and Yehudayoff's (2016) schemes of size 2^{O(d)}. In-context learning: Garg et al. (2022) on transformers that match least squares in their prompts; what theory lacks; benign overfitting (Bartlett et al. 2020), understood for linear models. Four open problems (non-vacuous bounds for deep networks, in-context learning, learning parity with noise, structured bandits) and the ★ research problem.
  • Outro. Recap, payoffs, practice, problems, next part.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The PAC model (Valiant 1984); realizable and agnostic learning; the finite-class bound from the union bound.
  2. VC dimension; Sauer–Shelah, proved; the fundamental theorem of PAC learning, both directions.
  3. Rademacher complexity and margin bounds; why the perceptron's mistake bound (Novikoff 1962) depends on the margin, not the dimension (callback to Part 7).
  4. Boosting: weak to strong learning (Schapire 1990); AdaBoost as a zero-sum game; multiplicative weights again (Part 23).
  5. Online learning: the halving algorithm, the mistake-bound model, Littlestone dimension; regret and the experts problem; online gradient descent; online-to-batch conversion.
  6. Bandits: explore and exploit; UCB, Thompson sampling; the Lai–Robbins lower bound (callback to Part 44's experiments).
  7. The limits of learning: cryptographic hardness of learning (Kearns & Valiant); statistical-query lower bounds and parity (callback to Part 7's parity branch).
  8. Generalization in the overparameterized regime: double descent, implicit bias of gradient descent, benign overfitting (callbacks to AI, Built).
  9. Learning and compression: Occam's razor bounds, sample compression schemes, MDL (callback to Part 21).
  10. Frontier: the sample-compression conjecture (compression schemes of size O(d)? Moran & Yehudayoff 2016 gave size exponential in d) (verify); learning theory of transformers and in-context learning; open problems.
  11. Outro.

Computed: VC bounds against measured learning curves; shattering animated; AdaBoost's margins over rounds; regret curves for Hedge, UCB and Thompson sampling against their bounds; the perceptron's mistakes against Novikoff's bound on Part 7's branch traces; SQ hardness of parity, measured as learning time. Visuals: the shattering of point sets by half-planes; the boosting distribution re-weighting points; regret curves bending under √T. In practice: model selection and validation, online recommendation, bandit-based experimentation, ad auctions. Reading: Shalev-Shwartz & Ben-David, Understanding Machine Learning; Mohri, Rostamizadeh & Talwalkar, Foundations of Machine Learning; Kearns & Vazirani; Cesa-Bianchi & Lugosi, Prediction, Learning, and Games; Lattimore & Szepesvári, Bandit Algorithms; Valiant 1984; Littlestone 1988; Freund & Schapire 1997; Belkin et al. 2019.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. VC维。 证明平面上的半平面的 VC维为 3,轴对齐矩形的 VC维为 4。

    解答

    下界只需一个被打散的集合;上界必须击败每一个集合。半平面至少为 3:取三个不共线的点。若三点标签相同,取一条不碰 它们所成三角形的直线即可;否则有一个点与众不同,它是三角形的一个顶点,一条穿过该顶点处两条边的直线就把它切开。8 种标注全部 可以实现(我们的工具对 (0, 0)、(2, 0.3)、(0.8, 1.8) 逐一用线性规划检查)。至多为 3:由 Radon 定理,平面上任意四点都能分成 两组,使两组的凸包相交:要么一个点落在另外三点的三角形内,要么四点处于凸位置而两条对角线相交(三点共线是前一种情形的退化, 中间的点落在另两点的线段上)。把一组标为 +1,另一组标为 −1。半平面和它的补集都是凸的,于是一个要包含 +1 组的凸包,另一个要 包含 −1 组的凸包,而这两个凸包相交:不可能。在正方形的四个角上,16 种标注中有 14 种可分,失败的两种都把相对的两个角标成同色。 矩形至少为 4:取菱形上的四点 (1, 0)、(0, 1)、(−1, 0)、(0, −1)。对任意子集,子集的包围盒(或远离这些点的一个空盒子)不含其余 任何点,因为每个点都是它自己那个方向上唯一的极端点。至多为 4:在五个点中选出最左、最右、最低、最高的点各一个;这至多是四个 点,所以还剩下第五个点,而它的坐标落在这些极值之间。把选出的点标为 +1、第五个点标为 −1:任何包含选出各点的矩形都包含它们的 包围盒,因而也包含第五个点。

  2. 绍尔–谢拉引理。 对 m + d 归纳,证明 Sauer–Shelah 引理。

    解答

    记 Φ_d(m) = Σ_{i=0}^{d} C(m, i);要证 VC维至多为 d 的类在任意 m 个点上至多实现 Φ_d(m) 种标注。基础情形:若 d = 0, S 的两种不同标注在某点 x 上不同,类就会打散 {x},所以至多 1 = Φ_0(m) 种;若 m = 0,只有一种(空的)标注,而 Φ_d(0) = 1。 归纳步:设 S = {x_1, …, x_m},S′ = S \ {x_m},H_S 为 S 上实现的标注。令 H₁ 为 S′ 上能扩展成 H_S 中某个标注的标注,H₂ 为能以 两种方式扩展的那些。H_S 中每个标注都是 H₁ 的一行配上 x_m 的一个标签,而 H₂ 中的行出现两次,所以 |H_S| = |H₁| + |H₂|。H₁ 是 m − 1 个点上 VC维至多为 d 的类。H₂ 的 VC维至多为 d − 1:若它打散 T ⊆ S′,则 T 的每种标注都同时配有 x_m 的两种标签,H_S 就会 打散 T ∪ {x_m},其大小 |T| + 1 ≤ d。两种情形的 m + d 都更小,所以 |H_S| ≤ Φ_d(m − 1) + Φ_{d−1}(m − 1) = Σ_{i≤d} [C(m − 1, i) + C(m − 1, i − 1)] = Σ_{i≤d} C(m, i),最后一步是帕斯卡法则 (杨辉三角的递推)。在正方形的四个角上:H₁ 有 8 行(至多 Φ_3(3) = 8),H₂ 有 6 行(至多 Φ_2(3) = 7),14 ≤ 15 = Φ_3(4)。 当 m ≥ d 时,(d/m)^d Φ_d(m) ≤ Σ_{i≤d} C(m, i)(d/m)^i ≤ (1 + d/m)^m ≤ e^d,所以 Φ_d(m) ≤ (em/d)^d:半平面在十个点上, 92 ≤ 176 ≤ 744,而 2^10 = 1024。

  3. 诺维科夫界。 证明感知机在可分数据上至多犯 (R/γ)² 次错误。

    解答

    设对所有 i 有 ‖x_i‖ ≤ R,且存在单位向量 w* 使 y_i w* · x_i ≥ γ > 0(偏置可以用一个额外的常数坐标吸收,代价是 R 变大)。 从 w_0 = 0 出发,令 w_k 为第 k 次错误之后的权重,无论样本的顺序如何、扫描多少遍。进展:在 (x, y) 上犯错时 w_{k+1} = w_k + yx, 所以 w_{k+1} · w* = w_k · w* + y x · w* ≥ w_k · w* + γ,归纳得 w_k · w* ≥ kγ。长度:‖w_{k+1}‖² = ‖w_k‖² + 2y w_k · x + ‖x‖² ≤ ‖w_k‖² + R²,因为犯错时 y w_k · x ≤ 0;所以 ‖w_k‖² ≤ kR²。由 Cauchy–Schwarz 不等式及 ‖w*‖ = 1, kγ ≤ w_k · w* ≤ ‖w_k‖ ≤ √k R,因此 √k ≤ R/γ,k ≤ (R/γ)²。这个界里既没有维数,也没有样本个数。R = 1、γ = 0.1 时它是 100; 我们的工具在 2000 个点上运行,在 2、10、100 和 1000 维中分别犯了 4、23、38 和 34 次错误。

  4. Hedge。 证明取合适学习率的 Hedge 算法遗憾至多为 √((T/2) ln N)。

    解答

    Hedge 从权重 w_1(i) = 1 开始,按 p_t(i) = w_t(i)/W_t 出招,并更新 w_{t+1}(i) = w_t(i) e^{−η ℓ_t(i)},损失 ℓ_t(i) ∈ [0, 1];遗憾为 Σ_t p_t · ℓ_t − min_i L_i,其中 L_i = Σ_t ℓ_t(i)。从下方:对每个 i,W_{T+1} ≥ w_{T+1}(i) = e^{−η L_i}, 且 W_1 = N,所以 ln(W_{T+1}/W_1) ≥ −η L_i − ln N。从上方:W_{t+1}/W_t = Σ_i p_t(i) e^{−η ℓ_t(i)} = E[e^{−ηX}],其中 X = ℓ_t(I),I ~ p_t,是 [0, 1] 中的随机变量;霍夫丁引理给出 ln E[e^{−ηX}] ≤ −η E[X] + η²/8 = −η p_t · ℓ_t + η²/8。对 T 轮 求和,对数逐项相消:ln(W_{T+1}/W_1) ≤ −η Σ_t p_t · ℓ_t + η²T/8。两者合起来,对每个 i 有 Σ_t p_t · ℓ_t − L_i ≤ ln N/η + ηT/8。 右边在 η = √(8 ln N/T) 时最小,此时两项都等于 √(T ln N/8),和为 √(T ln N/2)。论证从未假设损失是随机的,所以只要每轮的损失在 出招揭晓之前选定,它对任何序列都成立。N = 20、T = 2000 时:η = 0.109,ln N/η = ηT/8 = 27.4,保证为 54.7;我们实测的遗憾为 30.7。若事先不知道 T,加倍技巧依次取 T = 1, 2, 4, … 重新开始,只损失一个常数因子。

  5. 动手。 为伯努利拉杆实现 UCB1 和汤普森采样,并把它们的遗憾与 Lai–Robbins 速率比较。

    解答

    解答要点。 对每个拉杆记下拉动次数 n_i 和奖励之和 s_i。UCB1 先把每个拉杆各拉一次,之后拉使 s_i/n_i + √(2 ln t / n_i) 最大的 拉杆;汤普森采样对每个拉杆抽 θ_i ~ Beta(s_i + 1, n_i − s_i + 1),拉最大的那个。记录伪遗憾 Σ_t (μ* − μ_{a_t}),它的方差远小于实际 奖励,再对多次运行取平均;每次运行抽一张 T × K 的奖励表并交给每个算法共用(共同随机数,正如 explainer/cs/learn/theory.py 中的 bandits 所做),比较会更清楚。Lai–Robbins 常数为 Σ_i Δ_i / KL(μ_i, μ*),其中 KL(p, q) = p ln(p/q) + (1 − p) ln((1 − p)/(1 − q))。对我们的拉杆 (0.5, 0.45, 0.4, 0.3),三项分别为 9.98、4.97 和 2.43,合计 17.38 ln T,T = 5000 时为 148.0;由 Pinsker 不等式 KL ≥ 2Δ²,所以这个常数至多为 Σ 1/(2Δ_i) = 17.5,对接近一半的硬币几乎是 紧的。我们的工具在 100 次、每次 5000 轮的运行中测得 UCB1 158.8,汤普森采样 49.7,ε-贪心(ε = 0.05)75.1。把遗憾画成 ln t 的 函数:定理说的是斜率。一旦 √(2 ln t / n_i) < Δ_i,坏拉杆就不再被拉,也就是大约 2 ln t/Δ_i² 次之后,所以 UCB1 的斜率应趋于 Σ 2/Δ_i = 70,是最优值的四倍;对缓存曲线在 t ≥ 1000 上拟合得 68.2。汤普森采样拟合的斜率为 13.3,在这个时长上仍低于 17.4,渐近 定理允许这样;ε-贪心的遗憾是线性的。再与 UCB1 的有限时间界(这里为 2386)对照,测试最优拉杆得到的拉动最多;作为扩展,加上 KL-UCB,它的指标直接用 KL散度,能达到 Lai–Robbins 常数(Garivier 与 Cappé,2011)。

  6. ★ 研究。 样本压缩猜想:是否每个 VC维为 d 的概念类都有大小为 O(d) 的压缩方案?

    讨论。 尚未解决。Littlestone 与 Warmuth(1986)证明了大小为 k 的方案给出与 VC维 k 相仿的 PAC 界(第 9 章的 (k ln m + ln 1/δ)/(m − k)),并问逆命题是否成立;Floyd 与 Warmuth(1995)为极大类构造了大小为 d 的方案,Warmuth 在 2003 年把 一般问题作为公开问题提出。难点在于方案是一个整体的对象:同一个重建函数必须对每种大小的每个样本都有效,而 VC 理论只是在数行为。 Moran 与 Yehudayoff(2016)证明了大小随 d 指数增长的方案总是存在,办法是压缩成几个小的子样本,使在其上训练的 ERM 假设经提升法 投票后与整个样本一致(第 4 章的极小极大论证);指数来自对偶 VC维,它可以达到约 2^d。矩形(大小 4 = d)和半空间(最大间隔分隔面 的至多 n + 1 个支持向量,d = n + 1)说明猜想中的界是自然的。好的部分答案可以是:把 2^{O(d)} 降到 d 的多项式;对一大族类(VC维 很小的类,或几何类)证明大小 O(d);或者给出迫使方案大小超过 d 的类,并在小的有限类上精确搜索方案(用 SAT 编码,交给第 26 部分 的 CDCL 求解器)来检验猜测的常数。

Build the film

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

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

Build it
python -m videos.cs.cs57.compute
python -m unittest tests.test_cs57_learning
python tools/build.py cs57