Overfitting and generalisation
About this lesson
A model is only useful if it generalises: if it predicts well on data it has never seen. Fit six students' quiz scores with a straight line, then with a degree-5 curve that hits every point exactly, and watch five held-back students expose the curve. Training error keeps falling as a model gets more flexible; test error falls, then rises. Learn to spot overfitting and underfitting, why a validation set picks the model, and what more data does.
Six students, six points
A tutor records six students: hours studied (0 to 5) and quiz score out of 10. These points are the training data. The real goal is to predict the score of a new student the model has never seen.
training data (hours studied, quiz score) 0 2.5 1 3 2 5.5 3 6 4 8.5 5 9 goal: predict scores for NEW students, not just describe these six
Read the lesson step by step
Six students, six points
A tutor records six students: hours studied (0 to 5) and quiz score out of 10. These points are the training data. The real goal is to predict the score of a new student the model has never seen.
training data (hours studied, quiz score) 0 2.5 1 3 2 5.5 3 6 4 8.5 5 9 goal: predict scores for NEW students, not just describe these sixFit a straight line
Fit a degree-1 polynomial, a straight line. np.polyfit(x, y, 1) picks the line with the smallest squared error. The degree sets the model's capacity: how much its curve is allowed to bend.
w = np.polyfit(x, y, 1) w -> [1.414, 2.214] score = 1.414 * hours + 2.214 degree 1: 2 numbers to learn, no bendsMeasure the training error
How wrong is it? For each training point, take prediction minus true score, square it, and average. That is the mean squared error (MSE). The line misses every point a little: training MSE 0.23.
err = np.polyval(w, x) - y -> [-0.29, 0.63, -0.46, 0.46, -0.63, 0.29] mse = np.mean(err ** 2) -> 0.2286 (shown as 0.23)A degree-5 curve
Now allow degree 5. Six coefficients can pass through six points exactly, so the curve threads every training point. Training MSE drops to 0.00. Judged on its training data, this model looks perfect.
w = np.polyfit(x, y, 5) 6 numbers to learn, 6 points to hit: one curve passes through all of them degree 1 train MSE 0.23 degree 5 train MSE 0.00New students: the test set
Five more students were held back from training: the test set. Between the points it memorised, the wiggly curve swings up and down and misses them. Its test MSE is 0.93, against 0.26 for the straight line.
test data (never used for training) 0.5 3.25 curve says 1.50 1.5 3.75 curve says 4.62 2.5 6.25 curve says 5.75 3.5 6.75 curve says 6.87 4.5 9.25 curve says 10.00 test MSE degree 5: 0.93 degree 1: 0.26That is overfitting
This is overfitting: the curve fitted the noise in six examples, not the trend behind them. Training error low, test error high. The line generalises: about as good on new students (0.26) as on old ones (0.23).
train MSE test MSE degree 1 0.23 0.26 generalises degree 5 0.00 0.93 overfits a decision tree grown until every leaf holds one example memorises its data the same wayToo simple: underfitting
Go the other way. Degree 0 is a flat line at the average score, 5.75. It cannot follow the trend at all, so both errors are high: training 6.06, test 4.75. That is underfitting.
w = np.polyfit(x, y, 0) w -> [5.75] (the mean score) train MSE 6.06 test MSE 4.75 too little capacity: misses the trend itselfError against complexity
Side by side: as the degree rises, training error only falls: 6.06, 0.23, 0.00. Test error falls, then rises again: 4.75, 0.26, 0.93. Choose the degree where test error is lowest, not training error.
degree train MSE test MSE 0 6.06 4.75 1 0.23 0.26 2 0.23 0.26 3 0.17 0.27 4 0.17 0.27 5 0.00 0.93 training error never rises; test error is U-shapedPick with held-out data
Using the mint test points to choose the degree turns them into a validation set. Keep one more set locked away and measure it once, at the end, for an honest score. Cross-validation takes turns holding out each part.
training set fit the coefficients validation set choose the degree test set measure once, at the very end k-fold cross-validation: split into k parts, hold out each part in turn, average the errorsMore data calms it
More data helps. Fit the same degree-5 curve to all 11 points: it can no longer pass through every one, and it stays within 0.6 of the green straight line (before: 1.4). Other cures: a simpler model, regularisation, early stopping.
w = np.polyfit(x_all, y_all, 5) # 11 points train MSE 0.17 (no held-out data left) furthest from the line: 0.57 (was 1.42) regularisation: penalise large coefficients early stopping: stop training when the validation error starts to rise
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A model scores almost perfectly on its training data but badly on new data. What is happening?
Low training error with high test error is the signature of overfitting: the model learned the noise in its examples, not the pattern behind them.
02In the figure, degree 0 has training MSE 6.06 and test MSE 4.75. What does that show?
A flat line cannot follow a rising trend. Both errors are high, which is underfitting. Close errors only mean a good fit when they are also low.
03Why does the degree-5 curve reach a training MSE of 0.00 on six points?
With as many coefficients as points, the curve can thread every point exactly. Zero training error then says nothing about new data.
04You try degrees 0 to 5 and pick the one with the lowest error on held-out data. What should you report as the final score?
Data used to choose the model is a validation set; its error is now optimistic. An honest final score comes from a test set the choice never saw.
05Which of these does NOT help against overfitting?
A higher degree means more capacity, which makes overfitting more likely. More data, regularisation and early stopping all help.
Glossary
- Generalisation
- How well a model does on new data it was not trained on. It is the real goal of learning.
- Overfitting
- Fitting the noise and quirks of the training data so closely that the model does worse on new data: low training error, high test error.
- Underfitting
- A model too simple to capture the pattern: training and test error are both high.
- Capacity
- How flexible a model is, how many different shapes it can fit. Here, the degree of the polynomial.
- Mean squared error (MSE)
- The average of (prediction − true value)² over a set of examples. Lower is better.
- Training, validation and test sets
- Data to fit the model; held-out data to choose between models (such as the degree); held-out data measured once at the end for an honest score.
- Cross-validation
- Split the data into k parts, hold out each part in turn, and average the k held-out errors to choose a model.
- Regularisation
- Any change that discourages a model from fitting noise, for example adding a penalty for large coefficients to the error being minimised.
Notes and sources
- The scores are invented for the lesson: a straight trend (2 + 1.5 points per hour) plus or minus half a point of noise, so you can check every number. Real datasets are bigger and messier.
- np.polyfit is a least-squares fit and still works; NumPy's documentation recommends numpy.polynomial.Polynomial.fit for new code. The program needs NumPy installed (pip install numpy) and prints each degree's training and test MSE.
- In this small example the five held-out students play two parts: first a test set, then (when used to choose the degree) a validation set. In real work keep them separate, so the final test score is still honest.
- In the last step the five held-out students become training data, so nothing is left to test on. That is why real projects collect more data rather than borrow their test set.
- Goodfellow, Bengio & Courville, Deep Learning (MIT Press, 2016), ch. 5.2 Capacity, Overfitting and Underfitting, and 5.3 Hyperparameters and Validation Sets
- Goodfellow, Bengio & Courville, Deep Learning, ch. 7 Regularization (7.8 Early Stopping)
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), 1.1 Polynomial Curve Fitting
- Stanford CS229 lecture notes (A. Ng, T. Ma): bias and variance, regularization and model selection, cross validation
- James, Witten, Hastie & Tibshirani, An Introduction to Statistical Learning, 2nd ed. (2021), 2.2 Assessing Model Accuracy and 5.1 Cross-Validation
- Google Machine Learning Crash Course: Overfitting
- NumPy documentation: numpy.polyfit
- NumPy documentation: numpy.polyval
Quiz Unlocks after the last step.