Fitting lines with least squares
Find the straight line that best fits a set of measurements, compute its slope and intercept by hand and in Python, and use residuals to judge whether a line was the right model.
Lesson 4 of 6 · 35 min · Self-paced · Free
Why fit a line?
Many engineering relationships are, at least approximately, straight lines. A spring's extension is proportional to the load on it (Hooke's law). A temperature sensor's output voltage rises steadily with temperature. A wheel's distance travelled grows with the number of encoder counts. If you can find the line, you can calibrate a sensor, estimate a physical constant such as a spring's stiffness, and predict values you did not measure.
Real measurements never sit exactly on a line, because of noise. So the question becomes: which line fits best, and what does "best" mean?
The data
A spring is hung from a hook and loaded with known weights. Its extension is measured each time (made-up data for illustration):
load (N) 0.0 1.0 2.0 3.0 4.0 5.0
extension (mm) 0.1 2.1 3.9 6.2 7.9 10.1We want a line of the form
y = a + b · xwhere x is the load, y is the extension, b is the slope (millimetres per newton) and a is the intercept (the extension at zero load).
Residuals and "least squares"
For any candidate line, each data point has a residual: the measured value minus the value the line predicts.
residual = y_measured − (a + b · x)A good line has small residuals. We cannot just add them up, because positive and negative residuals would cancel, so a terrible line could score zero. Instead we square each residual and add them. The least-squares line is the one that makes this sum of squared residuals as small as possible. Squaring also punishes large misses heavily, which is usually what we want, though it means a single wild outlier can tug the line noticeably.
Using calculus, one can show that the best slope and intercept are:
x̄ = mean of x, ȳ = mean of y
Σ (x − x̄)(y − ȳ)
b = ------------------
Σ (x − x̄)²
a = ȳ − b · x̄You do not need the calculus to use these. Read the slope formula as: "how much do x and y move together, divided by how much x moves on its own." The intercept formula guarantees that the line passes through the point (x̄, ȳ), the centre of the data.
Working it by hand
x̄ = (0 + 1 + 2 + 3 + 4 + 5) / 6 = 2.5 and ȳ = 30.3 / 6 = 5.05.
x y x − x̄ y − ȳ (x − x̄)(y − ȳ) (x − x̄)²
0.0 0.1 −2.5 −4.95 12.375 6.25
1.0 2.1 −1.5 −2.95 4.425 2.25
2.0 3.9 −0.5 −1.15 0.575 0.25
3.0 6.2 0.5 1.15 0.575 0.25
4.0 7.9 1.5 2.85 4.275 2.25
5.0 10.1 2.5 5.05 12.625 6.25
sum = 34.850 sum = 17.50So b = 34.85 / 17.5 ≈ 1.991 mm/N and a = 5.05 − 1.991 × 2.5 ≈ 0.071 mm.
The spring stretches about 1.99 mm for every newton. Its stiffness is the inverse: k ≈ 1 / 1.991 ≈ 0.502 N/mm, or about 502 N/m. The small intercept, 0.07 mm, is close to zero, as Hooke's law predicts; it may come from how the zero reading was taken.
The same calculation in Python
import statistics
# Made-up data for illustration: a spring stretched by hanging loads
load = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] # newtons
extension = [0.1, 2.1, 3.9, 6.2, 7.9, 10.1] # millimetres
def fit_line(xs, ys):
"""Least-squares slope and intercept for y = a + b·x."""
x_bar = statistics.mean(xs)
y_bar = statistics.mean(ys)
sxy = sum((x - x_bar) * (y - y_bar) for x, y in zip(xs, ys))
sxx = sum((x - x_bar) ** 2 for x in xs)
b = sxy / sxx
a = y_bar - b * x_bar
return a, b
a, b = fit_line(load, extension)
print(f"extension ≈ {a:.3f} + {b:.3f} × load")
print("load measured predicted residual")
for x, y in zip(load, extension):
predicted = a + b * x
print(f"{x:4.1f} {y:8.2f} {predicted:9.3f} {y - predicted:8.3f}")Output:
extension ≈ 0.071 + 1.991 × load
load measured predicted residual
0.0 0.10 0.071 0.029
1.0 2.10 2.063 0.037
2.0 3.90 4.054 -0.154
3.0 6.20 6.046 0.154
4.0 7.90 8.037 -0.137
5.0 10.10 10.029 0.071Python 3.10 and later also include this calculation as statistics.linear_regression(load, extension), which returns the same slope and intercept. Writing it yourself once is the best way to understand what the library does.
Residuals tell you if a line was the right idea
The residuals above are small (about 0.15 mm at most) and scattered above and below zero with no obvious pattern. That is what you hope to see: the line captures the relationship and what is left looks like noise.
Now look at a sensor whose output curves upward (made-up data: y = x² exactly):
import statistics
# Made-up data for illustration: a sensor whose output curves upward
x = [0, 1, 2, 3, 4, 5]
y = [0.0, 1.0, 4.0, 9.0, 16.0, 25.0]
fit = statistics.linear_regression(x, y)
residuals = [yi - (fit.intercept + fit.slope * xi) for xi, yi in zip(x, y)]
print(f"slope {fit.slope:.2f}, intercept {fit.intercept:.2f}")
print([round(r, 2) for r in residuals])Output:
slope 5.00, intercept -3.33
[3.33, -0.67, -2.67, -2.67, -0.67, 3.33]The residuals form a clear pattern: positive at both ends, negative in the middle, a "smile". A pattern in the residuals means the model is wrong, not just noisy. Here, a straight line is the wrong shape.
A popular single-number score is R², the fraction of the variation in y that the line accounts for (1 means a perfect fit). For the spring, R² ≈ 0.999. For the curved sensor, R² ≈ 0.92, which sounds impressive, yet the line is plainly the wrong model. Always look at the residuals, not just R².
Do not extrapolate carelessly
The fit tells you about loads between 0 and 5 N. Using it to predict the extension at 50 N assumes the spring keeps behaving the same way far outside anything you tested, but real springs eventually stretch permanently or their coils touch. Treat predictions outside your data range as guesses, and test them.
Recap
- A residual is measured minus predicted. The least-squares line minimises the sum of squared residuals.
- Slope b = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)²; intercept a = ȳ − b · x̄. The line passes through (x̄, ȳ).
- The slope often has a physical meaning, such as the inverse of a spring's stiffness.
- Random-looking residuals suggest a good model; patterned residuals suggest the wrong one, whatever R² says.
- Be cautious about predicting outside the range of your data.
Project
Calibrate a rubber band
You need a rubber band, a small bag, coins of one type, a ruler, paper and Python. Hang the bag from the rubber band over the edge of a table, with the ruler held vertically beside it.
- Record the length of the band with 0, 2, 4, 6, 8 and 10 coins in the bag. Repeat the whole series three times and use the mean length at each load.
- Using your
fit_linefunction, fit length against number of coins and print the residuals. - Do the residuals look random, or is there a pattern? Rubber bands are often not linear, so a pattern is a real finding, not a failure.
- Try fitting only the first four loads. Does the slope change?
Keep heavy loads small, and keep faces away from a stretched band in case it snaps.
Deliverables
- A table of mean band length for each load
- Your fitted slope and intercept, with units
- A printed list of residuals and two or three sentences on whether a straight line suits the band
Knowledge check
Check your understanding
Go further
- Simple linear regression — Wikipedia ↗
Derivation of the slope and intercept formulas and how to estimate their uncertainty.
- Least squares — Wikipedia ↗
The history and wider uses of the least-squares idea beyond straight lines.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.