0:00Intro: MOFUSA Tech Academy
Welcome to MOFUSA Tech Academy. Beyond learning, towards mastery.
0:09Predict tomorrow's sales with a glass-box model
Meera has a meeting tomorrow. She's planning to spend six hundred dollars on ads and wants to know what sales to expect. But she doesn't just want a number. She wants to explain how the number was reached, to her team and her investors. Some models are black boxes. Today's model is the opposite: a glass box. One equation you can write on a napkin, where every part has a meaning. It's linear regression, probably the most widely used predictive model in history, from economics to medicine to every business dashboard.
And today we'll build it completely from scratch, two different ways, and watch both arrive at exactly the same answer.
0:55Map flight: regression
Season One, Module Three: regression. First stop: linear regression from scratch.
1:03The model ŷ = wx + b and what it means
The model is a straight line: y-hat equals w times x, plus b. Here x is the day's ad spend in hundreds of dollars, and y is the day's sales in thousands. Each parameter has a clear meaning. W is the slope: for every extra hundred dollars of ads, how many thousands of extra sales do we expect? B is the intercept: the sales we'd predict with no ads at all, the baseline. Turn w and the line tilts. Turn b and it slides up and down. Our job is to find the one line that fits Brightcart's five days best. But "best" needs a precise definition.
1:48Least squares, drawn with real squares
For any line we draw, each day has a residual, the vertical gap between the real sales and the line's prediction. Now here's a lovely way to see what "best" means. Draw each residual as an actual square. A residual of one becomes a square of area one. A residual of half becomes a square of area one quarter. Move the line around and watch the total area of the squares change. The best line, by the most common definition, is the one that makes that total area as small as possible. That's why it's called least squares.
For Brightcart, the smallest possible total is two point four, which is a mean squared error of zero point four eight, the same minimum gradient descent found in episode five.
2:37Solving it exactly: the closed-form recipe
Gradient descent found this line by walking downhill. But for linear regression, we can do better: we can solve for the best line exactly, with a formula. For a single feature, the recipe needs two ingredients. First, find the averages: average ad spend is three, average sales is six. Then measure how far each day is from those averages. Multiply each day's two distances together and add them up. That's called S-x-y: six, plus two, plus zero, plus two, plus four. Fourteen. You can picture each product as a rectangle stretching from the centre point to the data point.
When x and y are both above average, or both below, the rectangle counts as positive. Then square each x distance and add those up. That's S-x-x: four, plus one, plus zero, plus one, plus four. Ten. The slope is S-x-y divided by S-x-x: fourteen over ten, one point four. And the intercept is the average y minus the slope times the average x: six minus four point two, which is one point eight. Exactly the line gradient descent found, with no iterating at all. And here's a neat fact. The least-squares line always passes through the point of averages, three, six.
4:04Deep dive: the normal equation
Deep dive: the general formula that works for any number of features. Skip ahead if you like; the plain-words version is coming. We write the data as a matrix X with a column of ones for the bias, and stack the parameters into a vector theta: b, then w. The predictions for all days are X times theta. At the bottom of the cost bowl, the slope is zero in every direction. So take the gradient from episode three, set it equal to zero, and rearrange. We get X-transpose X, times theta, equals X-transpose y. Multiply both sides by the inverse of X-transpose X, and theta pops out.
This is called the normal equation. Let's run it on Brightcart's data. X-transpose X is five, fifteen, fifteen, fifty-five. X-transpose y is thirty and one hundred and four. The determinant is fifty, so the inverse is one-fiftieth of fifty-five, minus fifteen, minus fifteen, five. Multiply it all out and we get one-fiftieth of ninety and seventy: one point eight and one point four. The same intercept and slope, now from pure linear algebra. Plain words: the best line sits exactly where the gradient is zero, so instead of walking there, we solve that equation directly.
5:31Normal equation vs gradient descent
So we have two roads to the same answer. Which should we take? The normal equation is exact, needs no learning rate and no iterations. But inverting X-transpose X gets expensive quickly as the number of features grows, roughly with the cube of the number of features. And if two features are perfect copies of each other, the inverse doesn't even exist. Ridge regularisation fixes that, by the way. Gradient descent is approximate and needs a learning rate and scaled features, but it handles millions of features and rows comfortably, can learn from data as it streams in, and, crucially, it works for almost any model, including neural networks, where no neat formula exists.
In practice, libraries solve linear regression with numerically stable methods rather than a literal inverse. But the idea is exactly what we just did.
6:29Residual plots: is a straight line right?
Once we've fitted a line, we should check whether a straight line was the right choice at all. The best tool is a residual plot: each prediction against its error. For Brightcart, the errors scatter around zero with no obvious pattern. That's what we want to see. If you see a U-shape, the real relationship is curved, and a straight line is missing it. We'll fix that next episode. If the spread grows like a funnel, the errors get bigger for bigger values, and a log transform often helps. And a single point far away from the rest is an outlier worth investigating.
Remember, squared error gives outliers a lot of pull. Behind all this are linear regression's classic assumptions: the relationship is roughly linear, the errors are independent, their spread is constant, and for statistical confidence intervals, they're roughly normal. They don't need to be perfect, but big violations mean your predictions or your conclusions can mislead you.
7:34Prediction, extrapolation and causation
Now we can answer Meera. Six hundred dollars of ads: one point four times six, plus one point eight, is ten point two. About ten thousand two hundred dollars in sales. And she can explain exactly why: a baseline of eighteen hundred, plus fourteen hundred for every hundred dollars of ads. So why stop there? Pause and predict: should Meera spend five thousand dollars, since the line says that would bring in seventy-one thousand eight hundred dollars of sales?
No. The model has only ever seen ad budgets between one hundred and five hundred dollars. Beyond that, we're extrapolating, assuming the straight line continues forever. In reality, extra ads eventually stop helping. Always be cautious predicting outside the range of your data. And one more warning, maybe the most important in all of data analysis: correlation is not causation. Ice cream sales and sunburns rise together, but ice cream doesn't cause sunburn. Sunny weather drives both. Brightcart might spend more on ads during festival weeks, when people shop more anyway.
The line shows that the two move together. To prove the ads cause the sales, you need an experiment, like randomly varying ad spend, which is called an A-B test.
9:00Try it yourself: fit a line by hand
Your turn. Three days of data: ad spend of one, two and three hundred dollars, with sales of two, three and five thousand dollars. Find the best line. Pause and work it through, using the recipe from earlier. The averages are two and three point three three. The x distances are minus one, zero and one. The y distances are about minus one point three three, minus zero point three three and plus one point six seven. S-x-y: one point three three plus zero plus one point six seven, which is three. S-x-x: one plus zero plus one, two.
So the slope is three over two, one point five, and the intercept is three point three three minus three, about zero point three three. The predictions are one point eight three, three point three three and four point eight three. The residuals, plus zero point one seven, minus zero point three three, plus zero point one seven, add up to exactly zero. That's always true for a least-squares line with an intercept, a nice way to check your arithmetic. And this little line explains about ninety-six percent of the variation, which we'll learn to calculate next episode.
10:28Why the residuals sum to zero
Why do the residuals always add up to zero? It falls straight out of calculus. At the best line, the slope of the cost with respect to the intercept must be zero, and that slope is proportional to the sum of the residuals. So the residuals must sum to zero. Intuitively: if the errors were mostly positive, you could slide the line up a little and reduce the total error, so at the very best line, the ups and downs balance exactly. A similar condition for the slope means the residuals show no straight-line pattern with x.
11:05How sure are we about the slope?
Here's a question professionals always ask: how sure are we about that slope of one point four? With only five days of data, a slightly different week could easily give a different line. One way to see this is to resample: pick five days at random from our five, allowing repeats, fit a line, and do it again thousands of times. The slopes form a spread, and the middle range of that spread is a confidence interval: a range of plausible values for the true effect of ads. With five days, that range is wide. With five hundred days, it would be narrow.
And it matters for decisions: if the plausible range includes zero, we can't even be confident the ads help at all. The companion notebook computes the exact interval for Brightcart's data.
11:57Linear regression as the honest baseline
Linear regression plays a special role in real projects: it's the honest baseline. It trains in milliseconds, explains every prediction, needs little data, and behaves predictably. So professionals fit it first, and then ask every fancier model, whether boosted trees or neural networks, to beat it on held-out data by enough to justify the extra complexity, cost and loss of explainability. Sometimes the fancy model wins clearly. Sometimes it barely wins, and the simple line is the better business choice.
12:34From one feature to many: a preview
Everything in this episode extends naturally to many features. Two features give a flat plane through a cloud of points; more features give a hyperplane we can't draw, but the normal equation stays exactly the same. Next episode, we'll use it to predict Brightcart's delivery times from distance, number of items and weather, and see how the same machinery can even fit curves.
13:00Myth vs Fact: is linear regression too simple?
Myth: linear regression is too simple to matter any more. Fact: it's used every day in forecasting, pricing, economics and science, precisely because it's fast, stable and explainable. And professionals use it as a baseline: before trusting any complex model, they check it actually beats a plain linear regression. Surprisingly often, it doesn't.
13:25Recap
Let's recap. Linear regression fits y-hat equals w x plus b, where the slope is the effect of x and the intercept is the baseline. Least squares picks the line with the smallest total squared residual. For one feature, the slope is S-x-y over S-x-x and the intercept follows from the averages. For any number of features, the normal equation gives the same answer gradient descent finds. And then: check the residuals, don't extrapolate, and remember that correlation is not causation. One sentence to remember: the best line passes through the averages and makes the squares smallest.
14:09Next: multiple and polynomial regression
Mission complete. Meera walks into her meeting with a prediction of about ten thousand two hundred dollars, an explanation anyone can follow, and the right warnings about its limits. But one feature is rarely enough. Delivery time depends on distance, items and rain. And some relationships curve. Next episode, we'll extend regression to many features and to curves, and learn how to measure how good a fit really is. See you on the map.