Intermediate: machine learning · Evaluating models · topic 31 of 62 · 30 min
Overfitting, underfitting and regularisation
Explanation
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.
| Situation | Training score | Validation score | What it means |
|---|---|---|---|
| Underfitting | Low | Low | Too simple; it misses real patterns |
| Good fit | High | Close to training | It learned patterns that carry over |
| Overfitting | Very high | Much lower | It memorised noise in the training data |
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).
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")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
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)
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).
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)².
Training accuracy 0.98, validation accuracy 0.74. Which change is MOST likely to help?
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Cross-validation and tuning hyperparametersEvaluating models · same module
- Thresholds, ROC-AUC and imbalanced classesEvaluating models · same module
- Training: loss, backpropagation and optimisersNeural networks and deep learning
- Decision treesk-NN, decision trees and ensembles
- Random forests and baggingk-NN, decision trees and ensembles
- Feature selection, leakage and pipelinesClustering, dimensionality reduction and feature engineering
Questions people ask about this
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.
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.
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.
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 more topic in “Evaluating models” before its exam: Cross-validation and tuning hyperparameters.
- Module 6 exam: Evaluating models · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, k-NN, decision trees and ensembles. 62 topics left in the course before the final exam.