Skip to content

Intermediate: machine learning · Evaluating models · topic 31 of 62 · 30 min

Overfitting, underfitting and regularisation

Explanation

Underfitting means the model is too simple to capture the pattern, so it does badly on training and test data. Overfitting means it memorised the training data, including noise, so it does well on training but badly on new data. Regularisation, more data, simpler models and early stopping help a model generalise.

The goal is generalisation

We do not care how well a model remembers its training data. We care how well it predicts new cases. That ability is called generalisation. Comparing the training score with the validation or test score is the quickest way to see whether a model generalises.

SituationTraining scoreValidation scoreWhat it means
UnderfittingLowLowToo simple; it misses real patterns
Good fitHighClose to trainingIt learned patterns that carry over
OverfittingVery highMuch lowerIt memorised noise in the training data
Think of it like this: A student who skims the book (underfitting) fails both the practice test and the real exam. A student who memorises the practice answers word for word (overfitting) scores 100% on practice but fails when questions are reworded. The student who understands the ideas does well on both.

Bias and variance in plain words

Bias is error from wrong assumptions, like fitting a straight line to a curve: the model is consistently off. Variance is error from being too sensitive to the particular training data: train on a slightly different sample and you get a very different model. Simple models tend to have high bias and low variance; very flexible models the reverse. The bias-variance trade-off is about finding the flexibility that minimises total error on new data.

How to fix underfitting

  • Use a more flexible model (for example, trees instead of a line).
  • Add better features that carry real signal.
  • Reduce regularisation, or train longer.

How to fix overfitting

  • Get more training data, the most reliable cure.
  • Use a simpler model or limit its complexity (for trees: max_depth, min_samples_leaf).
  • Remove noisy or useless features.
  • Regularise: add a penalty for large weights to the loss.
  • Early stopping: stop training when the validation score stops improving.
  • For neural networks: dropout and data augmentation (module 9).

Regularisation: L2 (Ridge) and L1 (Lasso)

Regularisation adds a penalty to the loss so the model prefers small weights. L2 regularisation (Ridge) adds the sum of squared weights; it shrinks all weights smoothly. L1 regularisation (Lasso) adds the sum of absolute weights; it pushes some weights to exactly zero, which also selects features. The strength is set by a hyperparameter, often called alpha (in Ridge and Lasso) or C (in LogisticRegression, where smaller C means stronger regularisation).

python
from sklearn.linear_model import Ridge, Lasso

ridge = Ridge(alpha=1.0).fit(X_train, y_train)   # shrinks all weights
lasso = Lasso(alpha=0.1).fit(X_train, y_train)   # sets some weights to 0
print((lasso.coef_ == 0).sum(), "features dropped by Lasso")
Shown only. Scale the features first so the penalty treats them fairly.

Learning curves

A learning curve plots training and validation scores as the training set grows. If both are low and close, you are underfitting and more data will not help much; you need a better model or features. If there is a big gap that shrinks as data grows, you are overfitting and more data will help.

Common mistakes

  • Celebrating a 100% training score. Fix: always compare with validation.
  • Fixing overfitting by tuning endlessly on the test set, which just overfits to the test set.
  • Regularising without scaling features first.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Overfitting, underfitting and regularisation · 1/7

Generalisation

The goal of a model is to predict new data well. That is called generalisation.

Prefer a video by a teacher? Find free videos on “overfitting underfitting bias variance tradeoff regularization ridge lasso” on YouTube ↗

In real life: A sales forecast that memorised Diwali

A retailer's very deep tree model predicted last year's daily sales almost perfectly, including the Diwali spike on one exact date. This year Diwali fell on a different date, and the model predicted a spike on the wrong day. Limiting tree depth and replacing the raw date with features like "days to Diwali" fixed it: the training score dropped slightly, and the forecast for new dates became far better.

Practice (0/3 done)

Task 1 · Code · Python

Write diagnose(train_score, val_score) using these rules, in this order: if train_score < 0.7 return "underfit"; else if train_score − val_score > 0.1 return "overfit"; otherwise return "good". Scores are between 0 and 1 (higher is better).

Task 2 · Code · Python

Write ridge_loss(actual, predicted, weights, alpha) = MSE + alpha × Σ w² (the Ridge loss), rounded to 4 decimal places. MSE is the mean of (actual − predicted)².

Task 3 · Question

Training accuracy 0.98, validation accuracy 0.74. Which change is MOST likely to help?

Quick quiz

Question 1

1.A model scores 0.60 on training and 0.58 on validation for a task where 0.90 is achievable. It is…

Question 2

2.Which method can set some weights to exactly zero?

Question 3

3.What is the most reliable cure for overfitting when it is possible?

Question 4

4.High variance means…

Question 5

5.What is early stopping?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

A model scores 0.60 on training and 0.58 on validation for a task where 0.90 is achievable. It is…

Answer: Underfitting

Low scores on both mean the model is too simple or lacks good features.

Which method can set some weights to exactly zero?

Answer: Lasso (L1)

The L1 penalty pushes small weights all the way to zero.

What is the most reliable cure for overfitting when it is possible?

Answer: More good training data

More examples make memorising noise harder and real patterns clearer.

High variance means…

Answer: The model changes a lot when trained on a slightly different sample

Variance is sensitivity to the particular training data.

What is early stopping?

Answer: Stopping training when the validation score stops improving

It prevents the model from continuing to fit noise.

Training loss keeps falling but validation loss starts rising. What is happening?Related

Answer: Overfitting

The network is memorising the training data; consider early stopping.

From Training: loss, backpropagation and optimisers

A model scores 99.8% on the test set for a hard real-world task. What should you do first?Related

Answer: Look for leakage

Scores that are too good usually mean the answer leaked into the features.

From Train, validation and test sets

A model trained on flats of 400–1,500 sq ft predicts a 9,000 sq ft villa. What is the risk?Related

Answer: Extrapolation: the line may not hold far outside the training range

Patterns learned in one range may not continue outside it.

From Linear regression and least squares

In 5-fold cross-validation, how many times is the model trained?Related

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Evaluating models” before its exam: Cross-validation and tuning hyperparameters.
  2. Module 6 exam: Evaluating models · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
  3. Then the next module, k-NN, decision trees and ensembles. 62 topics left in the course before the final exam.

← Previous: Regression metrics: MAE, MSE, RMSE and R²