AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
∿Classical Machine Learning
  1. Linear regression
  2. Gradient descent
  3. Classification: logistic regression, kNN, SVM
  4. Decision trees and ensembles
  5. Clustering and PCA
  6. Overfitting and the bias-variance trade-off
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Classical Machine Learning

Overfitting and the bias-variance trade-off

The central problem of machine learning: generalising to new data. Underfitting vs overfitting, the bias-variance decomposition, how model capacity, data size, noise and regularisation interact — explored with a live polynomial-fitting lab.

Intermediate~24 min·6 references
Key terms
OverfittingUnderfittingBias-variance trade-offRegularisationValidation setCross-validationLearning curveEarly stopping

The goal of machine learning is not to do well on the training data — it is to do well on data the model has never seen. This ability is called generalisation, and almost every technique in the field (validation sets, regularisation, dropout, early stopping, data augmentation) exists to protect it. This lesson builds the mental model behind all of them[1][2].

≈
Memorising vs understanding
Student A memorises the answers to last year's exam and scores 100% on it — then fails this year's exam because the questions changed. That is [[overfitting]]. Student B only learned ‘the answer is usually C’ and does poorly on both. That is [[underfitting]]. Student C learned the underlying ideas and does well on both: good generalisation.

Underfitting vs overfitting

UnderfittingGood fitOverfitting
Training errorhighlowvery low (≈ 0)
Validation errorhighlow, close to traininghigh — big gap to training
Causemodel too simple, too much regularisation, too little training—model too flexible for the amount of data, noise memorised
Fixesmore capacity, better features, less regularisation, train longer—more data, regularisation, simpler model, early stopping, augmentation

The bias-variance decomposition

Imagine re-collecting the training set many times and refitting the model each time. For a squared-error loss, the expected error on a new point splits exactly into three parts[1][3]:

E[(y − f̂(x))²] = Bias[f̂(x)]² + Var[f̂(x)] + σ²
Bias² = how far the average model is from the truth. Variance = how much the model jumps around between training sets. σ² = irreducible noise in the labels.
In words: “expected test error = (systematic miss)² + (instability) + (noise you can never remove)”. Bias is how far the average model, over many possible training sets, is from the truth; variance is how much individual models scatter around that average. Simple models tend to have high bias, flexible models high variance — the Bias-variance trade-off trade-off.
Symbols(hover a symbol in the formula)
E
expected value: the average over many possible training sets (and noise draws)
y
the true (noisy) target at a test point x
f̂(x)
“f-hat of x”: the trained model's prediction; it changes with the training set
²
squared (squared-error loss)
Bias
average prediction minus the true function value: a systematic error (Underfitting)
Var
variance: how much f̂(x) jumps between training sets (Overfitting)
σ²
irreducible noise variance in the labels — no model can beat it
▸Worked example
True value at x: 10, label noise σ² = 1 Four training sets give predictions f̂ = 11, 13, 12, 12 average = 12 → Bias = 12 − 10 = 2 → Bias² = 4 Var = ((−1)² + 1² + 0² + 0²) / 4 = 0.5 expected error = 4 + 0.5 + 1 = 5.5 Direct check: ((10−11)² + (10−13)² + (10−12)² + (10−12)²)/4 + 1 = 18/4 + 1 = 5.5 ✓
  • High bias (underfitting): the model family is too rigid to represent the truth — a straight line for a curved relationship. More data does not fix it.
  • High variance (overfitting): the model is so flexible that it fits the noise of this particular sample; a different sample would give a very different model. More data, regularisation or averaging fixes it.
  • Noise σ²: measurement errors and unobserved factors. No model can go below it — if your validation error is already near σ², stop tuning.
≈
The dartboard picture
Each training set gives one dart throw. High bias, low variance: a tight cluster of darts, but off-centre. Low bias, high variance: darts scattered all around the bullseye — right on average, wrong each time. The goal is a tight cluster on the bullseye; making the model more flexible moves you from the first picture toward the second.

As model capacity grows, bias falls and variance rises. Training error keeps decreasing, but validation error traces a U-shape: it falls while bias shrinks, bottoms out, then climbs as variance takes over. The sweet spot is the bottom of the U — and you can only find it by measuring on data the model did not train on[6].

Loading interactive…
Fit polynomials of degree 1–15 to noisy samples of a smooth curve. The chart shows train and test error for every degree; the current degree is marked.
  • Degree 1: a straight line misses the curve — both train and test error are high (underfitting / high bias).
  • Degree 3–5: the fit follows the true shape; test error is at or near its minimum.
  • Degree 12–15 with few points: the curve snakes through every training dot (train error ≈ 0) and swings wildly between them — test error explodes (overfitting / high variance).
  • Now raise the sample count: the high-degree curve calms down and the U-curve flattens. More data is the most reliable cure for variance.
  • Raise the noise: the best degree shifts lower — with noisier data, simpler models win.
  • Keep degree 15 and increase the L2 (ridge) slider: the wiggles shrink and test error drops, without changing the degree. Too much L2 and it underfits again.
knobpolynomial degree (model capacity)
What it is
The highest power of x in the model ŷ = w₀ + w₁x + … + w_d·x^d — a stand-in for model capacity in general (tree depth, number of layers/neurons, number of features).
↑ If you increase it
Lower bias, higher variance: training error always falls; test error falls then rises once the model starts fitting noise.
↓ If you decrease it
Higher bias, lower variance: a smoother, more stable model that may miss real structure.
Typical values
Choose by validation error or cross-validation, never by training error.
knobtraining set size (n)
What it is
How many labelled examples the model learns from.
↑ If you increase it
Variance drops: flexible models overfit less and the train-test gap shrinks. Does not reduce bias — a too-simple model stays too simple.
↓ If you decrease it
Variance grows; only simple or strongly regularised models remain safe.
Typical values
Plot a learning curve (score vs n): if validation error is still falling, more data will help; if it has plateaued with a gap near zero, you need a better model instead.
knobL2 strength λ (ridge)
What it is
Weight of the penalty λ·Σw² added to the loss, discouraging large coefficients.
↑ If you increase it
Smoother function, lower variance, higher bias; with very large λ the model flattens and underfits.
↓ If you decrease it
Model uses its full flexibility; with high capacity and little data, it overfits.
Typical values
Search a log grid (10⁻⁶ … 10²) with cross-validation; in neural networks the equivalent is weight decay, ~1e-4 to 1e-2.

How to fight overfitting

  • Get more (and more diverse) data — the most reliable fix; data augmentation fakes it for images and audio.
  • Reduce capacity: fewer features, shallower trees, lower polynomial degree, smaller networks.
  • [[regularization|Regularise]]: L2/L1 penalties, Dropout in neural nets, min_samples_leaf in trees.
  • [[early-stopping|Early stopping]]: stop iterative training when validation loss stops improving.
  • Ensembles: averaging many models (random forests, bagging) reduces variance.

Detecting it honestly

You can only see overfitting by comparing training performance with performance on held-out data. With small datasets, a single validation set is noisy, so use k-fold [[cross-validation]]: split the data into k folds, train on k − 1 and validate on the remaining one, rotate, and average the k scores. validation_curve (score vs a hyperparameter) and learning_curve (score vs training size) in scikit-learn plot exactly the diagnostics of this lesson[4].

CV score = (1/k) · Σⱼ score(model trained without fold j, evaluated on fold j)
In words: “split the data into k parts; k times, train on all parts but one and test on the part left out; average the k test scores”. Every example is used for validation exactly once, so the estimate is less noisy than a single Validation set split. The spread of the k scores tells you how much to trust it.
Symbols(hover a symbol in the formula)
CV score
the Cross-validation estimate of how well the model generalises
(1/k)
average over the k folds (k is usually 5 or 10)
Σⱼ
sum over folds j = 1…k
score
any metric: Accuracy, R², −MSE, F1…
model trained without fold j
a fresh model fit on the other k − 1 folds
evaluated on fold j
tested on the held-out fold it never saw during training
▸Worked example
1,000 examples, k = 5 → 5 folds of 200 Fold j: 1 2 3 4 5 Train on: 800 examples each time (the other 4 folds) Accuracy: 0.82 0.85 0.80 0.88 0.85 CV score = (0.82 + 0.85 + 0.80 + 0.88 + 0.85) / 5 = 4.20 / 5 = 0.84 Std. dev. ≈ 0.028 → report 0.84 ± 0.03; a 0.01 gap between two models is within the noise.
python
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import validation_curve

rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(40, 1))
y = np.sin(3 * X[:, 0]) + rng.normal(0, 0.2, 40)     # smooth truth + noise

model = make_pipeline(PolynomialFeatures(include_bias=False),
                      StandardScaler(), Ridge(alpha=1e-6))  # almost no regularisation
degrees = np.arange(1, 16)
train_s, val_s = validation_curve(
    model, X, y,
    param_name="polynomialfeatures__degree", param_range=degrees,
    cv=5, scoring="neg_mean_squared_error")

for d, tr, va in zip(degrees, -train_s.mean(axis=1), -val_s.mean(axis=1)):
    print(f"degree {d:2d}   train MSE {tr:.3f}   val MSE {va:.3f}")
# Train MSE falls steadily; validation MSE is U-shaped.
# Re-run with Ridge(alpha=1.0) and watch the high-degree validation error drop.
The widget's experiment in scikit-learn: a validation curve over polynomial degree with 5-fold cross-validation.
!
Pitfalls
Tuning on the test set turns it into a validation set and makes your final number optimistic. Judging by training accuracy says nothing about generalisation. Tiny validation sets produce noisy scores — differences of 1% may be luck. [[data-leakage|Leakage]] can hide overfitting completely: the validation score looks great because it secretly saw the answers. Repeatedly tweaking until the validation score improves also overfits the validation set; keep a final untouched test set.
▸Go deeper: double descent and why huge neural networks still generalise

The bias-variance trade-off was formalised for neural networks by Geman, Bienenstock & Doursat (1992)[3]. Yet modern deep networks often have far more parameters than training examples, can fit random labels perfectly, and still generalise well. Belkin et al. (2019) showed a double descent curve: test error follows the classic U up to the point where the model can just interpolate the training data (the peak), then falls again as capacity keeps growing[5]. Implicit regularisation from gradient descent, architecture and data augmentation helps explain why. The U-curve is still the right intuition for classical models and small data — just not the whole story.

Quiz

1.
Training error 2%, validation error 25%. What is the diagnosis?
2.
Training error 30%, validation error 31%, and the task is known to be achievable at ~5%. What should you try?
3.
In the polynomial lab, you keep degree 15 and increase the number of training samples a lot. What happens to the test error?
4.
Which term of the bias-variance decomposition can no model reduce?
5.
You tried 200 hyperparameter settings and picked the one with the best score on the test set. What's wrong?
Score: 0/5

References

  1. [1]
    An Introduction to Statistical Learning (2nd ed.) — §2.2 Assessing Model Accuracy, Ch. 5 Resampling Methods
    BookJames, Witten, Hastie & Tibshirani2021statlearning.com
  2. [2]
    Deep Learning — Chapter 5: Machine Learning Basics (capacity, overfitting, underfitting)
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  3. [3]
    Neural Networks and the Bias/Variance Dilemma
    PaperGeman, Bienenstock & Doursat1992doi.org
  4. [4]
    scikit-learn User Guide — Validation curves: plotting scores to evaluate models
    Docsscikit-learn developersscikit-learn.org
  5. [5]
    Reconciling modern machine-learning practice and the classical bias–variance trade-off
    PaperBelkin, Hsu, Ma & Mandal2019arxiv.org
  6. [6]
    Machine Learning Crash Course — Overfitting
    CourseGoogledevelopers.google.com
← Previous
Clustering and PCA
Next → · Neural Networks
Neurons and Activation Functions