Slides · ML foundations

The learning problem: generalization, bias-variance and regularization

The learning problem

Fit the past without memorizing it: generalization, bias and variance, and the penalties that keep a model honest.

Concept

Why this is worth 35 minutes

  • A model that scores 99% on its training data and 80% on new data is common, and it is not a success.
  • Every later lesson, from trees to transformers, is another way to fit data and another way to fail to generalize.
  • This is also a common opening topic in ML interviews.

Four things you will be able to do:

  1. Frame a task as supervised learning and explain empirical risk.
  2. Use train, validation and test sets and spot leaks.
  3. Diagnose bias versus variance from error and learning curves.
  4. Explain what L1 and L2 penalties do and why lambda is a trade.

Concept

Supervised learning in one picture

  • You have examples (xi,yi)(x_i, y_i): inputs and the answers you want.
  • You pick a model family fθf_\theta and search for parameters θ\theta.
  • The goal is good predictions on inputs the model has never seen.
  • Unsupervised has inputs only; self-supervised makes its own labels; reinforcement learns from rewards.

Mental model: a student and a practice book. Full marks on the book means little unless the exam has fresh questions.

Math

Empirical risk versus expected risk

θ^=arg⁡min⁡θ  1n∑i=1nℓ(fθ(xi), yi)  +  λ R(θ)\hat\theta = \arg\min_\theta \; \frac{1}{n}\sum_{i=1}^{n} \ell\big(f_\theta(x_i),\, y_i\big) \;+\; \lambda\, R(\theta)
SymbolMeaning
nnNumber of training examples
ℓ\ellLoss for one prediction
R(θ)R(\theta)Penalty on complexity
λ\lambdaPenalty strength, a hyperparameter you choose
  • The average over the training set is the empirical risk. We can compute it.
  • The average over all future data is the expected risk. We cannot, so we hope the first tracks the second.
  • Parameters are learned by the optimizer. Hyperparameters, such as λ\lambda, are chosen on validation data.

Diagram

The pipeline and where it breaks

Diagram: The model, loss and optimizer form a training loop.

no

yes

Data X, y

Model f(x, w)

Loss

Optimizer

Evaluate on unseen data

Generalizes?

Fix: data, features,
capacity, regularization

Ship and monitor

Diagram summary: The model, loss and optimizer form a training loop. Only evaluation on unseen data decides whether to ship or to change data, features, capacity or regularization and loop again.

Check yourself

Check: why not just minimise training loss to zero?

A lookup table that memorizes every training row scores zero training loss. What is wrong with shipping it?

Answer

It has learned the training rows, not the pattern, so its error on a new input is unrelated to its training error. Empirical risk only stands in for expected risk when the model generalizes, and only held-out data shows that.

Process

Three splits, three jobs

  1. Train fits the parameters.
  2. Validation chooses hyperparameters and compares models. Every look leaks a little.
  3. Test is used once, at the end, to report an unbiased estimate.

Memory hook: train learns, validation chooses, test judges.

  • A common default is about 70% / 15% / 15%. It is a default, not a rule.
  • With small data, rotate the validation fold with k-fold cross-validation and keep the test set aside.

Source1 Cross-validation: evaluating estimator performance

Diagram

One dataset, three disjoint parts

Diagram: The data is cut into three disjoint parts.

All data

Train, about 70%
fit weights

Validation, about 15%
tune hyperparameters

Test, about 15%
one final look

Diagram summary: The data is cut into three disjoint parts. Train fits weights, validation tunes hyperparameters, and test is held back for one final report.

Compare

Leaks that inflate a score

LeakWhy it inflates the scoreFix
Scaler or imputer fitted on all data before the splitHeld-out rows shape the statisticsFit on train only; use a Pipeline
Tuning on the test setKnowledge of the test set leaks into the modelChoose on validation; test once
Rows of one patient or user on both sidesThe model recognises the entity, not the patternGroup k-fold
Random split of time-ordered dataTraining on the futureForward-chaining split
  • Reporting the best cross-validation score as the final estimate is the same trap: you picked it because it was best.

Source1 Cross-validation: evaluating estimator performance

Check yourself

Check: the test-set mistake

You tried 20 settings and quote the best test score. Why is the number too good, and what do you change?

Answer

Picking the maximum of 20 noisy scores favours luck, and each look at the test set leaked information into your choice. Choose on validation data (or with cross-validation on the training data) and use the test set once, for the chosen model.

Concept

Two ways to be wrong

  • Bias: systematic error from a model too simple for the pattern. A line fitted to a curve is wrong in the same way on every sample.
  • Variance: sensitivity to the particular training sample. A flexible model fitted to noise changes a lot from sample to sample.
  • Noise: error in the labels themselves. No model removes it.

Reading the numbers: low scores on both train and validation means underfitting. A high train score with a low validation score means overfitting.

Source2 Validation curves: plotting scores to evaluate models

Math

The decomposition

E[(y−f^(x))2]=Bias[f^(x)]2+Var[f^(x)]+σ2\mathbb{E}\big[(y-\hat f(x))^2\big] = \mathrm{Bias}[\hat f(x)]^2 + \mathrm{Var}[\hat f(x)] + \sigma^2
TermMeaning
Bias2\mathrm{Bias}^2Systematic error from a too-simple model
Var\mathrm{Var}Sensitivity to the training sample
σ2\sigma^2Irreducible label noise: the floor under every error
  • This is for squared error. The noise term is why a good model can still have error well above zero.

Source3 The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd edition)

Worked example

Worked example: a degree sweep

Data: y=sin⁡(2πx)y = \sin(2\pi x) plus noise with standard deviation 0.3, so the noise floor is 0.32=0.090.3^2 = 0.09. 15 training points spread over [0,1][0,1], 18 validation points, polynomial fits solved in exact fractions.

DegreeTrain MSEValidation MSEReading
10.3260.372Bias: both about four times the floor
30.0810.121Best validation error, near the floor
50.0560.215Validation has started to climb
90.0250.811Variance
120.01517.593Variance, extreme
  • Train error never rises as flexibility grows. Validation error falls to a minimum at degree 3, then climbs.
  • Any fitted model has training error a little below the floor (training optimism), so compare validation error with the floor.
  • Over 100 seeds, degree 3 beat degree 1 in 98 and degree 12 lost to degree 3 in 96. The script is in the lesson.

Sources4 Underfitting vs. Overfitting3 The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd edition)

Worked example

Learning curves: will more data help?

60 shuffled training points (the first nn each time), 200 validation points.

ModelTrain sizeTrain MSEValidation MSE
Degree 1150.3130.291
Degree 1300.3110.309
Degree 1600.3060.287
Degree 9150.0590.219
Degree 9300.0960.112
Degree 9600.0950.087
  • The line’s curves sit near 0.3, over three times the noise floor, and do not move as data quadruples: bias. More data will not help.
  • The degree-9 curves start apart and converge as data grows: variance. More data helps, and so does regularization.

Source2 Validation curves: plotting scores to evaluate models

Diagram

Diagnose, then fix

Diagram: High training error means bias, so add capacity or features.

yes

no

yes

no

Compare train and validation error

Train error high?

High bias, underfit
bigger model, better features,
train longer, less regularization

Validation much higher
than train?

High variance, overfit
more data, regularize, simpler model,
early stopping, augmentation

Good fit
check the test set once

Diagram summary: High training error means bias, so add capacity or features. Low training error with a big validation gap means variance, so add data or regularization. Both low and close means a good fit, so check the test set once. “High” is judged against a baseline or the noise floor.

Check yourself

Check: diagnose it

Train error 2%, validation error 25%. What is the diagnosis, what do you rule out first, and what fixes follow?

Answer

High variance. First rule out a leak or a validation set that does not look like production. Then add data, regularize, simplify the model, use early stopping or augmentation. A bigger model would make it worse.

Concept

Regularization: charge for large weights

  • Large weights let a curve wiggle through every point. A penalty makes that expensive.
  • L2 (ridge): add λ∥w∥22\lambda\lVert w\rVert_2^2. Shrinks all weights smoothly. Closed form (X⊤X+λI)−1X⊤y(X^{\top}X + \lambda I)^{-1}X^{\top}y also tames collinear features.
  • L1 (lasso): add λ∥w∥1\lambda\lVert w\rVert_1. Sets some weights to exactly zero, so it selects features.
  • Regularization trades a little bias for less variance.

Standardize first. The penalty sums weight sizes, and weight sizes depend on units. Fit the scaler on train only.

Source5 Linear Models (ridge regression and lasso)

Worked example

Worked example: why only L1 reaches zero

One feature, no intercept: x=[1,2,3]x = [1,2,3], y=[2,4,5]y = [2,4,5], so ∑xy=25\sum xy = 25 and ∑x2=14\sum x^2 = 14.

wridge=∑xy∑x2+λwlasso=max⁡ ⁣(∑xy−λ,  0)∑x2w_{\text{ridge}} = \frac{\sum xy}{\sum x^2 + \lambda} \qquad w_{\text{lasso}} = \frac{\max\!\big(\sum xy - \lambda,\; 0\big)}{\sum x^2}
λ\lambdaRidge wwLasso ww
01.7861.786
71.1901.286
140.8930.786
250.6410.000
1400.1620.000
  • Ridge divides by a larger number: shrinks in proportion, never arrives.
  • Lasso subtracts a constant: exactly zero once λ≥25\lambda \ge 25.
  • Geometry: the L1 diamond has corners on the axes; the L2 disc has none.

Sources5 Linear Models (ridge regression and lasso)6 Regression Shrinkage and Selection Via the Lasso

Compare

Lambda is a trade, and L1 versus L2

L2 (ridge)L1 (lasso)
EffectShrinks all weights smoothlySome weights exactly 0
Bayesian readingGaussian priorLaplace prior (lasso is the posterior mode)
Best whenMany correlated featuresYou want a sparse model
WeaknessKeeps every featurePicks one of a correlated group arbitrarily
  • On the three-point example, the unregularized fit has training MSE 0.119. Ridge at λ=14\lambda = 14 gives 3.839: that is the price paid in bias.
  • Too little λ\lambda leaves variance. Too much underfits. On the degree-12 sweep, validation error went 17.593, 0.326, 0.181, 0.220, 0.506 as λ\lambda grew; training error rose every step. Choose λ\lambda at the validation minimum.
  • Library scales differ: Ridge and Lasso in scikit-learn normalise their objectives differently, so the same alpha is not the same strength.

Sources5 Linear Models (ridge regression and lasso)6 Regression Shrinkage and Selection Via the Lasso7 The Bayesian Lasso

Code

The sweep in code

Python

from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge

# Xtr, ytr: the training rows and labels (a 2-D array and a 1-D array)
model = make_pipeline(PolynomialFeatures(12), StandardScaler(), Ridge(alpha=0.1))
model.fit(Xtr, ytr)   # the scaler is fitted on the training rows only
  • A Pipeline keeps preprocessing inside the fit, so inside cross-validation it is refitted on each training fold and no held-out rows leak in.
  • At degree 12, raising alpha should shrink the train-validation gap.
  • At degree 1, raising alpha will not help: that model has a bias problem.
  • The lesson’s own script uses exact fractions instead, so it needs no installs.

Check yourself

Check: raise lambda and watch

Lambda is made very large. What do the ridge and the lasso weights look like, and what does the model do to the data?

Answer

Ridge weights become tiny but stay nonzero. Lasso weights become exactly zero once lambda passes a threshold (25 in the lesson’s example). Either way the model underfits: it ignores the data, so training and validation error both rise.

Summary

Recap

  • Learning minimises empirical risk as a proxy for expected risk on unseen data.
  • Train fits, validation chooses, test judges once. Fit every scaler on the training fold only.
  • Error is bias squared plus variance plus noise. High train error is bias; a big validation gap is variance. Learning curves show whether more data helps.
  • L2 shrinks weights in proportion; L1 subtracts a constant and reaches exact zeros. Lambda trades variance for bias, and you choose it on validation data.
  • Common mistakes: tuning on the test set, scaling before the split, and assuming more data fixes bias.

References

References & Sources (1 of 2)

  1. Cross-validation: evaluating estimator performance (opens in a new tab)

    scikit-learn2026Documentation

    Used for Hold out a test set; tuning on the test set leaks knowledge into the model; preprocessing must be learned from the training set only, and a Pipeline does this inside each fold.

  2. Validation curves: plotting scores to evaluate models (opens in a new tab)

    scikit-learn2026Documentation

    Used for Bias and variance defined for estimators; low train and validation score means underfitting, high train and low validation score means overfitting; reading learning curves and when more training data helps.

  3. The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd edition) (opens in a new tab)

    Trevor Hastie, Robert Tibshirani, Jerome Friedman2009Book

    Used for The bias-variance decomposition of expected squared error (chapter 7) and the optimism of the training error, meaning training error is typically below test error (section 7.4).

  4. Underfitting vs. Overfitting (opens in a new tab)

    scikit-learn2026Documentation

    Used for Polynomial degrees 1, 4 and 15 fitted to a noisy cosine illustrate underfitting, a good fit and overfitting.

  5. Linear Models (ridge regression and lasso) (opens in a new tab)

    scikit-learn2026Documentation

    Used for Ridge objective and shrinkage, collinearity making least squares high-variance, lasso setting coefficients exactly to zero, elastic net helping with correlated features (lasso is likely to pick one of them at random), and the different scaling of the Ridge and Lasso objectives.

References

References & Sources (2 of 2)

  1. Regression Shrinkage and Selection Via the Lasso (opens in a new tab)

    Robert Tibshirani1996Journal of the Royal Statistical Society: Series B (Methodological), 58(1), 267-288Paper

    Used for The lasso constrains the sum of absolute coefficients, which tends to produce some coefficients that are exactly 0; the lasso can be read as a posterior mode under Laplace priors (as restated by Park and Casella).

  2. The Bayesian Lasso (opens in a new tab)

    Trevor Park, George Casella2008Journal of the American Statistical Association, 103(482)Paper

    Used for Tibshirani (1996) suggested that lasso estimates can be interpreted as posterior mode estimates when the regression parameters have independent, identical Laplace (double-exponential) priors.