internalsGet Pro

Module 07 · Lesson 1 of 12Free

Linear regression from scratch

Level
Beginner
Topic
Classical ML: regression and classification
Reading time
13 min

When you finish this page you can

  1. Fit a linear regression with scikit-learn and score it on held-out customers against a baseline.
  2. Read each weight in its own units, and compare features by the effect of a typical change.
  3. Use residual checks to find a bend or a growing spread that a single error number hides.
  4. Decide when a new feature fixes a straight line and when the line is the wrong shape.
  1. Least squares: the best-fitting line17 min
  2. Common losses: squared error to cross-entropy14 min
  3. Train, validation and test sets13 min
0:00 / 7:13
Show transcript

0:00 Kartly is our example online store. Farah, an ML engineer, is building a model that predicts what each customer will spend next month. Joseph, who leads growth, needs that number to size the voucher budget. Today, Joseph’s sheet uses one rule: next month, each customer spends their average of the last three months. Over 200,000 customers, the sheet says about 16.2 crore rupees. Farah tests the rule on a month that has already happened. Customers really spent about 14.1 crore. The sheet is 15% too high. Why? Look at the heavy spenders. Next month, most of them spend less. Light spenders mostly spend more. A big month is partly luck, and luck doesn’t repeat. So copying the past overshoots. So here’s the plan. Fit a straight line that predicts next month’s spend. Read what it learned. And spot when a straight line is the wrong shape.

0:54 Farah gives the model three facts about each customer, called features. Past spend, in rupees a month. Days since their last order. And whether they shop in the app, as a one or a zero. The label, the answer it learns, is what they spend the month after. Linear regression gives each feature one weight, and adds a constant. Multiply each feature by its weight, add them up, and add the constant. Each weight is in rupees per unit of its feature. The constant, called the intercept, is the prediction when every feature is zero. How are the weights chosen? scikit-learn’s LinearRegression, picks the ones that make the sum of squared misses smallest. That’s least squares. Squared error aims at the average, which is what a budget total needs. And with three features, the exact answer takes well under a second. Here’s what it learns. Joseph’s rule is the diagonal: next month equals the past. Farah’s line rises more gently. It keeps about 0.70 of each past rupee. So for light spenders, it predicts more than the past. For heavy spenders, less. And heavy spenders make up most of the total. Before fitting, Farah holds out 50,000 customers that the model never trains on. It fits on the other 150,000. In scikit-learn’s split, a whole number means a count, not a share.

2:07 Why hold customers out? On the training customers, the misses always balance out. Least squares with an intercept makes them add up to zero. So the honest score comes from the held-out customers, the test set. The score is RMSE, short for root mean squared error. It’s a typical miss for one customer, in rupees. Farah’s line misses by about 550. That sounds large next to an average spend of 707. But next month’s spend is noisy for any model. What matters is the comparison with baselines. Joseph’s rule misses by about 650. Predicting the average for everyone misses by about 930. scikit-learn also reports R squared. It compares the model’s squared error with that of predicting the average. One means perfect. Zero means no better than the average. Below zero means worse. Farah’s line scores about 0.65. One more check. A random split tests new customers from the same month. So before Joseph relies on it, Farah also tests a later month.

3:10 Now read what the line learned. Change one feature by one unit, keep the others fixed, and the prediction moves by that feature’s weight. Past spend gets 0.70 for each rupee. Each quiet day since the last order takes off about 3 rupees. And shopping in the app adds 100. So the app looks like the biggest effect, and past spend the smallest. Both readings are wrong. Each weight is in its own units, so raw weights can’t be compared. Instead, compare the effect of a typical change in each feature. Past spend varies by thousands of rupees, so its typical effect is about 745 rupees. The app flag’s is only about 49. And the intercept, 233 rupees, is the prediction for a customer with no past spend, no gap and no app. Alone, it means little. Keeping the others fixed has a catch. When two features move together, like past spend and order count, the line can split their shared effect almost any way. That’s called multicollinearity. Predictions stay good, but each weight alone stops meaning much.

4:14 A residual is one customer’s actual spend minus the prediction. RMSE squeezes all 50,000 of them into one number. Grouping them shows where the line is wrong. Farah sorts the test customers into 15-day bands of days since their last order. Then she averages the residuals in each band. The points form a V. Why a V? The real effect of a quiet day stops at 45 days. After that, a customer has settled at their low level. A straight line can’t stop, so it settles for minus 3 rupees a day, everywhere. Look at the bottom of the V: customers quiet for 30 to 60 days. The line predicts too much for them. Together, that’s about 30 lakh rupees too much. Yet RMSE barely notices. Fixing the bend lowers it by only about 1 rupee. The second check plots each residual against its prediction, on held-out data, as scikit-learn’s PredictionErrorDisplay does. The points spread out like a fan. Small predictions miss by about 200 rupees either way. Big ones, by about 1,500. A big spender’s month varies by more rupees, so their misses are bigger. A spread that changes like this is called heteroscedasticity. But the centre of the fan stays near zero. So totals still hold, while any single big prediction is rough.

5:32 So what should Farah change before the model sizes Joseph’s budget? Four choices. Keep the straight line. Switch to a tree model, covered later in this module. Predict the log of spend. Or add one new feature. Keeping the line leaves the total right, but budgets split by days since the last order come out too high or too low. A tree finds the bend by itself, but its weights no longer read as rupees. The log of spend tames the fan, but its predictions turn into medians, so the budget comes out short. And it doesn’t fix the bend. The best fix is one new feature: days past 45. It stays at zero until then, and counts up after. With it, the line can bend right there. The days weight becomes about minus 6 rupees a day, and the new one about plus 6, so they cancel after the bend. Four weights, still read in rupees. The V disappears, and the handful of negative predictions goes away. Two cases change the choice. Many bends, or effects that depend on each other, point to trees. And if Joseph starts using single predictions, like one voucher per customer, the fan matters more than the total.

6:36 Let’s recap. One: linear regression fits one weight per feature by least squares, aiming at the mean a budget needs. Two: score it on held-out customers, against baselines. Three: weights are in their own units, so compare the effect of a typical change. Four: group the residuals. A V shows a bend, a fan shows a growing spread, and neither moves RMSE much. Five: a known bend needs one new feature, not a new model. Joseph’s next question is who will stop buying. A straight line fitted to a yes-or-no label gives values below zero and above one. Next, we bend the line into a probability. See you in Logistic regression: predicting probabilities.

Joseph’s sheet assumes nobody changes

is our example online store. Farah, an ML engineer, is building the model that predicts how much each customer will spend next month, so Joseph, the growth lead, can size the voucher budget.

Joseph’s sheet uses one rule: next month, each customer spends their average of the last three months. Across 200,000 customers that adds up to about ₹16.2 crore. When Farah checks the rule on a month whose outcome is already known, customers spent about ₹14.1 crore. The sheet is about ₹2.1 crore, 15%, too high.

The 200,000 customers come from the course’s notebook sample. The three features, the rule that makes next-month spend, the noise and every rupee figure here are this lesson’s made-up scenario, built so the expected results can be worked out by hand.

This lesson answers one question: how do you fit a straight line that predicts next-month spend, read what it learned, and tell when a straight line is the wrong shape? Least squares taught the maths. Here we build and judge a working model.

Check yourselfAnswer in your head first, then reveal
Farah plots past spend against next-month spend. Do customers who spent ₹3,000 a month mostly spend more or less next month? And customers who spent ₹200?Show answerHide answer
Heavy spenders mostly spend less, about ₹2,240, and light spenders mostly spend more, about ₹280. A big month is partly luck that doesn’t repeat. That is why Joseph’s sheet, which repeats the past, overshoots.

A straight line learns how much the past carries over

Farah gives the model three per customer, measured at the end of a known month: past spend (₹ per month, last three months), days since the last order, and whether they shop in the app (1 or 0). The is what they spent the following month. Linear regression predicts with one weight per feature plus a constant:

y^=b+w1x1+w2x2+w3x3\hat{y} = b + w_1 x_1 + w_2 x_2 + w_3 x_3
  • y^\hat{y} is the predicted next-month spend, in rupees.
  • x1,x2,x3x_1, x_2, x_3 are past spend, days since the last order and the app flag.
  • w1,w2,w3w_1, w_2, w_3 are the , each in rupees per unit of its feature.
  • bb is the intercept: the prediction when every feature is 0.

scikit-learn’s LinearRegression picks the weights that make the sum of squared misses smallest, by ordinary least squares.1 Squared error aims at the mean, which is what a budget total needs, as Common losses showed. With three features there is no need for the steps of gradient descent: the exact answer takes well under a second.

The fitted line keeps 70 paise of each past rupee. Joseph’s rule keeps all of it, so it overshoots for the heavy spenders who make up most of the total.

Farah holds out 50,000 customers the model never trains on, then fits on the other 150,000. A whole number for test_size means a count of rows, not a share.3 Leave it out and you get the default, 0.25 (25% test, 75% train).

Python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(42)
n = 200_000
past = rng.lognormal(mean=6.2, sigma=1.0, size=n)   # avg monthly spend, last 3 months (₹)
gap = rng.integers(0, 91, size=n).astype(float)     # days since the last order
app = (rng.random(n) < 0.4).astype(float)           # 1 if they shop in the app

# The made-up rule behind next-month spend, with noise that averages 1
mean_spend = 0.7 * past + 100 * app + 300 - 6 * np.minimum(gap, 45)
spend_next = mean_spend * rng.lognormal(mean=-0.125, sigma=0.5, size=n)

X = np.column_stack([past, gap, app])               # column order matters: keep it
X_train, X_test, y_train, y_test = train_test_split(
    X, spend_next, test_size=50_000, random_state=42)

model = LinearRegression().fit(X_train, y_train)
print("weights:", model.coef_.round(2), "intercept:", round(model.intercept_, 1))

pred = model.predict(X_test)
rmse = np.sqrt(np.mean((y_test - pred) ** 2))
rmse_sheet = np.sqrt(np.mean((y_test - X_test[:, 0]) ** 2))
rmse_mean = np.sqrt(np.mean((y_test - y_train.mean()) ** 2))
print("RMSE line:", round(rmse), " sheet:", round(rmse_sheet), " mean:", round(rmse_mean))
print("R² on test:", round(model.score(X_test, y_test), 2))
print("test total, ₹ crore: actual", round(y_test.sum() / 1e7, 2),
      " line", round(pred.sum() / 1e7, 2))

Expected values worked out from the rule, not a measured run:

  • Weights close to 0.70, −3.0 and 100; intercept near 233.
  • RMSE about 550 for the line, 650 for Joseph’s rule, 930 for predicting the average for everyone.
  • R² about 0.65.
  • Test totals within about 1% of each other, near ₹3.5 crore each.

Score the line on customers it never saw

The training misses always balance out, because least squares with an intercept makes them sum to zero. So the honest score comes from the 50,000 held-out customers, the .

RMSE=1n∑i=1n(yi−y^i)2\text{RMSE} = \sqrt{\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2}
  • nn is the number of test customers.
  • yiy_i is what customer ii spent; y^i\hat{y}_i is the prediction.
  • RMSE is in rupees: a typical miss for one customer.

A miss of ₹550 sounds large next to a mean of ₹707, but next-month spend is noisy for any model. What matters is the comparison: ₹550 against ₹650 for Joseph’s rule and ₹930 for the plain average, the . score reports R²:1

R²=1−(model’s squared error÷squared error of predicting the average)
1.0 is perfect; 0 means no better than the average; below 0 means worse

A random split checks new customers from the same month. Before Joseph relies on the model, Farah also checks a later month, as Train, validation and test sets explains.

Each weight is an effect in its own units

coef_ holds the weights and intercept_ the constant.1 Read each one as: change this feature by one unit, keep the others fixed, and the prediction moves by the weight.

Raw weights can’t be compared across units. Multiply each by a typical change in its feature, one standard deviation, and past spend dominates.

The ₹100 for app users looks biggest, and the 0.70 smallest. Both readings are wrong. Past spend varies by thousands of rupees, so its typical effect is about ₹745; the app flag’s is about ₹49. The intercept, ₹233, is the prediction for a customer with no past spend, no gap and no app, and means little alone.

“Keep the others fixed” has a catch. When two features move together, such as past spend and order count, the line can split their shared effect between them almost any way. That is multicollinearity: the predictions stay good, but each weight alone stops meaning much.

Residuals show what the score hides

A residual is actual minus predicted for one customer. RMSE squeezes 50,000 of them into one number; grouping them shows where the line is wrong. Farah averages the test residuals in 15-day bands of days since the last order.

A V in the residuals means the true effect bends. The straight line overpredicts customers quiet for 30–60 days and underpredicts the newest and the quietest.

The true effect of a quiet day stops at 45 days: after that, a customer has settled at their low level. A straight line can’t stop, so it compromises at −₹3 a day everywhere. For the 66,000 customers quiet for 30–60 days, it overpredicts by about ₹45 each, ₹30 lakh in all. RMSE barely notices: removing the bend lowers it by about ₹1.

The second check plots residuals against predictions, as scikit-learn’s PredictionErrorDisplay does; its docs recommend held-out data for it.2

The spread of misses grows with the prediction. The average is still right, so totals hold; any single big prediction is rough.

Misses grow with the prediction because a big spender’s month varies by more rupees. Statisticians call a spread that changes like this heteroscedasticity. Residual plots are the standard way to spot both a bend and a fan.4

A bend needs a feature, not a new model

The residuals show a bend at 45 days. What should Farah change before the model sizes Joseph’s budget?

Keep the straight line.

The overall total is right, so the main budget is fine. Any segment budget by days since the last order is off by about 7%, high or low.

Switch to a tree model, covered later in this module.

Finds the bend without being told where it is. Weights no longer read as rupees per unit, and there is more to tune and check.

Predict the log of spend.

Tames the fan, but predictions turned back into rupees are medians, so the budget comes out short. It doesn’t fix the bend either.

Why this choice

The line is right about everything except one shape it can’t draw. A hinge feature, zero until day 45 and growing after it, lets the line bend there: the gap weight becomes about −₹6 a day and the new one about +₹6, cancelling after day 45. That fix keeps the model readable.

Two cases change the choice. Many bends, or effects that depend on each other, point to trees. If Joseph starts using single predictions, such as one voucher per customer, the fan matters more than the total, and a log target or a per-customer error check earns its place.

Try it yourself

Run this in a free Colab or Kaggle after the first block; it takes seconds.

Python
resid = y_test - pred
gap_test = X_test[:, 1]

band = np.minimum(gap_test // 15, 5)                # 0 = days 0–14, ..., 5 = days 75–90
print("mean residual by gap band:", [round(resid[band == k].mean()) for k in range(6)])

for lo, hi in [(0, 500), (500, 1_000), (1_000, 2_000), (2_000, 5_000)]:
    inside = (pred >= lo) & (pred < hi)
    print(f"prediction ₹{lo}–{hi}: residual spread", round(resid[inside].std()))
print("negative predictions:", int((pred < 0).sum()))

def with_bend(X):
    return np.column_stack([X, np.maximum(X[:, 1] - 45, 0)])

bent = LinearRegression().fit(with_bend(X_train), y_train)
print("weights:", bent.coef_.round(2), "intercept:", round(bent.intercept_, 1))
resid_b = y_test - bent.predict(with_bend(X_test))
print("mean residual by gap band:", [round(resid_b[band == k].mean()) for k in range(6)])

# Optional picture (needs matplotlib, which Colab has):
# from sklearn.metrics import PredictionErrorDisplay
# PredictionErrorDisplay.from_predictions(y_test, pred, subsample=2_000, random_state=42)

Expected values worked out from the rule, not a measured run:

  • Straight line by band: about 45, 0, −45, −45, 0, 45, give or take ₹10.
  • Residual spread: about 150–200 in the lowest band, rising to about 1,500 in the highest.
  • Negative predictions: a handful, roughly 10 to 30.
  • With the bend: weights near 0.70, −6, 100 and 6, intercept near 300, and every band near 0.

Where this shows up

Joseph’s next question is who will stop buying. A straight line fitted to a yes-or-no label gives values below 0 and above 1. Logistic regression bends the line into a probability.

Common mistakes

  • Comparing raw weights across features. Each is in its own units. Compare effects of a typical change.
  • Judging the fit by RMSE or R² alone. The bend cost ₹30 lakh in one segment and ₹1 of RMSE. Group the residuals.
  • Losing the column order. The weights only mean something in the order they were fitted. Save the order with the model, as Models as functions warned.
  • Clipping negative predictions at zero without asking why. Here they came from the missing bend.
  • Predicting the log of spend for a total. It predicts medians, and the budget comes out short.

Check your understanding

Check yourselfAnswer in your head first, then reveal
Farah’s line scores an R² of 0.65 on the test set. Joseph asks whether that means it is right 65% of the time. What should she say?Show answerHide answer
No. R² compares squared error with predicting the average for everyone: the line removes about 65% of that error. It says nothing about how often a single prediction is close.
Check yourselfAnswer in your head first, then reveal
A teammate says days since the last order barely matters, because its weight is only −3 while the app weight is 100. What is wrong with that?Show answerHide answer
The weights are in different units. A typical change of 26 days moves the prediction by about ₹78, more than the app flag’s ₹49. Compare the effect of a typical change, not raw weights.
Check yourselfAnswer in your head first, then reveal
After adding the days-past-45 feature, the test RMSE drops by only about ₹1. Was the change worth it?Show answerHide answer
Yes. The bend hardly moves an average over all customers, but it overpredicted the 30–60-day group by about ₹30 lakh in total. Segment budgets now line up, and the negative predictions are gone.
Check yourselfAnswer in your head first, then reveal
The total of Farah’s test predictions matches the actual total within 1%, yet single predictions for big spenders miss by ₹1,500. Can both be true?Show answerHide answer
Yes. The misses have a mean near zero, so they cancel in a total. Their spread grows with the prediction, so any one big spender’s prediction is rough.

Summary

  1. Linear regression fits one weight per feature by least squares; scikit-learn’s LinearRegression does it exactly, and squared error aims at the mean a budget total needs.
  2. Score it on held-out customers against baselines: here about ₹550 RMSE against ₹650 for Joseph’s rule and ₹930 for the average, R² about 0.65.
  3. Each weight is rupees per unit of its feature with the others held fixed; compare features by the effect of a typical change.
  4. Group the residuals by feature and by prediction: a V shows a bend, a fan shows a spread that grows, and neither moves RMSE much.
  5. A bend at a known point needs one new feature, not a new model; many bends, or a per-customer use, point elsewhere.

Report a mistake

Tell us what’s wrong in this lesson and we’ll fix it.