Find a course

Module 4: Generalization: Overfitting, Regularization and ValidationLesson 8 of 1115 min

The Bias-Variance Trade-off and Regularization

Diagnose underfitting and overfitting with learning curves, understand bias and variance, and use L1 and L2 regularization to tame complex models.

Step 1 of 12Learn

Two ways to be wrong

Three students fit models to the same noisy data about how study hours relate to exam scores.

  • Student A fits a flat line: "everyone scores 72." Training error is high; test error is just as high. The model is too simple.
  • Student B fits a gently curving line that follows the overall trend. Training error is moderate; test error is about the same.
  • Student C fits a wildly wiggly curve that passes exactly through every training point. Training error is zero; test error is terrible.

A is underfitting, C is overfitting, and B has found the sweet spot.

These map onto two sources of error:

Bias is error from overly simple assumptions. A high-bias model misses real structure no matter how much data you give it: a straight line can never capture a curve. Signs: high training error and high validation error.

Variance is error from sensitivity to the specific training sample. A high-variance model would change dramatically if trained on a different random sample of the same population, because it fits noise. Signs: low training error but much higher validation error.

There is also irreducible error: noise in the data itself, such as a student who was sick on exam day. No model can remove it.

The bias-variance trade-off: as model complexity grows, bias tends to fall and variance tends to rise. Total error is often U-shaped in complexity, and the goal is to find the bottom of the U. (Very large modern neural networks can behave in more surprising ways, but the trade-off remains the right mental model for most practical work.)

Step 2 of 12Compare

Three students, three fits

AspectStudent AStudent BStudent C
ModelFlat lineGentle curveWiggly curve
Training errorHighModerateZero
Test errorHighModerateVery high
DiagnosisUnderfitting: high biasGood balanceOverfitting: high variance

Step 3 of 12Explore

An illustrative bias-variance curve

This is a stylized model, not real data. Bias² falls as complexity x rises (a/x), variance rises with complexity (c·x), and noise n is constant. The curve shows total expected error. Change how strongly each component grows and watch where the best complexity lands.

010203040 51015
Best complexity √(a/c)
4
Lowest total error 2√(ac) + n
10

Step 4 of 12Practice · Sort into groups

Each line describes a model's training and validation error. Diagnose it.

Tap an item, then tap its group (or drag it there).

Step 5 of 12Learn

Diagnosing with learning curves

A learning curve plots training and validation error against the number of training examples. It tells you which fix is worth your time.

High bias pattern. Both curves flatten out quickly at a high error, close together. Adding more data won't help, because the model can't represent the pattern even with infinite examples. Fixes:

  • Use a more flexible model (more features, polynomial terms, deeper trees, a bigger network).
  • Engineer better features.
  • Reduce regularization.

High variance pattern. Training error is low, validation error is much higher, and the gap narrows slowly as data grows. More data is likely to help. Fixes:

  • Collect more training data, or use data augmentation (for images: flips, crops, small rotations).
  • Simplify the model or select fewer features.
  • Increase regularization.
  • Use ensembles, such as bagging.
  • Use early stopping for iterative training: stop when validation error starts rising.

This diagnosis saves enormous effort. Teams have spent months collecting more data for a high-bias model that could never use it, and others have kept adding model complexity to a high-variance model that needed more data or constraints.

A related tool is the validation curve: plot training and validation error against a single hyperparameter, such as tree depth or polynomial degree. Training error keeps falling as complexity rises, while validation error falls and then rises. The bottom of the validation curve marks a good setting.

Step 6 of 12Practice · Chart

A high-variance learning curve

Tap the training size where the gap between the curves is widest.

Tap the point that answers the question, then press Check.

A high-variance learning curveLine chart with 5 categories: 100: Training error 2%, Validation error 30%; 500: Training error 3%, Validation error 24%; 1,000: Training error 4%, Validation error 19%; 2,000: Training error 5%, Validation error 16%; 5,000: Training error 6%, Validation error 14%.0%10%20%30%Error1005001,0002,0005,000Training examples
Illustrative.
A high-variance learning curve
Training examplesTraining errorValidation error
1002%30%
5003%24%
1,0004%19%
2,0005%16%
5,0006%14%

Step 7 of 12Practice · What would you do?

What would you do?

Your image classifier has 1% training error and 20% validation error. You have a limited budget. Which plan is most likely to help?

Step 8 of 12Learn

Regularization: paying a price for complexity

Regularization adds a penalty for complexity to the loss, so the model must justify large weights with real improvements in fit:

Total loss = data loss + λ × penalty

λ (lambda) is a hyperparameter controlling the strength. λ = 0 means no regularization; a very large λ forces weights toward zero and the model toward underfitting.

L2 regularization (ridge regression; called weight decay in neural networks) penalizes the sum of squared weights: λ × Σ wᵢ². It shrinks all weights smoothly toward zero but rarely makes them exactly zero. It is especially helpful when features are correlated, because it spreads weight among them instead of letting a pair grow huge with opposite signs.

L1 regularization (lasso) penalizes the sum of absolute weights: λ × Σ |wᵢ|. Its geometry pushes many weights to exactly zero, so it performs automatic feature selection. With 500 candidate features, lasso might keep 30.

Elastic net combines both penalties.

Example: weights w = (3, −4) and λ = 0.1. The L2 penalty is 0.1 × (9 + 16) = 2.5. The L1 penalty is 0.1 × (3 + 4) = 0.7.

Two practical notes:

  • Scale features first. Penalties compare weights directly, so a feature measured in thousands would be unfairly penalized less than one measured in fractions.
  • The bias term b is usually not penalized.

Other regularization methods include dropout in neural networks (randomly switching off neurons during training), early stopping, limiting tree depth, and data augmentation. They all share the same goal: reduce variance at a small cost in bias.

Step 9 of 12Compare

L1 vs. L2 regularization

AspectL1 (lasso)L2 (ridge, weight decay)
Penaltyλ × sum of |w|λ × sum of w²
Effect on weightsSets some exactly to zeroShrinks all smoothly
Feature selectionYes, built inNo
Correlated featuresTends to pick oneSpreads weight among them

Step 10 of 12Practice · Code challenge

Write l2Penalty(weights, lambda) that returns the L2 regularization penalty: lambda times the sum of the squared weights.

Runs in a sandbox in your browser.
  • l2Penalty([1, 2], 0.5)
  • l2Penalty([3, -4], 1)
  • l2Penalty([], 2)
  • l2Penalty([2, 2, 2, 2], 0.25)

Step 11 of 12Practice · True or false

L1 regularization (lasso) tends to set some weights exactly to zero, effectively removing those features from the model.

Step 12 of 12Practice · Choose one

You increase the regularization strength λ from 0.01 to 100 in a linear model. Training and validation errors both rise sharply. What happened?