Fitting the data
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.
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.
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.
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.
Generalising
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.
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).
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.
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.
Choosing and fixing
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.
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.
What happens
;; step 1/10 · data 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
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. 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.