The learning problem: generalization, bias-variance and regularization
- Beginner
- 35 min
- Lesson 1 of 2 in ML foundations
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
You will be able to
- Frame a task as supervised learning, and explain why we minimise empirical risk on training data as a stand-in for expected risk on unseen data.
- State the job of the train, validation and test sets, and name the leaks that make a reported score too optimistic.
- Diagnose high bias or high variance from train and validation error and from learning curves, and pick the fix that matches.
- Explain how an L2 or L1 penalty changes the fitted weights, why only L1 gives exact zeros, and how the strength lambda trades variance for bias.
Concept
This is a common opening topic in machine learning interviews, and every later lesson builds on it. Here is the whole idea in one sentence: learning means fitting the past without memorizing it.
In supervised learning you have examples : inputs (features) and the answers you want (labels). You pick a family of functions with adjustable parameters , and you search for the parameters that make good predictions on inputs the model has never seen.
The catch is in the last clause. You can only measure error on data you have. Think of grading a student on the practice book and hoping the score predicts the exam. So you do something indirect: you minimise the average loss on the training set, called the empirical risk, and hope it tracks the expected risk, the average loss over the real world.
| Symbol | Meaning |
|---|---|
| Number of training examples | |
| The model’s prediction for input | |
| The true label | |
| Loss: how wrong one prediction is (squared error, log loss) | |
| A penalty on model complexity (regularizer) | |
| How strongly the penalty counts. You choose it; it is a hyperparameter |
The rest of this lesson is about the gap between “low training loss” and “works on new data”, and the tools that manage it.
Other learning settings differ in what you have. Supervised learning has inputs and labels (fraud or not, a house price). Unsupervised learning has inputs only (customer clusters). Self-supervised learning builds labels from the data itself (next-token prediction in language models). Reinforcement learning has a reward signal from actions. This course starts with supervised learning because most production ML is supervised, and its ideas carry over.
The common losses (squared error versus absolute error, cross-entropy, hinge) are compared in the next lesson on linear models, loss and optimization. Two vocabulary points that interviewers probe. Parameters (weights) are learned from training data by the optimizer. Hyperparameters (learning rate, tree depth, ) are set by you, and you choose them using validation data.
Why It Matters
If minimising training loss were enough, the best model would be a lookup table that memorizes every training example. It would score zero training error and be useless on the first new input.
Generalization is the whole point, and it is where real projects fail. A model with 99% training accuracy and 80% validation accuracy is common, and it is not a success. In production you meet a second version of the problem: the data you train on is a snapshot of the past, and the data you serve is the future. Every tool in this lesson is a way to estimate or improve how a model behaves on data it was not fitted to.
Mental Model
Think of a student preparing for an exam. The training set is the practice book. A student who memorizes the answers to every practice problem gets full marks on the book and fails the exam when the questions change. That is overfitting. A student who only learned “answers are usually B” scores poorly on the book and the exam alike. That is underfitting.
The exam has to be a fresh set of questions, or it measures nothing. That is why we hold data back. And if the student keeps retaking the same mock exam and tweaking their study plan based on the result, the mock exam has become part of the practice book. That is what happens when you tune on the test set.
Splits and leakage
You need three jobs done on three separate pieces of data.
- Train fits the parameters.
- Validation chooses hyperparameters and compares models. Each time you look at it and make a decision, it leaks a little information into your choices.
- Test is used once, at the end, to report an unbiased estimate.
A memory hook: train learns, validation chooses, test judges.
The scikit-learn documentation states the danger directly: when you tweak hyperparameters until the score on the test set is good, “knowledge about the test set can ‘leak’ into the model and evaluation metrics no longer report on generalization performance” (scikit-learn, Cross-validation).
Splitting three ways has a cost: you spend data on evaluation that could have trained the model. With small data, use k-fold cross-validation. Rotate which fold is the validation fold and report the mean and spread. Keep a test set aside anyway. Pick the variant that matches your data:
| Situation | Split to use | Why |
|---|---|---|
| Imbalanced classes | Stratified k-fold | Keeps the rare class in every fold |
| Several rows per patient or user | Group k-fold | One entity must not sit on both sides of the split |
| Data ordered in time | Time-ordered (forward-chaining) split | The model must not train on the future |
The most common leak
Fitting a scaler or imputer on all the data before splitting. The mean and standard deviation of the held-out rows then influence training. The documentation’s rule is that preprocessing “should be learnt from a training set and applied to held-out data”, and a Pipeline does this correctly inside each cross-validation fold (scikit-learn, Cross-validation). Other traps: reporting the best cross-validation score as the final estimate (you chose it because it was the best), and celebrating a high training score.
Bias, variance and learning curves
Two different ways to be wrong explain nearly all generalization failure.
- Bias is systematic error from a model too simple for the pattern. A straight line fitted to a curve is wrong in the same way on every training sample you draw.
- Variance is sensitivity to the particular training sample. A very flexible model fitted to a different sample would come out very different, because it is fitting the noise in each one.
For squared error at a point , the expected error over random training sets splits into three parts:
The last term is noise in the labels themselves. No model can remove it, so it is a floor under every error number you see.
Worked example: a degree sweep
The data: with noise standard deviation 0.3, so the noise variance, the floor, is . There are 15 training points spread over and 18 random validation points. We fit polynomials of increasing degree by least squares and measure mean squared error (MSE). The full script is in the Code section; it solves the equations in exact fractions, so the numbers are not round-off artefacts (a high-degree fit solved in ordinary floating point can be badly wrong). The scikit-learn gallery shows the same pattern with degrees 1, 4 and 15 on a noisy cosine (scikit-learn, Underfitting vs. Overfitting).
| Degree | Train MSE | Validation MSE | Reading |
|---|---|---|---|
| 1 | 0.326 | 0.372 | Bias: both errors are about four times the 0.09 floor |
| 3 | 0.081 | 0.121 | Best validation error, close to the floor |
| 5 | 0.056 | 0.215 | Validation error has started to climb |
| 9 | 0.025 | 0.811 | Variance: train keeps falling, validation is much worse |
| 12 | 0.015 | 17.593 | Variance, extreme: 13 coefficients for 15 points |
Training error never rises as you add flexibility, because each polynomial family contains the one before it. Validation error falls, reaches a minimum at degree 3, then climbs. The shape matters more than the exact digits.
One trap: do not read “train error below the noise floor” as proof of overfitting. Any fitted model has training error a little below the floor, because it was fitted to those very points. A least-squares model that is correctly specified, with parameters, has expected training MSE of , which would be for and (the textbook name is the optimism of the training error, ESL section 7.4). The signal is on the other side: compare validation error with the floor, and watch the gap between the two.
Is this one seed typical? I repeated the degree sweep over 100 random seeds. Degree 3 beat degree 1 on validation in 98 of them, degree 12 was worse than degree 3 in 96, and the best degree was 3 in 61, 5 in 29 and something else in 10. The median validation MSE rose from 0.112 (degree 3) to 0.535 (degree 12), while the median training MSE fell from 0.068 to 0.013.
Learning curves: will more data help?
A learning curve plots train and validation error against the number of training examples. The picture tells you which problem you have and, crucially, whether collecting data is worth the money. The scikit-learn guide puts it this way: “you should only collect more training data if the true function is too complex to be approximated by an estimator with a lower variance” (scikit-learn, Validation curves).
A second run uses a pool of 60 shuffled training points and 200 validation points (a larger validation set steadies the estimate), a ridge penalty of , and the first points of the pool each time. The script is in the Code section.
| Model | Train size | Train MSE | Validation MSE |
|---|---|---|---|
| Degree 1 | 15 | 0.313 | 0.291 |
| Degree 1 | 30 | 0.311 | 0.309 |
| Degree 1 | 60 | 0.306 | 0.287 |
| Degree 9 | 15 | 0.059 | 0.219 |
| Degree 9 | 30 | 0.096 | 0.112 |
| Degree 9 | 60 | 0.095 | 0.087 |
The straight line’s two curves sit together at about 0.3, over three times the noise floor, and do not move as data quadruples. More data will not help; it needs more capacity or better features. The degree-9 curves start apart and converge as data grows, so here more data really does help (as would regularization). Validation at is a little under 0.09 only because 200 validation points are themselves a noisy estimate. Over 20 other seeds the median degree-9 validation MSE at was 2.464 (the curves can start very far apart) and 0.103 at .
| Symptom | Diagnosis | What helps | What does not |
|---|---|---|---|
| Train and validation both high and close | High bias | Richer model, new features, less regularization | More data of the same kind |
| Low train, much higher validation | High variance | More data, regularization, simpler model, early stopping, bagging | A bigger model |
Model capacity and regularization are two knobs on the same trade. Many variance-reducing changes act as regularization.
Regularization
The cheapest way to stop a flexible model from fitting noise is to charge it for large weights. Large weights are what let a curve wiggle through every point. The two standard charges are the L2 and L1 norms of the weights.
L2 (ridge): shrink smoothly
Add to the loss. For linear regression this gives a closed form:
Adding also makes safely invertible when features are nearly collinear. Without it, the least-squares estimate is, in the scikit-learn documentation’s words, “highly sensitive to random errors in the observed target, producing a large variance” (scikit-learn, Linear models). Ridge is a good default, especially with many correlated features.
L1 (lasso): shrink and select
Add instead. Lasso “is able to set coefficients exactly to zero” (scikit-learn, Linear models), so it doubles as feature selection. The original paper explains that the constraint on the sum of absolute coefficients “tends to produce some coefficients that are exactly 0” (Tibshirani, 1996).
Why exact zeros? A worked one-feature example
Use one feature with no intercept and three points: , . Then and . Ordinary least squares gives .
With the loss (ridge), setting the derivative to zero gives:
With the loss (lasso), the derivative gives, while stays positive:
| Ridge | Lasso | |
|---|---|---|
| 0 | 1.786 | 1.786 |
| 7 | 1.190 | 1.286 |
| 14 | 0.893 | 0.786 |
| 25 | 0.641 | 0.000 |
| 140 | 0.162 | 0.000 |
Read the table for the mechanism. Ridge divides the weight by a bigger number: it shrinks in proportion to the weight and approaches zero but never arrives, even at . Lasso subtracts a fixed amount: once reaches the weight is exactly zero and stays there. In gradient terms, the L2 penalty pushes back with force proportional to (weak on small weights), while the L1 penalty pushes with constant force regardless of size. Geometrically, the L1 constraint region is a diamond with corners on the axes, and the loss contour tends to touch a corner, where some weights are zero; the L2 region is a disc with no corners.
The two losses are scaled differently (one has a factor of one half), so compare the shapes of the columns, not the strength of one row against the other.
The price: bias
Regularization is not free. On the same three points the unregularized fit has training MSE 0.119. Ridge with halves the weight, and the training MSE becomes 3.839. That is the trade: you accept a worse fit to the training data in return for a model less sensitive to the sample. Too much underfits. You choose on validation data, never on the test set.
The same effect on the degree-12 polynomial from the sweep above (the penalty is on the coefficients of powers of the rescaled , not the intercept):
| Lambda | Train MSE | Validation MSE |
|---|---|---|
| 0.00000001 | 0.015 | 17.593 |
| 0.01 | 0.049 | 0.326 |
| 0.1 | 0.062 | 0.181 |
| 1 | 0.192 | 0.220 |
| 10 | 0.522 | 0.506 |
Training error rises with every step. Validation error falls from 17.6 to its minimum of 0.181 at , then climbs again as the model underfits. Choose at that minimum, on validation data. With the penalty tuned, the degree-12 polynomial goes from 17.593 to 0.181, a huge improvement, though on this draw it still does not beat the plain cubic’s 0.121.
| L2 (ridge) | L1 (lasso) | |
|---|---|---|
| Penalty | ||
| Effect | Shrinks all weights smoothly | Drives some weights to exactly 0 |
| Bayesian reading | Gaussian prior on the weights | Laplace prior on the weights (the lasso is the posterior mode) |
| Best when | Many correlated features, default choice | You want a sparse, selected model |
| Weakness | Keeps every feature | With correlated features, picks one arbitrarily |
Elastic net mixes both penalties. The scikit-learn documentation says it is useful when several features are correlated: “Lasso is likely to pick one of these at random, while elastic-net is likely to pick both” (scikit-learn, Linear models). The Bayesian reading comes from the shape of the penalty: a Gaussian prior on a weight has a negative log proportional to , and a Laplace prior has one proportional to . Tibshirani (1996) noted that the lasso is the posterior mode under independent Laplace priors, as Park and Casella (2008) restate. Other ways to control variance are early stopping (halt when validation loss stops improving), data augmentation, a smaller model and more data; dropout and weight decay for neural networks come in the deep learning module.
Standardize features before an L1 or L2 penalty. (The polynomial script instead rescales to , which keeps every power on a comparable scale.) The penalty adds up the sizes of the weights, and a weight’s size depends on the feature’s units. A feature measured in metres is penalized differently from the same feature in millimetres. Fit the scaler on the training data only.
Libraries also scale the penalty differently. scikit-learn’s Ridge minimises , while Lasso uses . The same alpha is not the same strength across them (scikit-learn, Linear models).
Code
This standard-library script produced every number in the degree sweep, the lambda table and the learning curves. It uses exact fractions, so it needs no installs and has no round-off. The numbers were checked with Python 3.14; they rely on random.Random(0) and random.Random(1000), so another Python version could draw different noise. If your printed values differ in the last digit or more, the shape (validation minimum at a moderate degree, explosion at high degree) should still hold.
import math
import random
from fractions import Fraction as Fr
def solve(A, b):
"""Gaussian elimination in exact fractions, so there is no round-off."""
n = len(A)
M = [row[:] + [b[i]] for i, row in enumerate(A)]
for c in range(n):
p = next(r for r in range(c, n) if M[r][c] != 0)
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
w = [Fr(0)] * n
for i in range(n - 1, -1, -1):
w[i] = (M[i][n] - sum(M[i][k] * w[k] for k in range(i + 1, n))) / M[i][i]
return w
def basis(x, degree):
t = Fr(x) * 2 - 1 # rescale x from [0, 1] to [-1, 1]
return [t ** j for j in range(degree + 1)]
def fit(xs, ys, degree, lam):
"""Ridge-penalised polynomial fit; the intercept is not penalised."""
rows = [basis(x, degree) for x in xs]
p = degree + 1
A = [[sum(r[i] * r[j] for r in rows) + (Fr(lam) if i == j and i > 0 else 0)
for j in range(p)] for i in range(p)]
b = [sum(r[i] * Fr(y) for r, y in zip(rows, ys)) for i in range(p)]
return solve(A, b)
def mse(w, xs, ys):
pred = lambda x: float(sum(a * b for a, b in zip(w, basis(x, len(w) - 1))))
return sum((pred(x) - y) ** 2 for x, y in zip(xs, ys)) / len(xs)
def noisy_sine(x, rng):
return math.sin(2 * math.pi * x) + rng.gauss(0, 0.3)
rng = random.Random(0)
xt = [(i + rng.random()) / 15 for i in range(15)] # 15 training points, spread over [0, 1]
yt = [noisy_sine(x, rng) for x in xt]
xv = [rng.random() for _ in range(18)] # 18 validation points
yv = [noisy_sine(x, rng) for x in xv]
print("degree sweep, lambda = 1e-8")
for d in (1, 3, 5, 9, 12):
w = fit(xt, yt, d, 1e-8)
print(d, round(mse(w, xt, yt), 3), round(mse(w, xv, yv), 3))
print("degree 12, lambda sweep")
for lam in (1e-8, 1e-2, 1e-1, 1, 10):
w = fit(xt, yt, 12, lam)
print(lam, round(mse(w, xt, yt), 3), round(mse(w, xv, yv), 3))
print("learning curves, lambda = 1e-8, 200 validation points")
rng = random.Random(1000)
pool = [(i + rng.random()) / 60 for i in range(60)]
rng.shuffle(pool)
ypool = [noisy_sine(x, rng) for x in pool]
xv2 = [rng.random() for _ in range(200)]
yv2 = [noisy_sine(x, rng) for x in xv2]
for d in (1, 9):
for n in (15, 30, 60):
w = fit(pool[:n], ypool[:n], d, 1e-8)
print(d, n, round(mse(w, pool[:n], ypool[:n]), 3), round(mse(w, xv2, yv2), 3))What to look for: at degree 12, raising lambda should shrink the gap between train and validation error. At degree 1 it would not help, because that model has a bias problem, not a variance problem. In scikit-learn the equivalent is make_pipeline(PolynomialFeatures(d), StandardScaler(), Ridge(alpha=...)), which refits the scaler on training rows only.
Real-World Application
On a real project the checklist runs in this order. First, rule out a split bug or leakage: a model that is suspiciously good on training data and poor on validation can mean overfitting, but it can also mean the validation set does not resemble production. Then compare against a simple baseline. Then read the learning curves to decide where to spend the next week: data collection for a variance problem, feature work for a bias problem.
A concrete case: a model scores 99% on training and 80% on validation. Fix order: check for leaks and a mismatched validation set, then add data or regularization, reduce complexity, use early stopping or augmentation, and confirm that validation looks like production traffic. More data does not rescue a high-bias model, and it does not rescue noisy labels or a training distribution that differs from serving.
Interview Perspective
Expect “explain bias-variance and how you diagnose each”, “why does L1 give sparse weights”, “train 99%, validation 80%: what do you do”, and “when would more data not help”. A strong answer follows a pattern: one-line definition, the picture, the formula or mechanism, when it fails, and a real example. The weak answer lists regularizers without saying which problem each solves.
Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.
Practice Questions
- Basic: What is the difference between a parameter and a hyperparameter? Give an example of each.
- Intermediate: Training error is 2% and validation error is 25%. Diagnose it and give three fixes.
- Advanced: Why do the penalty gradients explain L1 sparsity but L2 shrinkage?
- Product-Company: A teammate tunes five hyperparameters by looking at the test score and reports the best one. What is wrong, and what do you change?
Activity
Fit the one-feature example from the Regularization section by hand: compute the ridge and lasso weights for and for , then say which of the two ever reaches exactly zero and why. Then sketch the learning curves you would expect for a straight line fitted to curved data and for a degree-15 polynomial, and mark the noise floor.
Homework
Implement ridge and lasso for a single feature, a validation-error function, a bias-or-variance diagnosis rule, and a lambda search. The code is in homework/; run the tests until they pass.
Quick Revision
- Learning = minimise empirical risk (training loss) as a proxy for expected risk on unseen data.
- Train fits, validation chooses, test judges once. Fit every scaler inside the training fold.
- Error = bias squared + variance + irreducible noise. High train error means bias; low train error with a big validation gap means variance.
- Learning curves show whether more data helps (variance: yes; bias: no).
- L2 shrinks all weights in proportion; L1 subtracts a constant and reaches exact zero. Too much lambda underfits. Standardize first.
Check yourself
- Walk-through: Without notes, explain what you check, in order, when train accuracy is 99% and validation accuracy is 80%.
- Variation: The same gap appears after you double the training set and it shrinks only a little. What does that tell you?
- Common misconception: “More data fixes everything”, and “regularization always improves the model”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Hands-on
Underfitting vs. Overfitting (opens in a new tab)
A short runnable script that sweeps polynomial degree. Change the degree and the noise and watch the cross-validated error move.
More for this module: ML foundations resources
Practice
Test what you just read. Quizzes and cards are grouped by module: ML foundations.
Check yourself12 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.