Simple Algorithm
Machine Learning · Initialization · 17 min

Generalization & Model Selection

Why models that fit the past can predict the future, and when they can’t.

A model that gets every training example right can still fail on the very next one. This lesson is about the gap between fitting the past and predicting the future: why it opens, how to see it, how to measure it without fooling yourself, and why the largest modern models bend some of the classic rules.

What you’ll learn

  • Tell training error from test error, and recognize underfitting and overfitting from the two.
  • Describe bias and variance as two different ways a model can miss, and how a complexity knob trades one for the other.
  • Choose a model with a validation set or k-fold cross-validation, and explain why the test set is used only once.
  • Explain why more data and regularization help, and why comparing many models on one dataset produces lucky winners.

Fitting the past, predicting the future

A model learns from the examples it is shown, the training set. It is only useful if it also works on examples it has never seen. That ability is called generalization.

Picture two students preparing with last year's exam. One memorizes every answer; the other learns the method behind them. Both score 100% on last year's paper, and only one passes this year's. Grading a model on its own training examples is like grading the first student on last year's paper: it tells you almost nothing.

So you keep some examples aside, a test set, and judge the model there. The training error is the average error on the examples the model learned from; the test error is the average error on fresh ones. The difference between them is the generalization gap.

One assumption makes the whole idea work: the fresh examples must come from the same source as the training examples, the same distribution (the i.i.d. assumption). A model of last year's customers can fail on next year's for reasons no test set from last year will reveal.

Predict before you look

The wave above has 12 training points, all at different positions xx. What is the lowest polynomial degree that can pass exactly through all 12?

Show the answer

11

A polynomial of degree dd has d+1d+1 adjustable coefficients. Two points fix a line (degree 1), three fix a parabola (degree 2), and twelve fix a polynomial of degree 11. With one knob per data point the model can hit every training point exactly, noise included, so its training error is zero. That is a warning sign, not an achievement.

Underfitting, overfitting and complexity knobs

Every family of models has knobs that set how flexible it is, its complexity. With too little flexibility the model cannot express the pattern: it underfits, and both errors are high. With too much it bends to fit accidents of this particular sample: it overfits, with a low training error and a high test error. In between lies a sweet spot.

The knobs look different from model to model, but they all play this role. A setting like this, chosen by you rather than learned from the data, is called a hyperparameter.

ModelKnobMore flexible when…At the extreme
Polynomialdegreethe degree goes upa degree-11 curve threads 12 points
k-nearest neighborskk, the number of neighbors that votekk goes downk=1k=1 copies the label of the single closest training point, stray ones included
Decision treedepththe depth goes upa deep enough tree gives every training point its own leaf
Regularized modelpenalty strength λ\lambdaλ\lambda goes downλ=0\lambda=0 removes the brake on large coefficients
Neural networktraining timetraining runs longerlate in training it starts memorizing individual examples
Different knobs, one story: as flexibility grows, training error keeps falling, while test error falls and then rises.
Check your understanding

A spam filter has a training error of 30% and a test error of 31%. You need it below 10%. What is the most likely problem?

  1. Overfitting: it has memorized the training emails
  2. The test set is too small to trust
  3. Underfitting: the model is too simple for the pattern
  4. Nothing: training and test error agree, so the model is fine
Show the answer

C. Underfitting: the model is too simple for the pattern

Both errors are high and nearly equal: the model cannot capture the pattern even on the data it trained on. That is underfitting. A more flexible model, better features or a weaker penalty should help; more data on its own will not.

Two ways to miss: bias and variance

Imagine collecting a brand-new training set from the same source, retraining, and repeating a hundred times. You would get a hundred slightly different models, and two separate things can go wrong:

  • Bias: on average the models miss in the same direction. A straight line fitted to a wave is wrong in the same places every time, however many datasets you try.
  • Variance: the models disagree with each other. A wiggly high-degree curve looks completely different for every new sample of noise.

A third part of the error belongs to the data, not to the model: the noise, the part of each label that no input can predict.

For squared error the three parts add up exactly. The Descent lesson proves it in a few lines; for now, read it as an accounting identity:

expected test error=noise⏟in the data+bias2⏟too rigid+variance⏟too sensitive\text{expected test error}=\underbrace{\text{noise}}_{\text{in the data}}+\underbrace{\text{bias}^2}_{\text{too rigid}}+\underbrace{\text{variance}}_{\text{too sensitive}}
Raising complexity usually lowers bias and raises variance: the bias–variance trade-off. The noise term is the same for every model, a floor no model can go below.
Check your understanding

A hospital trains the same model on five different random samples of its patients. Each model fits its own sample well, but the five models flag very different patients as high-risk. Which part of the error dominates?

  1. Bias
  2. Noise
  3. Variance
  4. None: fitting each sample well means the models are good
Show the answer

C. Variance

The models change a lot when the training sample changes: that is variance. A model that fits its own sample well but disagrees with its siblings is fitting the quirks of each sample.

A mock exam: validation and cross-validation

To choose a degree, a kk or a λ\lambda, you need an estimate of the test error for each candidate. Using the test set for that is like studying with the exam paper in hand: once you pick the candidate that scored best on it, its score is no longer honest, because you chose it partly for luck on those particular examples.

So split the data three ways: fit on the training set, compare candidates on a validation set (a mock exam), and touch the test set once, at the very end.

Setting aside a validation set wastes data when data are scarce. Cross-validation lets every example take a turn:

  1. Split the data into kk equal parts, called folds.
  2. Train on k−1k-1 folds and measure the error on the fold left out.
  3. Rotate until every fold has been left out once.
  4. Average the kk errors.

With k=5k=5 or 1010, this k-fold cross-validation is the everyday workhorse of model selection.

Predict before you look

You try 20 useless models, each truly no better than guessing, on the same validation set. Each one, independently, has a 5% chance of looking good by pure luck. What is the chance that at least one of them looks good?

Show the answer

64 %

One model fails to look lucky with probability 0.950.95, so all 20 fail with probability 0.9520≈0.360.95^{20}\approx0.36. The chance that at least one looks good is 1−0.36=64%1-0.36=64\%. Compare enough candidates on one dataset and a lucky winner is almost guaranteed, which is why the final test set stays locked until you have finished choosing.

More data, and how much is enough

More data is the most reliable cure for variance. With more points the noise averages out, and flexible fits stop disagreeing with each other. It does nothing for bias: a straight line stays a straight line however much data you feed it. A learning curve, training and validation error plotted against the number of examples, tells you which situation you are in.

How many examples are enough? Learning theory gives guarantees of this kind. Suppose one of NN candidate rules is exactly right, and you pick any candidate that makes no mistakes on your mm training examples. If

m ≥ ln⁡N+ln⁡(1/δ)ε,m\ \ge\ \frac{\ln N+\ln(1/\delta)}{\varepsilon},

then with probability at least 1−δ1-\delta the rule you picked errs on at most a fraction ε\varepsilon of new cases. With N=1000N=1000 rules, ε=5%\varepsilon=5\% and δ=5%\delta=5\%, that is about 200 examples.

Think first In that formula, what happens to the number of examples needed if you double the number of candidate rules, from 1,000 to 2,000?

It grows by only ln⁡2/0.05≈14\ln 2/0.05\approx14 examples, because the count of rules enters through its logarithm. What costs examples is the richness of the candidates you search, not the raw count, and for infinite families (all lines, all curves) theory measures richness by the largest number of points on which the family can fit every possible pattern of labels, its VC dimension. The Descent lesson on learning theory makes this precise.

Regularization: a leash on the curve

Instead of restricting the model's form, you can penalize its excesses. Regularization adds to the training error a cost for large coefficients, weighted by a strength λ\lambda. The fit then prefers calm curves unless the data insist on wiggles. Ridge regression and the lasso are the classic penalties; stopping a network's training early (early stopping) works in a similar spirit.

It is a deliberate trade: a little bias for a lot less variance.

Modern surprises, and the road ahead

The classic story says: keep the model small enough, or regularize it, or it will memorize noise and fail. Modern neural networks seem to break it. They often have far more parameters than training examples, can fit training sets perfectly even when the labels are pure noise, and still predict well on real data.

Plotted against model size, test error can fall, rise to a peak around the size at which the model can just barely fit every training example (interpolation), and then fall again: double descent. The bias–variance accounting still holds exactly; what fails is the idea that the number of parameters measures complexity. Why huge networks generalize is not fully settled, and it is one of the most active questions in the field.

Think first If a network can fit completely random labels perfectly, why doesn't it just memorize the training set when the labels are real?

Fitting random labels shows the network could memorize. It does not show that it does when real structure is present. Training with gradient descent seems to prefer simple solutions that fit the structure first, and with real labels a simple solution exists. Pinning down which solutions training prefers, and why they generalize, is the subject of the Descent lesson on modern generalization and its Convergence deep dives.

Descent lessonWhat you will do there
Overfitting & the Bias–Variance Trade-offDerive noise + bias² + variance, turn every complexity knob, and diagnose a model from its learning curves.
Validation & Cross-ValidationRun k-fold and leave-one-out cross-validation, apply the one-standard-error rule, split grouped and time-ordered data correctly, and nest cross-validation for an honest final estimate.
Learning Theory: How Many Examples Are Enough?Make "enough examples" precise with PAC learning, and measure the richness of a model family with the VC dimension.
Generalization in Modern MLWatch double descent happen, meet the implicit regularization of gradient descent, and see what is still unexplained.
In the Descent level each idea gets its math and its algorithms.

Key takeaways

  • Generalization means low error on new data from the same source. Training error is an optimistic guide; judge models on held-out data.
  • Too simple underfits (high bias); too flexible overfits (high variance). For squared error, expected test error = noise + bias² + variance exactly.
  • Choose models with a validation set or k-fold cross-validation, and touch the test set once, at the end: picking the best of many scores on one dataset selects luck.
  • More data cures variance, not bias. Regularization trades a little bias for much less variance, which is why parameter counts are a poor measure of complexity.
  • Huge modern models can fit noise and still generalize, and test error can descend twice: the classic U-curve is not the whole story.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A decision tree grown to full depth classifies its training set with 2% error, and the test set with 25%. Which diagnosis and fix fit best?

  1. Underfitting: grow the tree deeper
  2. Overfitting: limit the depth, prune, or get more data
  3. Nothing is wrong: test error is always higher than training error
  4. The training set is too large
Show the answer

B. Overfitting: limit the depth, prune, or get more data

A large gap between a low training error and a high test error is the signature of overfitting: a full-depth tree can carve out a leaf for almost every training example, noise included. Anything that limits its flexibility, or gives it more data to average over, narrows the gap.

Question 2

A team submits 200 variants of its model to a leaderboard that scores each on the same hidden test set, then announces its best leaderboard score. Why is that score likely to be too optimistic?

  1. Because hidden test sets are always harder than real data
  2. Because 200 variants are too few to find a good one
  3. Because the best of 200 scores on one test set is partly picked for luck on those particular examples
  4. It is not optimistic: the test set was hidden, so it stays unbiased
Show the answer

C. Because the best of 200 scores on one test set is partly picked for luck on those particular examples

Each score is the true performance plus some luck of the draw. Choosing the maximum of 200 scores selects the luckiest draw too, so the winner's score overstates how it will do on fresh data. Hiding the test set does not help if its feedback steers your choices.

Question 3

You fit straight lines to many different samples from a strongly curved trend. The lines are nearly identical, and all of them miss the bend in the same places. What describes this model?

  1. High bias, low variance
  2. Low bias, high variance
  3. High bias and high variance
  4. Low bias, low variance
Show the answer

A. High bias, low variance

The lines barely change from sample to sample (low variance), but their shared average misses the curve systematically (high bias). More data will not help; a more flexible model will.

Question 4

In 5-fold cross-validation on 100 examples, how many times is each example used to measure the error?

  1. Never: it is only used for training
  2. Four times
  3. Five times
  4. Exactly once
Show the answer

D. Exactly once

Each example sits in exactly one fold, and each fold is held out exactly once. So every example is used once for measuring error and four times for training (in the other four rounds).

Question 5

Which problem does collecting much more training data (from the same source) fix most reliably?

  1. High bias
  2. High variance
  3. Noise in the labels
  4. A test set that was reused too often
Show the answer

B. High variance

More data averages out the noise that flexible models chase, so their fits stop changing much from sample to sample: variance falls. Bias belongs to the model's form, and label noise belongs to the data, so neither goes away.

Go deeper

Further reading

  • G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), §2.2 and chapter 5.
  • M. Belkin, D. Hsu, S. Ma & S. Mandal, "Reconciling modern machine-learning practice and the classical bias–variance trade-off," Proceedings of the National Academy of Sciences 116(32), 15849–15854 (2019).