Lesson 2 · Learning from data
Linear regression
The problem
In the last lesson you trained a line by hand on ten deliveries. Two things were missing.
- The model used one feature, distance. But traffic matters too: delivery C (3 km in heavy traffic) took 24 minutes, much longer than its distance suggests.
- Training was slow. Nudging one knob at a time took five turns for one knob, and stopped short of the best answer.
This lesson fixes both. The model uses every feature at once. And for this kind of model there's a formula that finds the best parameters in one step.
A linear model
With two features, the natural guess is a weighted sum plus a constant:
A model that predicts with a weighted sum of the features plus a constant is a linear model. The weights and say how much each feature adds. The constant is the intercept: the prediction when every feature is 0. It's also called the bias.
Worked example
A linear model with w = (4, 6) and b = 7
A new order is 5 km away, in light traffic (level 1). Its features are .
The maths
For an example with features , a linear model predicts
Read it as: multiply each feature by its weight, add them up, and add the intercept. With one feature, the model is a line: is its slope and is where it crosses the minutes axis. With two features it's a flat sheet over the (km, traffic) floor. With more, you can't draw it, but the sum works the same way.
Linear regression is the job of choosing and from data. First we need to say exactly what "best" means.
Residuals and the mean squared error
For each example, the residual is the true value minus the prediction: . The last lesson called it the miss.
The loss from the last lesson averages the squared residuals. Its name is the mean squared error (MSE):
A squared number is the area of a square. So draw each residual as a square, with the residual as its side. The MSE is the total area of the squares, divided by the number of examples.
Line: minutes = 1.00 × km + 20.0
Total area of the squares: 246.5 · biggest square: delivery 9 (39% of the area)
Mean squared error = 246.5 ÷ 10 = 24.65
The best line's mean squared error is 3.64.
Things to notice:
- The line starts too flat, so the shortest and longest trips have the biggest squares. Tilt the line up and both shrink fast.
- Double a residual and its square gets four times bigger. One far-off delivery can own most of the total area.
- "Snap to the best line" shows the line with the smallest total area: MSE 3.64. You can get close by hand, but not lower.
Predict first
Model A misses four deliveries by 2, 2, 2 and 2 minutes. Model B misses by 0, 0, 0 and 8. Which has the lower mean squared error?
When one delivery goes badly wrong
The predict question hints at a weakness. Suppose one driver got lost, and a 4.2 km trip took 60 minutes instead of 30. That delivery says nothing about normal trips, but its square is huge, so the MSE line moves a long way to get closer to it.
There's another loss that's less touchy. The mean absolute error (MAE) averages the size of each residual, ignoring its sign:
For model A above, the MAE is 2. For model B, it's as well. The MAE counts a residual of 8 as 8, not 64.
Drag the lost delivery up and watch both best lines.
Delivery 4 (4.2 km) took 30.1 minutes
MSE line (solid): 3.91 min per km + 10.9
MAE line (dashed): 3.89 min per km + 11.0
Things to notice:
- At 60 minutes, the MSE line's slope jumps from 3.9 to 6.0 minutes per km. One delivery changed the shop's estimate for every trip.
- The MAE line doesn't move at all. It goes through the middle of the other deliveries and treats the lost one as one miss among ten.
- With the original data, the two lines are almost the same.
So why use the MSE at all? Two reasons. Its best weights have an exact formula, which comes next. And it's smooth: its slope changes gradually, which gradient descent (Lesson 3) needs. The MAE has a corner wherever a residual is 0.
A rule of thumb: use MSE when big mistakes cost much more than small ones, and you trust your data. Use MAE when the data has occasional wild values you can't remove. Report the MAE to people either way, because it's in minutes. The MSE is in minutes squared.
Least squares: the best weights in one step
Go back to the Transformations lesson. There, two deliveries gave two equations in two unknowns:
That's a linear system. Each equation is a line of weights that fits one delivery exactly, and the answer is where the lines cross. The figure below draws the same picture, then adds more deliveries.
2 deliveries: 2 lines, 2 unknowns. Every line passes through (4, 6), so there is one exact answer.
Least squares: w₁ = 4.00, w₂ = 6.00
A, B and C are the three deliveries from the Vectors lesson. The others are made up: 4 minutes per km and 6 per traffic level, plus a few minutes of noise.
Things to notice:
- With 2 deliveries there are 2 equations and 2 unknowns, so you can solve.
- Delivery C also passes through (4, 6), because A, B and C were made up to fit.
- With 5 or more real-looking deliveries, the lines don't share a point. There are more equations than unknowns, so you can't solve. You fit instead.
- As deliveries are added, the least-squares point settles near (4, 6), the rule that made the data.
Choosing the weights with the smallest squared error is called least squares. Fitting a linear model this way is linear regression.
The formula
Put the features in a matrix , one row per example. Add a column of ones, so the intercept becomes one more weight. Then the predictions for every example at once are the matrix–vector product .
The MSE is a bowl-shaped function of the weights. At the bottom of the bowl, its gradient is zero. Setting it to zero gives a small linear system, the normal equations:
Here is the transpose of . is a square matrix with one row per weight, whatever the number of examples. So 300 deliveries and 3 weights give a 3×3 system.
Worked example
Least squares on three deliveries
Deliveries of 1, 2 and 3 km took 10, 14 and 15 minutes. The model is . With a column of ones for :
Read the formula back with the picture. Each row of is one delivery's line in weight space. and add up all those lines into one small system (2×2 here). Its answer is the point that's closest to all of the lines at once, measured by squared error.
DeeperWhere the normal equations come fromSet the slope to zero in each direction. Two facts about the residuals drop out. · 4 min
Take one feature. The loss is a function of two numbers, and :
It's a bowl: a sum of squares, each one a parabola in and . At the bottom, the slope is zero in both directions. So set both partial derivatives to zero. Write for the residuals.
The slope in the direction. By the chain rule, . Setting it to zero says the residuals add up to 0. Too-high and too-low predictions balance out.
The slope in the direction. . Setting it to zero says . The residuals don't lean with distance. If long trips were all under-predicted, tilting the line would help, so you weren't at the bottom yet.
Check both with the worked example. The residuals are , and . They add up to 0. And .
In matrix form. Both conditions together say : each column of has a dot product of 0 with the residuals. Substitute :
These are the normal equations. The same argument works for any number of features: one condition per column of .
Putting it together: all 300 deliveries
The shop has 300 deliveries with six features each: distance, traffic, rain, the hour it was sent, the number of items and the driver. The figure fits a linear model with least squares, for three sets of features, and plots each delivery's prediction against the time it took.
minutes = 4.10 × km + 6.45 × traffic + 6.74
MSE 18.6 · MAE 3.41 minutes
Dots on the dashed line are perfect predictions. Dots above it took longer than predicted.
Things to notice:
- Distance alone leaves a wide cloud: MSE 71.3. Adding traffic pulls the dots in towards the line: MSE 18.6.
- With distance and traffic, the weights are 4.10 minutes per km and 6.45 per traffic level. The Vectors lesson's guess of (4, 6) comes back, now fitted.
- With all six features, rain gets 4.48 minutes, and the driver gets about 0. That's right: in this data, the driver makes no difference.
- The hour gets a small negative weight. The real effect is a bump at 18:00–19:00, and a straight line in the hour can't make a bump. Turning the hour into a "rush hour: yes or no" feature fixes that. That's feature engineering, covered later in the course.
In scikit-learn
scikit-learn is the standard Python library for classical machine learning. Every model in it is an estimator, used in three steps. Make the model object, call .fit(X, y) to train it, then call .predict(X) to use it. Learned parameters end in an underscore, like .coef_.
df = deliveries()
print(df.head(3)) # distance_km traffic rain hour items driver minutes late
features = ["distance_km", "traffic"]
X = df[features].to_numpy() # one row per delivery shape (300, 2)
y = df["minutes"].to_numpy() # the labels shape (300,)
model = LinearRegression() # an estimator: make it, then .fit, then .predict
model.fit(X, y)
print(model.coef_, model.intercept_) # [4.10 6.45] 6.74: minutes per km, per traffic level, fixed part
pred = model.predict(X)
print(mean_squared_error(y, pred)) # 18.58: the average squared miss, in minutes²
print(mean_absolute_error(y, pred)) # 3.41: the average miss, in minutes
new = np.array([[5.0, 1.0]]) # a new order: 5 km, light traffic
print(model.predict(new)) # [33.68] minutes[4.09746521 6.44776981] 6.74253234964241
18.584274874606034
3.4116743998033074
[33.67762818]X has one row per delivery and one column per feature, so its shape is (300, 2). y holds the 300 labels. .coef_ holds the weights in the same order as the columns, and .intercept_ holds . The model's typical miss is 3.4 minutes (the MAE). The new 5 km order in light traffic gets 33.7 minutes, close to the 33 from the worked example's guessed weights.
In PyTorch
The same fit in PyTorch shows what scikit-learn does inside. Turn the data into tensors, add a column of ones, and solve the normal equations with torch.linalg.solve. Then load the answer into an nn.Linear layer and score it with nn.MSELoss.
Xt = torch.tensor(X) # float64, from NumPy shape (300, 2)
yt = torch.tensor(y) # shape (300,)
# Add a column of ones, so the intercept is one more weight.
A = torch.cat([Xt, torch.ones(len(Xt), 1, dtype=Xt.dtype)], dim=1) # (300, 3)
# The normal equations: (AᵀA) w = Aᵀy, a 3×3 linear system.
w = torch.linalg.solve(A.T @ A, A.T @ yt) # (3,): w1, w2, b
w_lstsq = torch.linalg.lstsq(A, yt.unsqueeze(1)).solution.squeeze(1) # the same, more stable
print(w) # tensor([4.0975, 6.4478, 6.7425])
assert torch.allclose(w, w_lstsq)
# The same model as a layer: nn.Linear holds the weights and the intercept (its bias).
linear = nn.Linear(2, 1, dtype=torch.float64)
with torch.no_grad():
linear.weight.copy_(w[:2].unsqueeze(0)) # (1, 2)
linear.bias.copy_(w[2:]) # (1,)
loss_fn = nn.MSELoss() # mean squared error between two tensors of the same shape
with torch.inference_mode():
mse = loss_fn(linear(Xt).squeeze(1), yt) # (300, 1) → (300,) to match yt
print(mse.item()) # 18.58, as scikit-learntensor([4.0975, 6.4478, 6.7425], dtype=torch.float64)
18.58427487460603The weights and the MSE match scikit-learn's to every decimal shown. A few things to notice in the code:
torch.linalg.lstsq(A, y)solves the least-squares problem directly, without forming . It's more accurate when features nearly copy each other (see the aside below), so prefer it in real work. It takes the labels as a matrix with one column, so the code adds one with.unsqueeze(1).nn.Linear(2, 1)is a linear model: itsweight(shape (1, 2)) holds , and itsbiasholds . Setting them insidetorch.no_grad()keeps autograd out of it.nn.MSELoss()computes the mean squared error. It's the layer form ofF.mse_loss, which the next lesson uses to train this same model by gradient descent. The prediction has shape (300, 1), so.squeeze(1)makes it matchyt.torch.inference_mode()turns off gradient tracking while we only evaluate.
DigressionWhen the exact answer is a bad ideaMillions of features, or features that copy each other. Both push you towards gradient descent. · 2 min
The normal equations look like the end of the story. In practice there are two problems.
Too many features. has one row and one column per weight. With 1,000 features it's 1,000 × 1,000, and solving it takes about , a billion, steps. Models with millions of weights, like neural networks, can't be solved this way. And most models aren't linear, so they have no formula at all.
Features that nearly copy each other. Suppose the table had distance in km and also distance in miles. The two columns carry the same information, so is a singular matrix, or close to one.
So there's no single best answer. The solver may return huge weights that cancel out: per km and per mile, say. The predictions still look fine, but the weights mean nothing.
The fixes come in the next few lessons. Gradient descent finds the bottom of the bowl in small steps, for any model and any number of weights. Regularisation adds a small penalty on big weights, which settles the copied-features problem.
Common misconceptions
"A linear model can only fit straight lines." It's linear in the weights, not in the raw inputs. Add as a feature and the same least squares fits a curve. The course comes back to this with polynomial features.
"A bigger weight means a more important feature." A weight depends on the feature's units. Measure distance in metres instead of km and its weight drops from 4.1 to 0.0041, though nothing about the deliveries changed. Compare weights only after putting features on the same scale (feature scaling).
"An MSE of 18.6 means the model is off by 18.6 minutes." The MSE is in minutes squared. The MAE, 3.4 minutes, is the typical miss. The square root of the MSE, about 4.3 minutes, is also in minutes. Big misses push it above the MAE.
"Least squares finds the true rule." It finds the best fit to this data. With five noisy deliveries, the weights came out as (3.60, 6.62), not (4, 6). More data brings them closer.
Recap
- A linear model predicts : a weighted sum of the features plus the intercept.
- A residual is the true value minus the prediction. The MSE averages the squared residuals, so one big miss counts a lot.
- The MAE averages the residuals' sizes. One wild example moves its best line much less.
- Least squares picks the weights with the smallest MSE in one step, by solving the normal equations . Fitting a linear model this way is linear regression.
- On the 300 deliveries, least squares finds about 4.1 minutes per km and 6.4 per traffic level.
- Code names: scikit-learn's
LinearRegression(an estimator:.fit,.predict,.coef_,.intercept_),mean_squared_errorandmean_absolute_error; PyTorch'storch.linalg.solve,torch.linalg.lstsq,nn.Linear,nn.MSELossandtorch.inference_mode.