0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09One dial, and a 432-to-8 speed-up
Last time, this curve memorised Brightcart's sales data and failed on new weeks. Look at what's behind that wild shape: its weights. Some of them are huge, adding up to more than nine thousand. Huge weights let a curve bend violently. Now watch one dial. A tiny turn, and the weights shrink, the curve calms down, and the error on new data falls from over forty to about two hundredths. Same model, same flexibility, completely different behaviour. And here's a second trick. On the left, gradient descent takes four hundred and thirty-two steps to train Brightcart's delivery model.
On the right, the exact same data, simply rescaled, takes eight. Two simple ideas, regularisation and feature scaling, that every machine learning engineer uses every day. Let's learn both.
1:04Map flight: regularisation and feature scaling
Season One, Module Two, stop three: regularisation and feature scaling.
1:10Why big weights mean overfitting
Why do overfit models have huge weights? Let's look inside the seventh-degree curve. Its prediction is a sum of terms: x, x squared, x cubed, all the way up to x to the seventh, each multiplied by a weight. To thread through every noisy point, the model uses enormous positive and negative terms that almost cancel out. The tiny leftover is the wiggle. And when weights are huge, the slightest change in the input gets amplified into a wild swing in the output. That's exactly why it fails on new data. So here's the idea behind regularisation.
If large weights cause trouble, make them expensive. Change the cost so the model has to pay for every bit of weight it uses.
1:59L2 regularisation (ridge)
The most common version is called L2 regularisation, or ridge regression. We keep the usual error term, the sum of squared errors, and add a second term: lambda times the sum of the squared weights. Now the model faces a trade-off. Fitting the data perfectly lowers the first term, but if it takes huge weights, the second term punishes it. The model has to find weights that fit well and stay small. Lambda is the dial that sets the price. Let's turn it on Brightcart's seventh-degree model. At zero, there's no penalty and we're back to the wild curve: test error over forty.
A tiny lambda of one thousandth already tames it, and the test error drops to zero point three eight. At one hundredth, zero point zero six. At one, the curve is gentle and smooth, and the test error is just zero point zero two, even better than the plain straight line. So what if we make lambda enormous? Pause and predict.
The penalty takes over. The weights are squeezed so hard that the curve goes nearly flat, and we're underfitting again. At ten, the test error is back up to zero point zero nine. So lambda has a sweet spot, and we find it the way we learned last episode: with a validation set or cross-validation. Two more details. We don't penalise the bias, because shifting the whole curve up or down doesn't make it wiggly. And with plain gradient descent, this same L2 idea is called weight decay, because every update shrinks each weight a little towards zero.
3:45L1 regularisation (lasso)
There's a second popular penalty: L1 regularisation, also called lasso. Instead of squaring each weight, it adds up their absolute values. That sounds like a small change, but it behaves very differently. Watch the weight bars for Brightcart's model. As we strengthen the L1 penalty, the weights don't just shrink. They hit exactly zero, one after another. With a strong enough penalty, only two of the seven terms survive: x and x squared. And the test error stays low, at about zero point zero four. So lasso doesn't just keep the model calm.
It automatically picks which features matter and throws the rest away. Imagine a customer model with fifty possible features. Lasso might keep a dozen and switch off the rest, giving a simpler model that's easier to explain. And if you want a bit of both behaviours, there's a mix of the two penalties called elastic net.
4:45Why L1 gives exact zeros: the geometry
Why does L1 produce exact zeros when L2 doesn't? There's a lovely picture that explains it. Optional deep dive; the plain answer comes at the end. Take a model with two weights. The red ellipses are contours of the data error, all centred on the best unpenalised fit. A penalty is like a budget: the weights must stay inside a region. For L2, the region is a circle. As we expand the error ellipses outwards, they first touch the circle somewhere on its smooth edge, usually where both weights are non-zero, just smaller.
For L1, the region is a diamond, with sharp corners sitting right on the axes. Expanding ellipses tend to hit a corner first. And at a corner, one of the weights is exactly zero. In plain words: the L1 diamond has corners on the axes, and the solution likes to land on those corners, so some weights become exactly zero. The L2 circle has no corners, so its weights shrink but stay non-zero.
5:54Feature scaling: the problem
Now the second problem from Dev's mission: why does training take so long? Look at Brightcart's delivery features. Distance runs from one to nine kilometres. Items from one to five. Rain is just zero or one. If we added order value, that could run up to three hundred. The features live on completely different scales. Remember the canyon from the gradient-descent episode? Different scales stretch the cost bowl into exactly that shape. For the delivery model, the bowl is more than three hundred and sixty times more sharply curved in one direction than another.
The steep walls force a tiny learning rate, and the flat floor then takes forever. Gradient descent needs four hundred and thirty-two steps.
6:42Standardisation and min-max scaling
The fix is to put every feature on a similar scale before training. The most common way is standardisation: subtract the feature's mean, and divide by its standard deviation. Take distance. The average Brightcart delivery is four point seven five kilometres, with a standard deviation of about two point six. So seven kilometres becomes seven minus four point seven five, divided by two point six three four: zero point eight five. In words: "a bit less than one standard deviation above average." After this, every feature has a mean of zero and a standard deviation of one.
Another option is min–max scaling, which squeezes each feature into the range zero to one. It's handy when you need a fixed range. Image pixels, for example, are often scaled from zero to two fifty-five down to zero to one. But a single extreme value, like the four-hundred-and-twenty-dollar order from episode four, can squash everything else into a tiny corner of the range, so standardisation is usually the safer default.
7:51Watch it learn: 432 steps vs 8
Let's train the delivery model again on standardised features. Before we run it, a quick prediction: four hundred and thirty-two steps before, so how many now? Eight. Standardising turned the canyon into an almost round bowl, so the gradient points nearly straight at the bottom, and we can safely use a learning rate about twenty-five times larger. The predictions at the end are the same as before. Only the weights look different, because they're now measured per standard deviation instead of per kilometre. Just remember: every new order has to be scaled in exactly the same way before the model sees it.
8:38The leakage trap, and who needs scaling
One trap here catches a lot of people. The mean and standard deviation used for scaling must be computed on the training data only. Then those same numbers are applied to the validation set, the test set and real customers. If you compute them using the test data too, a little information about the test set leaks into training, and your test score becomes too optimistic. It's called data leakage, and we'll meet it again next episode. So which models need scaling? Anything trained by gradient descent, because of the canyon problem.
Anything based on distances, like k nearest neighbours and k-means, because otherwise the feature with the biggest numbers dominates the distance. And regularised models, because the penalty compares weights across features. Decision trees and the forests built from them, on the other hand, don't care, because they split one feature at a time.
9:35Try it yourself: ridge shrinkage by hand
Let's see ridge regression shrink a weight, by hand. Three data points, x equals one, two, three, and y equals two, four, six point five, with a model that's just w times x. With the ridge penalty, the best w turns out to be the sum of x times y, divided by the sum of x squared plus lambda. The sum of x times y is twenty-nine point five. The sum of x squared is fourteen. Pause and predict w for lambda equals zero, one and fourteen.
With no penalty, w is twenty-nine point five over fourteen: about two point one one. With lambda equals one, it's twenty-nine point five over fifteen: one point nine seven. With lambda equals fourteen, it's twenty-nine point five over twenty-eight: about one point zero five, roughly half. You can see the penalty literally sitting in the denominator, pulling the weight towards zero. The bigger lambda, the stronger the pull.
10:51Ridge, lasso or elastic net?
So which penalty should you use? Ridge suits problems where many features each contribute a little, and it handles groups of correlated features gracefully, sharing the weight between them. Lasso suits problems where you suspect only a few features truly matter, and you want a smaller, easier-to-explain model. One caution: when several features are highly correlated, lasso tends to keep one and drop the others somewhat arbitrarily. Elastic net, a blend of the two, is a good choice when you have many correlated features but still want some selection.
In practice, try them with cross-validation, and always standardise features first, so the penalty treats every feature fairly.
11:38Regularisation is everywhere
Regularisation isn't one formula. It's a family of ideas with one goal: discourage memorising noise and encourage simpler explanations. Using a smaller model is regularisation. Stopping training early is regularisation. Pruning a decision tree, which we'll do in episode fourteen, is regularisation. In neural networks, you'll meet dropout, which randomly switches off neurons during training, weight decay, which is L2 by another name, and data augmentation. Whenever you see a technique that makes a model a little worse on training data so that it generalises better, you're looking at regularisation.
12:20When scaling goes wrong
Scaling causes some of the most common bugs in real projects. The first we've seen: computing the mean and standard deviation on all the data, test set included, which leaks information. The second happens in production: the model was trained on standardised features, but someone sends it raw values, seven kilometres instead of zero point eight five standard deviations, and the predictions go haywire. The fix is to save the scaler together with the model, as one pipeline, so new data is always transformed with exactly the same numbers used in training.
And a smaller point: binary yes-or-no columns usually don't need scaling. Scaling them rarely hurts, but whatever you choose, do it identically in training and in production.
13:10Myth vs Fact: does regularisation hurt?
Myth: regularisation makes a model worse, because it fits the training data less well. Look at the numbers. With lambda at one, training error went up from zero to about six hundredths. And test error collapsed from over forty to about two hundredths. Giving up a little fit on old data bought a huge improvement on new data, and new data is the only thing that counts.
13:37Recap
Let's recap. Overfit models tend to have huge weights, so regularisation makes large weights expensive. L2, or ridge, adds the squared weights and shrinks them smoothly. L1, or lasso, adds their absolute values and sets some to exactly zero. Lambda sets the strength, and we choose it with validation. Feature scaling puts every feature on a similar scale, turning a narrow canyon into a round bowl, and training Brightcart's delivery model went from four hundred and thirty-two steps to eight. Always fit the scaler on the training data only.
One sentence to remember: make big weights expensive, and put features on the same scale.
14:22Next: feature engineering
Mission complete. Brightcart's flexible model no longer memorises, and its training is fifty times faster. But so far our data has been neat columns of numbers. Real data isn't. It has categories, missing values, dates and text, and the way we turn that mess into features often matters more than the model itself. That's feature engineering, and it's next. See you on the map.