Show contents
Chapter 2 of 7 · 20 min
Linear regression
By the end of this chapter, you'll be able to
- Fit a line to data with numpy
- Measure the error of a regression model (MAE and MSE)
- Explain and program gradient descent
- Choose a learning rate that converges
A line that summarises the data
We look for a line yield = a × rain + b: a is the slope (how much the yield rises per millimetre of rain), b the intercept. These are the model's two parameters. np.polyfit(x, y, 1) computes the best line (a degree-1 polynomial):
import numpy as np
# Season's rain (mm) and millet yield (tonnes per hectare), simulated data
rain = np.array([380, 420, 450, 500, 540, 600, 650, 700])
crop_yield = np.array([0.62, 0.70, 0.74, 0.83, 0.88, 0.97, 1.03, 1.12])
a, b = np.polyfit(rain, crop_yield, 1)
print(f"yield = {a:.5f} × rain + {b:.3f}")
print(f"Forecast for 550 mm: {a * 550 + b:.2f} t/ha")
yield = 0.00151 × rain + 0.059
Forecast for 550 mm: 0.89 t/ha
The model learned that about 100 mm more rain brings 0.15 t/ha more. The data is simulated for the example, with plausible orders of magnitude for the Sahel.
Measure the error
For each season, the error (or residual) is the gap between the prediction and the real value. We summarise them with:
- the MAE (mean absolute error): the mean of the gaps in absolute value, in the data's unit;
- the MSE (mean squared error): the mean of the squared gaps, which heavily penalises large errors. This is what regression minimises.
import numpy as np
rain = np.array([380, 420, 450, 500, 540, 600, 650, 700])
crop_yield = np.array([0.62, 0.70, 0.74, 0.83, 0.88, 0.97, 1.03, 1.12])
a, b = np.polyfit(rain, crop_yield, 1)
predictions = a * rain + b
errors = predictions - crop_yield
print(np.round(errors, 3))
print("MAE:", round(float(np.abs(errors).mean()), 4), "t/ha")
print("MSE:", round(float((errors ** 2).mean()), 6))
[ 0.014 -0.005 0. -0.014 -0.004 -0.003 0.013 -0.001]
MAE: 0.0068 t/ha
MSE: 7.7e-05
On average, the model is off by less than 0.01 t/ha on these seasons. That is very little, but it is measured on the data used to draw the line: the chapter “Evaluate a model” shows why this figure should be treated with caution.
How the machine finds the line
polyfit uses an exact formula. Most models have none: you start from arbitrary parameters and adjust them step by step to bring the error down. This is gradient descent. At each step:
- compute the error with the current parameters;
- compute the gradient: in which direction, and how strongly, each parameter raises the MSE;
- move each parameter a small step in the opposite direction. The step size is the learning rate.
For the descent to go well, we centre the rain: x = (rain - 500) / 100 gives values around 0, of an order of magnitude close to 1.
import numpy as np
rain = np.array([380, 420, 450, 500, 540, 600, 650, 700])
crop_yield = np.array([0.62, 0.70, 0.74, 0.83, 0.88, 0.97, 1.03, 1.12])
x = (rain - 500) / 100
a, b = 0.0, 0.0
rate = 0.1
for step in range(101):
error = a * x + b - crop_yield
if step in (0, 1, 2, 5, 20, 100):
print(f"step {step:>3}: a = {a:.4f} b = {b:.4f} MSE = {(error ** 2).mean():.5f}")
a -= rate * 2 * (error * x).mean()
b -= rate * 2 * error.mean()
print(np.round(np.polyfit(x, crop_yield, 1), 4))
step 0: a = 0.0000 b = 0.0000 MSE = 0.76769
step 1: a = 0.0858 b = 0.1723 MSE = 0.44484
step 2: a = 0.1404 b = 0.3049 MSE = 0.26464
step 5: a = 0.2024 b = 0.5511 MSE = 0.06522
step 20: a = 0.1616 b = 0.8001 MSE = 0.00035
step 100: a = 0.1514 b = 0.8158 MSE = 0.00008
[0.1514 0.8158]
The MSE drops at each step, then levels off: the parameters have converged to those given by polyfit. Here, a is the yield gain for 100 mm more, and b the forecast yield for 500 mm. The formulas 2 * (error * x).mean() and 2 * error.mean() are the derivatives of the MSE with respect to a and b.
At step 100, the parameters no longer move: the descent has converged.
Text description of the animation
- We start from arbitrary parameters: a flat line, at zero.
- Step 0: the line predicts 0 everywhere, the error is huge.
- Both parameters move in the direction that lowers the error.
- After 5 steps, the error has been divided by more than 10. a has even overshot its final value.
- At step 20, the line is almost in place.
- At step 100, the parameters no longer move: the descent has converged.
Mini-lab: tune the learning ratePython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the price of land
In a neighbourhood, plots sold at areas (m²) [200, 250, 300, 400, 500] for prices (millions of FCFA) [6.1, 7.4, 9.2, 11.8, 15.1]. Fit a line with polyfit, display the forecast price for 350 m², then the model's MAE on these sales, rounded to 2 decimal places.
Hint 1
a, b = np.polyfit(area, price, 1), then a * 350 + b.Hint 2
np.abs(predictions - price).mean().Show the solution and common mistakes
import numpy as np
area = np.array([200, 250, 300, 400, 500])
price = np.array([6.1, 7.4, 9.2, 11.8, 15.1])
a, b = np.polyfit(area, price, 1)
print(f"Forecast price for 350 m²: {a * 350 + b:.2f} million")
predictions = a * area + b
print(f"MAE: {np.abs(predictions - price).mean():.2f} million")
Forecast price for 350 m²: 10.52 million
MAE: 0.14 million
The slope a is the price of one extra square metre: about 30,000 FCFA here.
Common mistakes:
- Swapping the arguments of
polyfit:np.polyfit(price, area, 1)would predict the area from the price. - Predicting far outside the data (a 5,000 m² plot): nothing guarantees the link stays linear so far from the examples. This is an extrapolation, always risky.
Summary
- 1Linear regression looks for the line y = a × x + b that minimises the mean squared error (MSE).
- 2The MAE measures the average error in the data's unit; the MSE penalises large errors.
- 3Gradient descent adjusts the parameters step by step, in the direction that lowers the error.
- 4A learning rate that is too large makes the descent diverge; centring the data helps it converge.
- 5A prediction far from the training data (extrapolation) is unreliable.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.