Slides · ML foundations
The learning problem: generalization, bias-variance and regularization
1 / 24
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:
- Frame a task as supervised learning and explain empirical risk.
- Use train, validation and test sets and spot leaks.
- Diagnose bias versus variance from error and learning curves.
- Explain what L1 and L2 penalties do and why lambda is a trade.
Concept
Supervised learning in one picture
- You have examples (xi,yi): inputs and the answers you want.
- You pick a model family fθ and search for parameters θ.
- 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θminn1i=1∑nℓ(fθ(xi),yi)+λR(θ)| Symbol | Meaning |
|---|---|
| n | Number of training examples |
| ℓ | Loss for one prediction |
| R(θ) | Penalty on complexity |
| λ | Penalty 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 λ, are chosen on validation data.
Diagram
The pipeline and where it breaks
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
- Train fits the parameters.
- Validation chooses hyperparameters and compares models. Every look leaks a little.
- 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.
Source[1] Cross-validation: evaluating estimator performance
Diagram
One dataset, three disjoint parts
Compare
Leaks that inflate a score
| Leak | Why it inflates the score | Fix |
|---|---|---|
| Scaler or imputer fitted on all data before the split | Held-out rows shape the statistics | Fit on train only; use a Pipeline |
| Tuning on the test set | Knowledge of the test set leaks into the model | Choose on validation; test once |
| Rows of one patient or user on both sides | The model recognises the entity, not the pattern | Group k-fold |
| Random split of time-ordered data | Training on the future | Forward-chaining split |
- Reporting the best cross-validation score as the final estimate is the same trap: you picked it because it was best.
Source[1] 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.
Source[2] Validation curves: plotting scores to evaluate models
Math
The decomposition
E[(y−f^(x))2]=Bias[f^(x)]2+Var[f^(x)]+σ2| Term | Meaning |
|---|---|
| Bias2 | Systematic error from a too-simple model |
| Var | Sensitivity to the training sample |
| σ2 | Irreducible 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.
Source[3] The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd edition)
Worked example
Worked example: a degree sweep
Data: y=sin(2πx) plus noise with standard deviation 0.3, so the noise floor is 0.32=0.09. 15 training points spread over [0,1], 18 validation points, polynomial fits solved in exact fractions.
| Degree | Train MSE | Validation MSE | Reading |
|---|---|---|---|
| 1 | 0.326 | 0.372 | Bias: both about four times the floor |
| 3 | 0.081 | 0.121 | Best validation error, near the floor |
| 5 | 0.056 | 0.215 | Validation has started to climb |
| 9 | 0.025 | 0.811 | Variance |
| 12 | 0.015 | 17.593 | Variance, 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.
Sources[4] Underfitting vs. Overfitting[3] 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 n each time), 200 validation points.
| 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 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.
Source[2] Validation curves: plotting scores to evaluate models
Diagram
Diagnose, then fix
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. Shrinks all weights smoothly. Closed form (X⊤X+λI)−1X⊤y also tames collinear features.
- L1 (lasso): add λ∥w∥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.
Worked example
Worked example: why only L1 reaches zero
One feature, no intercept: x=[1,2,3], y=[2,4,5], so ∑xy=25 and ∑x2=14.
wridge=∑x2+λ∑xywlasso=∑x2max(∑xy−λ,0)| λ | Ridge w | Lasso w |
|---|---|---|
| 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 |
- Ridge divides by a larger number: shrinks in proportion, never arrives.
- Lasso subtracts a constant: exactly zero once λ≥25.
- Geometry: the L1 diamond has corners on the axes; the L2 disc has none.
Sources[5] 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) | |
|---|---|---|
| Effect | Shrinks all weights smoothly | Some weights exactly 0 |
| Bayesian reading | Gaussian prior | Laplace prior (lasso is the posterior mode) |
| Best when | Many correlated features | You want a sparse model |
| Weakness | Keeps every feature | Picks one of a correlated group arbitrarily |
- On the three-point example, the unregularized fit has training MSE 0.119. Ridge at λ=14 gives 3.839: that is the price paid in bias.
- Too little λ leaves variance. Too much underfits. On the degree-12 sweep, validation error went 17.593, 0.326, 0.181, 0.220, 0.506 as λ grew; training error rose every step. Choose λ at the validation minimum.
- Library scales differ:
RidgeandLassoin scikit-learn normalise their objectives differently, so the samealphais not the same strength.
Sources[5] Linear Models (ridge regression and lasso)[6] Regression Shrinkage and Selection Via the Lasso[7] 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
alphashould shrink the train-validation gap. - At degree 1, raising
alphawill 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)
Cross-validation: evaluating estimator performance (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/cross_validation.html
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.
Validation curves: plotting scores to evaluate models (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/learning_curve.html
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.
Trevor Hastie, Robert Tibshirani, Jerome Friedman2009Book
https://hastie.su.domains/ElemStatLearn/
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).
Underfitting vs. Overfitting (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/auto_examples/model_selection/plot_underfitting_overfitting.html
Used for Polynomial degrees 1, 4 and 15 fitted to a noisy cosine illustrate underfitting, a good fit and overfitting.
Linear Models (ridge regression and lasso) (opens in a new tab)
scikit-learn2026Documentation
https://scikit-learn.org/stable/modules/linear_model.html
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)
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
https://academic.oup.com/jrsssb/article/58/1/267/7027929
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).
The Bayesian Lasso (opens in a new tab)
Trevor Park, George Casella2008Journal of the American Statistical Association, 103(482)Paper
https://hedibert.org/wp-content/uploads/2018/05/park-casella-2008.pdf
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.
Keys: ← → move, Home End first and last, F full screen.