0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09The perfect model that fails on new data
Here are eight weeks of Brightcart sales. And here's a model that fits them perfectly. Every single point, exactly. Its training error is zero. Flawless. Now four held-out weeks, scattered through the period, weeks the model has never seen. The perfect model predicts them terribly. Its error jumps from zero to over forty. Meanwhile, a boring straight line, one that never fitted the training data perfectly, predicts the new weeks almost exactly. How can the "perfect" model be the worst one? This is overfitting, the most important trap in all of machine learning.
Today we'll see why it happens, how to detect it, and how professionals test models honestly.
0:58Map flight: overfitting
Season One, Module Two, stop two: overfitting, and how to test a model honestly.
1:06Generalisation: the student analogy
Think of two students preparing for an exam. One memorises last year's papers word for word. The other learns the methods behind the answers. Give them last year's exam again and they both score a hundred percent. But give them new questions, and the memoriser collapses while the student who learned the method still does well. A machine learning model can be either student. What we actually want is called generalisation: performing well on new data the model has never seen. Doing well on the training data proves nothing by itself, because a model can always memorise.
That's why, as we said in episode one, we lock part of the data away as a test set. It's the exam with new questions.
1:56Underfitting, a good fit and overfitting
Let's fit three models of increasing flexibility to Brightcart's eight training weeks. The first is just a flat line, the average. It's too simple to capture the upward trend, so it's wrong on the training data and wrong on the test data. That's underfitting. The second is a straight line. It doesn't hit every point, but it follows the real trend. Training error zero point zero five, test error zero point zero five. That's a good fit. The third is a seventh-degree polynomial, a curve flexible enough to bend through all eight points exactly.
Training error: zero. But look past the last training week: it shoots off, predicting almost eighteen when the truth is about five. It bent itself to chase every little random bump. Those bumps were noise, just week-to-week luck that will never repeat. The model memorised the noise instead of learning the pattern. That's overfitting. How flexible a model is allowed to be is called its capacity. Too little and it underfits. Too much and it overfits.
3:04The complexity curve
This picture is worth remembering for your whole career. As we make a model more flexible, the training error just keeps going down. More flexibility always means a closer fit to the data it's seen. But the error on new data tells a different story. At first it falls too, because the model is learning the real pattern. Then it hits a lowest point, and after that it climbs, because the extra flexibility is being spent on memorising noise. The dangerous part is the right-hand side. Training error is still improving, and it looks like progress, but the model is getting worse at the only thing we care about.
Never judge a model by its training error alone.
3:49The bias-variance trade-off
There's a precise way to think about these two failures, called the bias–variance trade-off. Imagine training the same kind of model many times, each time on a different random sample of data. Each trained model is one dart thrown at a dartboard, and the bullseye is the truth. Bias is how far the average dart is from the bullseye. It's a systematic error from a model that's too simple to represent the truth. Variance is how scattered the darts are. It's how much the model changes depending on which data it happened to see.
Let's actually do it. Five hundred resampled versions of Brightcart's data, each with its own fitted model. The flat lines are all bunched together, so they have low variance, but they're all wrong in the same way: high bias. The seventh-degree curves have almost no bias on average, but they're wildly scattered, with a variance of about one, more than twenty times the straight line's. The straight lines are both centred and tight. For squared error, there's an exact result: the expected error on new data equals bias squared, plus variance, plus irreducible noise.
That last part is randomness no model can ever remove. Simple models tend to have high bias. Flexible models tend to have high variance. Good modelling means balancing the two.
5:20Train, validation, test and cross-validation
In practice we usually split data three ways. The training set is where the model fits its parameters. The validation set is for making choices, like which polynomial degree or which learning rate to use. And the test set stays locked away until the very end, to give one final, honest score. Why not choose settings using the test set? Because every time we peek at it and adjust, a little information leaks in, and the test score starts to flatter us. Do that enough and the test set has quietly become part of training.
When data is scarce, there's a smarter way to validate: k-fold cross-validation. Split the data into, say, four folds. Train on three folds, validate on the fourth. Then rotate, so every fold gets a turn as the validation set, and average the four scores. Every example gets used for both training and validation, and the score is far less dependent on one lucky split. Here we treat the weeks as interchangeable samples; for real forecasting, you'd use the rolling validation coming up. Here are four-fold scores for Brightcart's sales data, for degrees one, two, three, five and seven.
Pause and predict: which degree wins? Degree two edges it with zero point zero six two, just ahead of the straight line at zero point zero six seven. After that, the error climbs fast, all the way to over two for degree seven. When two models are this close, the usual practice is to choose the simpler one, and here we happen to know the true trend really is a straight line. Cross-validation narrows things down; good judgement makes the final call.
7:13How to fix overfitting: a preview
So how do we fight overfitting? We'll study these tools properly, but here's the toolkit. More data makes memorising harder, because the noise starts to average out. A simpler model has less capacity to memorise. Regularisation, next episode, adds a penalty that keeps the model's weights small and its shape smooth. Early stopping halts training at the moment validation error starts to rise. And in Season Two, neural networks bring their own tools, like dropout and data augmentation. And if you're underfitting instead, you go the other way: a more flexible model, better features, or simply more training.
7:55Try it yourself: diagnose three models
Let's practise diagnosing models. Three report cards. Model A: ninety-nine percent on training data, seventy percent on test data. Model B: seventy-two percent on training, seventy on test. Model C: ninety-five on training, ninety-three on test. Which one is overfitting, which is underfitting, and which is healthy? Pause and decide.
Model A has a huge gap between training and test: it's memorising. That's overfitting, so try more data, a simpler model, regularisation, or stopping training earlier. Model B is poor everywhere: it's too simple to capture the pattern. That's underfitting, so try a more flexible model, better features, or more training. Model C is close on both and high on both: a healthy fit, ready for the final checks. The key habit: always look at training and test performance together. The gap tells you about variance; the level tells you about bias.
9:04Learning curves: performance vs data size
A powerful diagnostic tool is the learning curve: train on more and more data, and plot the performance. Here's a real one from handwritten digits, which we'll meet again in Season Two. With twenty-five examples, sixty-three percent. With two hundred, ninety-three. With all twelve hundred and fifty-seven, ninety-seven. Big gains at first, then smaller ones. The shape of the curves tells you what to do. If training and validation performance have a big gap that's still closing as data grows, the model has high variance, and more data will help.
If both curves have flattened at a disappointing level, the model has high bias, and more data won't help much. You need a better model or better features. That single chart can save weeks of collecting data that won't make a difference.
10:00Validating models that predict the future
Ordinary cross-validation shuffles data randomly. For problems that predict the future, like next week's sales, that's a mistake: the model can train on later weeks and be tested on earlier ones, peeking at the future. The score looks great, and reality disappoints. The fix is rolling validation. Train on weeks one to six and test on week seven. Then train on weeks one to seven and test on week eight. Keep sliding forward, always testing on data that comes after everything the model trained on. It's exactly how the model will be used in real life.
10:40The danger of reusing the test set
There's a subtler trap. Imagine a team tries fifty different models, checks each one on the test set, and keeps the best. Each check is honest on its own, but choosing the best of fifty using the test set means they've quietly fitted to the test set's quirks. When fresh data arrives, performance is lower than reported. The discipline: make every choice using validation data, and touch the final test set only once, at the end. If you need to keep experimenting, collect a fresh test set. A technique called nested cross-validation does this automatically: an inner loop chooses the settings, and an outer loop measures performance on data that played no part in those choices.
11:28Early stopping: a preview
One more tool for the toolkit, as a preview. Models trained step by step, like the gradient descent from last episode, start by learning real patterns and later begin to memorise noise. If you track the validation error during training, you'll often see it fall, reach a minimum, and then start rising, even as the training error keeps going down. Stop at that minimum, and keep the model from that moment. It's called early stopping, and in Season Two we'll watch it happen live, in a real neural network.
12:05Always compare with a baseline
Before celebrating any test score, ask: compared with what? Every project needs a baseline, the simplest sensible prediction. For Brightcart's weekly sales, three baselines come to mind: always predict the average of past weeks, predict that next week will look exactly like last week, or fit a plain straight-line trend. Any sophisticated model must beat these, on the same test weeks, by a clear margin. Baselines matter even more for classification. If only one customer in ten leaves, a "model" that always predicts "stays" is already ninety percent accurate, without learning anything at all.
We'll dig into that trap in episode twelve. The rule is simple: if your model can't clearly beat a simple baseline on held-out data, it isn't ready, however impressive its training score looks. Baselines keep everyone honest, including you.
13:02Myth vs Fact: training accuracy
Myth: if my model is ninety-nine percent accurate on its training data, it's ready to use. Fact: training accuracy tells you almost nothing on its own. Only data the model has never seen estimates how it'll do in the real world. And one more subtle point. Your test data should look like the future the model will face. For sales over time, that means training on the past and testing on later weeks, not on randomly shuffled ones. Otherwise the model gets to peek at the future during training.
13:34Recap
Let's recap. Our goal is generalisation, doing well on data we've never seen. Too simple a model underfits, and too flexible a model overfits, memorising noise. For squared error, the expected error splits exactly into bias squared, variance and noise. We fit on training data, choose settings on validation data, and use the test set once, at the end. And cross-validation rotates the validation fold to give a steadier score. One sentence to remember: training error flatters, test error tells the truth.
14:11Next: regularisation and feature scaling
Mission complete. Will the model work next month? Only if it generalises. The plain straight line does; the "perfect" curve doesn't. But sometimes we need flexible models, because the real pattern is complicated. So how do we keep their flexibility without letting them memorise? That's regularisation, together with a trick that makes training far faster: feature scaling. That's next. See you on the map.