0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Same data, two answers
Real problems rarely have just one cause. A delivery's time depends on distance, on how many items there are, and on whether it's raining, all at once. And not everything is a straight line. Brightcart's discounts boost sales, but at some point bigger discounts stop helping, and even start hurting. And here's a puzzle. One Brightcart model says each kilometre adds four point six six minutes to a delivery. Another, built on exactly the same deliveries, says three point nine seven. Same data, different answers. Which one is right?
Today: regression with many features, regression with curves, and how to measure whether a fit is actually any good. Season One, Module Three, stop two: multiple and polynomial regression.
1:04From a line to a plane
With one feature, regression draws a line. With two features, say distance and number of items, it draws a flat plane through a cloud of points in 3D. Each red stick is a residual, the gap between a real delivery and the plane. With more features, we can't draw it any more. It becomes a hyperplane in many dimensions. But the maths doesn't change one bit. It's the dot product from episode two: each feature times its weight, all added up, plus a bias. And for all orders at once: X times w, plus b. Least squares and the normal equation work exactly as before.
For Brightcart's eight deliveries, the best fit is: three point nine seven minutes per kilometre, zero point eight eight per item, seven point nine two extra when it rains, plus four point four five minutes of fixed time, for loading and finding a parking spot.
2:06Reading coefficients
The beauty of a linear model is that every coefficient has a meaning. But it's a precise one. Take a seven-kilometre delivery with three items in the rain: forty-two point eight minutes. Now add one kilometre and keep everything else exactly the same. The prediction rises by three point nine seven. Add one item instead: up by zero point eight eight. Switch the rain off: down by seven point nine two. So each coefficient means: the change in the prediction when that one feature goes up by one unit, holding all the other features fixed.
That last phrase matters a lot, as we're about to see. One more caution. You can't compare raw coefficients to decide which feature is "most important" when they're in different units, minutes per kilometre against minutes per item. Standardise the features first, and then the sizes become comparable.
3:03Why coefficients change: confounding
Now the puzzle from the start. If we model delivery time with distance alone, each kilometre seems to add four point six six minutes. Add items and rain, and it drops to three point nine seven. Why? Pause and predict. Look at which deliveries were made in the rain.
In this sample, the rainy deliveries happened to be among the longer trips. So when the model only knew about distance, it couldn't separate "long trip" from "rainy day". Some of the rain's delay got blamed on the kilometres. Once rain gets its own coefficient, distance only takes credit for its own effect. Rain explains most of the drop; the number of items explains a little more. This is called omitted-variable bias, or confounding, and it's why a coefficient's meaning always depends on what else is in the model.
Leave out something important, and the other coefficients quietly absorb its effect. The opposite problem happens when two features move almost in lockstep, like distance and fuel used. The model can't tell which one deserves the credit, so their coefficients become unstable, swinging wildly with small changes in the data. That's called multicollinearity, and ridge regularisation is a common remedy.
4:29Polynomial regression
What about relationships that curve? Here are Brightcart's discount experiments. Bigger discounts boost sales, up to a point, then the effect levels off and drops. A straight line fits poorly, R squared zero point seven eight, and its residuals make that tell-tale arch shape: an upside-down U. Here's the trick. We don't need a new algorithm. We just add a new feature: the discount squared. Now the model is y-hat equals w one times d, plus w two times d squared, plus b. Fit it with the very same least squares, and the line becomes a curve that hugs every point, with an R squared of zero point nine nine nine.
This is called polynomial regression, and the key insight is that it's still linear regression. The model is linear in its parameters, the w's, even though it's curved in d. We simply gave it a richer set of features. And now calculus pays off. The curve peaks where its slope is zero, which works out to a discount of about twenty-three percent, for a lift that also happens to be about twenty-three percent. Beyond that, deeper discounts lose sales. But remember episode six. Higher and higher degrees can bend through everything, including noise.
Choose the degree with validation, and regularise.
5:55Scoring a fit: MAE and RMSE
How good is the delivery model? First, in the problem's own units. The root mean squared error is one point six five minutes, so a typical prediction is off by under two minutes. Dev can work with that. We met these in the cost-functions briefing. Mean absolute error treats every minute of error equally. Root mean squared error squares first, so it punishes big misses more. Both are in minutes, and both are easy to explain to a non-technical audience.
6:27R² explained
The most famous score for regression is R squared. Here's what it actually means. Start with the laziest possible model: ignore x and always predict the average, six. Draw the squared errors of that flat line. Their total is twenty-two. That's all the variation in the data. Now draw the squared errors of our fitted line. Their total is just two point four. R squared is one minus the ratio: one minus two point four over twenty-two, which is zero point eight nine one. In plain words: our line explains about eighty-nine percent of the day-to-day variation in sales that the average couldn't explain.
One means perfect. Zero means no better than always guessing the average. And on test data, it can even go negative, when a model is worse than the average. The delivery model scores zero point nine eight three. But be careful. Plain R squared never goes down when you add a feature, even a completely useless one. Adjusted R squared charges a small price for each feature: here, zero point nine seven one. And no R squared, however high, proves a model will work on new data, or that it's capturing cause and effect. Always pair it with a test set.
7:49Try it yourself: compare two deliveries
Try this. Two Brightcart orders, both with two items. Order A is three kilometres away on a dry day. Order B is six kilometres away, in the rain. How much longer should B take? Pause and work it out from the coefficients.
The items are the same, so their contribution cancels. B is three kilometres further, which adds three times three point nine seven, about eleven point nine minutes, and it's raining, which adds seven point nine two. In total, about nineteen point eight minutes longer. With a linear model, you can read differences straight off the coefficients, a big reason people love them for explaining decisions.
8:39Dummy variables for categories
What about categories, like which delivery zone an order is in: city centre, suburbs or outskirts? We use the one-hot encoding from episode eight, dropping one zone as the reference. The model then learns a separate shift for each remaining zone: how many extra minutes, on average, a suburban or outskirts delivery takes compared with the city centre, holding distance, items and rain fixed. And here's why we drop one column. Include all three zone columns plus an intercept, and the three columns always add up to one, exactly duplicating the intercept.
Then the matrix in the normal equation has no inverse, the problem we previewed in episode two, and the coefficients can't be determined.
9:26Interaction features
Sometimes one feature changes the effect of another. Dev suspects rain slows long trips more than short ones. We can capture that by adding an interaction feature: distance multiplied by rain. On dry days, that feature is zero, and the slope for distance is just w one. In the rain, the slope becomes w one plus w four, so if w four is positive, each kilometre costs more time in the rain. But be careful: our tiny dataset of eight deliveries is far too small to estimate five parameters reliably. That would be overfitting, from episode six.
Interactions are powerful, and they need enough data to support them.
10:10Choosing the polynomial degree
How do we know a squared term was right for the discount data, and not a much higher degree? With only seven discount levels, a high-degree polynomial could pass exactly through every point, a perfect score on the data, and dive wildly just outside the tested range. The honest approach is the one from episode six: hold some discount levels out, or use cross-validation, and choose the degree that predicts the held-out points best, preferring the simplest one that's nearly as good. And apply business sense. The fitted curve will happily predict what happens at a fifty percent discount, but Brightcart never tested fifty percent.
That's extrapolation, and the curve's opinion there is a guess.
11:00Too many features, too little data
One last warning. As you add features, the model gains flexibility. With as many features as data points, a linear model can fit the training data perfectly, an R squared of one, and predict nonsense for anything new. As a rough guide, you want many more examples than parameters, and when features are plentiful, ridge or lasso regularisation from episode seven keeps the coefficients sensible. Adjusted R squared and cross-validation are your early-warning systems.
11:33Planning driver hours
Models earn their keep when they drive decisions. Dev needs to plan tomorrow's driver hours for about a hundred orders. Plug the average order profile into the model: four point seven five kilometres, about two point four items, and rain on three orders in eight. That's four point four five, plus about eighteen point nine for distance, plus about two point one for items, plus about three for rain: roughly twenty-eight point four minutes per order. Notice something neat: that's exactly the average delivery time in the training data.
A least-squares line with an intercept always passes through the point of averages, now in every dimension at once. For a hundred orders, that's about two thousand eight hundred and forty minutes, roughly forty-seven driver-hours. But averages hide variation. A rainy day, or a cluster of long-distance orders, could push that up noticeably, and each individual prediction is typically off by a couple of minutes. So a good plan adds a buffer, or better still, predicts every order individually and adds them up.
12:43Myth vs Fact: R²
Myth: an R squared of zero point nine nine means your model is excellent. Fact: our overfit seventh-degree curve had a training R squared of one, the maximum, and it failed on new data. A leaked feature can push R squared towards one. And any two things that both grow over time can show a high R squared without being related at all. Judge models on held-out data, in real units, with common sense about the problem.
13:15Recap
Let's recap. Multiple regression fits a weighted sum of many features: a plane, or a hyperplane. Each coefficient is the effect of its feature, holding the others fixed, so leaving out an important feature makes the others absorb its effect. Polynomial regression captures curves by adding powers of a feature, and it's still linear regression underneath. We score fits in real units with M-A-E and R-M-S-E, and with R squared, the share of variation explained, ideally adjusted, and always on test data. One sentence to remember: a coefficient only means something alongside the features it's measured with.
13:59Next: logistic regression
Mission complete. Dev's delivery estimates are accurate to within about two minutes, and Meera now knows that discounts past about twenty-three percent stop paying off. That completes Module Three: regression. But many of Brightcart's most important questions aren't "how much?" They're "yes or no?" Will this customer leave? Is this review fake? For those, we need classification, and it begins with a clever twist on everything we've just learned: logistic regression. See you on the map.