Lesson 1
Line of best fit
The line of best fit through points on a graph, drawn by eye and then chosen by a criterion: the residuals, the sum of their squares, and a search by brute force for the line that minimises it.
A line of best fit is the straight line that best represents a set of measurements plotted on a graph, and drawing one by eye, with a ruler, is how most people first fit a model to data. This lesson introduces the residuals that measure how far a line misses the data, the choice of what to minimise, and a search by brute force for the line that minimises the sum of the squared residuals, the least-squares line.
Hooke’s law #
A spring stretches in proportion to the force on it, as long as it is not stretched too far: this is Hooke’s law. A familiar experiment tests it by hanging masses from a spring and measuring its length with a ruler. A mass \(x\) pulls on the spring with the force \(xg\), where \(g\) is the acceleration due to gravity, and stretches it by \(xg/k\), where \(k\) is the spring constant, the force needed to stretch the spring by a unit length. The length of the spring is therefore
where \(L_0\) is its natural length. A graph of \(y\) against \(x\) is a straight line, whose intercept (its value at \(x = 0\)) is the natural length, and whose gradient is \(g/k\), from which the spring constant follows.
The following code simulates the lengths measured with ten masses from 50 g to 500 g, for a spring of natural length 120 mm and spring constant 40 N/m. Each length has a random error drawn from the Gaussian (or normal) distribution, the bell-shaped distribution of many errors of measurement, with a standard deviation (the typical size of an error) of 2 mm. Unlike a real experiment, a simulation knows the true values, so that a method of fitting can be judged by how close it comes to them.
import numpy as np
import matplotlib.pyplot as plt
# Colours and greys for Matplotlib plots.
INK, BLUE, RED, GREEN = "black", "#0072B2", "#D55E00", "#009E73"
DARK_GREY, GREY, LIGHT_GREY = "0.4", "0.6", "0.85"
plt.rcParams.update({"figure.dpi": 120, "axes.spines.top": False,
"axes.spines.right": False})
rng = np.random.default_rng(2)
g = 9.81 # acceleration due to gravity, m.s-2
L0, k = 120.0, 40.0 # natural length (mm) and spring constant (N.m-1)
sigma = 2.0 # standard deviation of the errors, mm
x = np.linspace(0.05, 0.5, 10) # masses, kg
y = L0 + 1000 * g / k * x + sigma * rng.standard_normal(x.size) # lengths, mm
print("Mass/g Length/mm")
for x_i, y_i in zip(x, y):
print(f"{1000 * x_i:6.0f} {y_i:9.1f}")
Mass/g Length/mm
50 132.6
100 143.5
150 156.0
200 164.2
250 184.9
300 195.9
350 205.2
400 219.6
450 230.9
500 241.5
The fixed seed of the random numbers, 2, makes every run give the same errors, and the factor of 1000 converts the gradient \(g/k\) from metres per kilogram to millimetres per kilogram.
Gradient and intercept #
Figure 1.1 shows the measurements, with two lines drawn through them by eye, as two different students might draw them. The usual way to measure the gradient of such a line is to pick two points on it, far apart, so that the errors of reading them matter less, and to divide the difference of their \(y\) values (the rise) by the difference of their \(x\) values (the run). The first line passes through (0.1 kg, 145 mm) and (0.45 kg, 231 mm), and the second through (0.1 kg, 143 mm) and (0.45 kg, 233 mm):
def line_through(x_a, y_a, x_b, y_b):
"""Return the intercept and gradient of the line through (x_a, y_a) and (x_b, y_b)."""
gradient = (y_b - y_a) / (x_b - x_a)
return y_a - gradient * x_a, gradient
eye_lines = {"First line": line_through(0.10, 145.0, 0.45, 231.0),
"Second line": line_through(0.10, 143.0, 0.45, 233.0)}
for name, (intercept, gradient) in eye_lines.items():
print(f"{name}: intercept {intercept:.1f} mm, gradient {gradient:.1f} mm.kg-1, "
f"spring constant {1000 * g / gradient:.1f} N.m-1")
First line: intercept 120.4 mm, gradient 245.7 mm.kg-1, spring constant 39.9 N.m-1
Second line: intercept 117.3 mm, gradient 257.1 mm.kg-1, spring constant 38.1 N.m-1
The first line gives a natural length of 120.4 mm and a spring constant of 39.9 N/m, close to the 120 mm and 40 N/m of the simulation; the second gives 117.3 mm and 38.1 N/m.
x_line = np.array([0, 0.55])
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.plot(x, y, "o", color=INK, ms=4, zorder=3)
for (name, (intercept, gradient)), colour, style in zip(eye_lines.items(), [BLUE, RED], ["-", "--"]):
ax.plot(x_line, intercept + gradient * x_line, color=colour, ls=style, lw=1.5, label=name)
ax.plot([0.10, 0.45, 0.45], [145, 145, 231], color=GREY, lw=1)
ax.text(0.275, 139, "run = 0.35 kg", ha="center", va="top", color=DARK_GREY, fontsize=9)
ax.text(0.46, 188, "rise = 86 mm", ha="left", va="center", color=DARK_GREY, fontsize=9)
ax.set_xlabel("$x$ / kg")
ax.set_ylabel("$y$ / mm")
ax.legend(loc="upper left", frameon=False)
plt.show()
On the scale of the graph, both lines look reasonably good; a third person might draw a third, equally reasonable line. Choosing between them needs a way of measuring objectively how well a line fits.
Residuals #
In school, a straight line is written \(y = mx + c\). This tutorial writes it \(y = \theta_1 + \theta_2 x\), with the intercept \(\theta_1\) and the gradient \(\theta_2\), because the same notation will serve models with any number of parameters. The residual of the \(i\)th of \(N\) measurements, \((x_i, y_i)\), is its vertical distance from the line, the measured value minus the value of the line at the same \(x\) (“observed minus calculated”):
The residuals are measured vertically, and not at right angles to the line, because only the lengths have appreciable errors: the masses are known, as long as they are accurately made. This is the first of several assumptions behind the methods of this tutorial, that the errors are in \(y\) alone; a later lesson treats data with errors in both variables. Figure 1.2 shows the residuals of the measurements from the two lines drawn by eye.
fig, ax = plt.subplots(figsize=(6.4, 3.0))
ax.axhline(0, color=GREY, lw=0.8)
for (name, (intercept, gradient)), colour, marker, shift in zip(
eye_lines.items(), [BLUE, RED], ["o", "s"], [-0.004, 0.004]):
r = y - (intercept + gradient * x)
ax.vlines(x + shift, 0, r, color=colour, lw=1.2)
ax.plot(x + shift, r, marker, color=colour, ms=4, label=name)
ax.set_xlim(0, 0.55)
ax.set_xlabel("$x$ / kg")
ax.set_ylabel("$r_i$ / mm")
ax.legend(loc="lower left", frameon=False, fontsize=9)
plt.show()
The residuals of the first line scatter above and below zero with no trend, as the random errors of the measurements should. Those of the second line are mostly positive at small masses and negative at large ones: the line is too steep, starting below the measurements and finishing above them. On a graph of the residuals, a difference too small to see on a graph of the data stands out.
Criteria #
To decide which of two lines fits better, the residuals must be combined into a single measure of goodness-of-fit, smallest for the best line. There are three obvious candidates, described below.
The sum of the residuals, \(\sum_i r_i\), fails at once, because positive and negative residuals cancel. Every line through the centroid of the data, the point \((\bar{x}, \bar{y})\) whose coordinates are the means of the \(x_i\) and of the \(y_i\), has residuals that sum to zero, whatever its gradient (See Exercise 1.2). Three very different lines show this:
x_mean, y_mean = x.mean(), y.mean()
for theta2_c in (150.0, 250.0, 350.0):
theta1_c = y_mean - theta2_c * x_mean # the line with this gradient through the centroid
r = y - (theta1_c + theta2_c * x)
print(f"Gradient {theta2_c:.0f} mm.kg-1: sum of the residuals {r.sum():.1e} mm")
Gradient 150 mm.kg-1: sum of the residuals 8.5e-14 mm
Gradient 250 mm.kg-1: sum of the residuals 5.7e-14 mm
Gradient 350 mm.kg-1: sum of the residuals 2.8e-13 mm
Each sum is of the order of \(10^{-13}\,\mathrm{mm}\), the size of the rounding errors in arithmetic with lengths of the order of 100 mm, since a computer stores each number to about 16 significant figures.
The sum of the absolute values of the residuals, \(\sum_i \lvert r_i \rvert\), does not cancel, and is a sensible measure, but it is awkward to work with mathematically: \(\lvert r \rvert\) has a corner at \(r = 0\), where it has no derivative, and so its minimum cannot be found by setting derivatives to zero. (Exercise 1.3 finds its best line by the brute-force search method of the next section.)
The sum of the squares of the residuals,
does not cancel either. It penalises one large residual far more than several small ones, so that the line is not allowed to stray far from any point, and it is a smooth function of the parameters, whose minimum can be found with calculus, as the next lesson shows. Adrien-Marie Legendre, who first published the method, justified the choice (not very pithily) as follows: “By this means, there is established among the errors a sort of equilibrium which, preventing the extremes from exerting an undue influence, is very well fitted to reveal that state of the system which most nearly approaches the truth.”1 The line that minimises \(S\) is the least-squares line, and a later lesson gives a deeper reason for preferring it, from the probabilities of the errors. For the two lines drawn by eye, \(S\) is
for name, (intercept, gradient) in eye_lines.items():
r = y - (intercept + gradient * x)
print(f"{name}: S = {np.sum(r**2):.1f} mm2")
First line: S = 51.1 mm2
Second line: S = 68.2 mm2
and so by this measure the first line, with \(S = 51.1\,\mathrm{mm^2}\), fits better than the second, with \(S = 68.2\,\mathrm{mm^2}\).
Brute-force search #
The least-squares line can be found with nothing more than arithmetic, by calculating \(S\) for a large number of lines and picking the line for which it is smallest. The function sum_of_squares calculates \(S\) for every combination of an intercept from one array and a gradient from another, and best_line picks out the combination with the smallest value:
def sum_of_squares(x, y, theta1, theta2):
"""Return S for every pair of an intercept from theta1 and a gradient from theta2."""
r = y - (theta1[:, None, None] + theta2[None, :, None] * x)
return np.sum(r**2, axis=-1)
def best_line(S, theta1, theta2):
"""Return the intercept and gradient at which the array S is smallest."""
i, j = np.unravel_index(np.argmin(S), S.shape)
return theta1[i], theta2[j]
theta1 = np.linspace(110, 130, 401) # possible intercepts, mm
theta2 = np.linspace(220, 280, 401) # possible gradients, mm.kg-1
S = sum_of_squares(x, y, theta1, theta2)
intercept_ls, gradient_ls = best_line(S, theta1, theta2)
print(f"Smallest S: {S.min():.1f} mm2, at intercept {intercept_ls:.2f} mm "
f"and gradient {gradient_ls:.2f} mm.kg-1")
print(f"Spring constant: {1000 * g / gradient_ls:.1f} N.m-1")
Smallest S: 47.0 mm2, at intercept 119.30 mm and gradient 247.75 mm.kg-1
Spring constant: 39.6 N.m-1
The search finds \(S = 47.0\,\mathrm{mm^2}\), smaller than for either line drawn by eye, at an intercept of 119.30 mm and a gradient of 247.75 mm/kg, which give a spring constant of 39.6 N/m. The steps of the arrays, 0.05 mm and 0.15 mm/kg, limit the precision of the result. The NumPy function np.polyfit(x, y, 1) fits a polynomial of degree 1, a straight line, by least squares, and returns its gradient and intercept (the coefficient of the highest power first):
print("np.polyfit (gradient, intercept):", np.polyfit(x, y, 1))
np.polyfit (gradient, intercept): [247.8121262 119.28169906]
It agrees with the search to within the steps of the arrays, and the next lesson shows how it finds the line exactly. Figure 1.3 draws \(S\) as a map, with contours (lines of equal \(S\)) over the intercepts and gradients searched.
fig, ax = plt.subplots(figsize=(6.4, 4.4))
contours = ax.contour(theta1, theta2, S.T, levels=[60, 80, 120, 200, 400, 800],
colors=GREY, linewidths=1)
ax.clabel(contours, fmt="%d", fontsize=8)
ax.plot(intercept_ls, gradient_ls, "x", color=INK, ms=8, mew=1.5, label="Least squares")
for (name, (intercept, gradient)), colour, marker in zip(eye_lines.items(), [BLUE, RED], ["o", "s"]):
ax.plot(intercept, gradient, marker, color=colour, ms=6, label=name)
ax.set_xlabel(r"Intercept, $\theta_1$ / mm")
ax.set_ylabel(r"Gradient, $\theta_2$ / $\mathrm{mm\,kg^{-1}}$")
ax.legend(loc="upper right", fontsize=9)
plt.show()
The contours can be thought of as representing a landscape with its lowest point in a depression at the optimum least-squares fit and steep sides surrounding it: the goal of fitting the data is to determine where the bottom of this valley lies. The lesson on covariance returns to this shape, which describes how uncertain the intercept and gradient are, and how their errors are related.
Exercises #
Exercise 1.1 ★ #
The resistance of a platinum resistance thermometer rises with its temperature, almost in proportion. The following are simulated calibration measurements of a thermometer whose resistance is close to 100 Ω at 0 °C, at temperatures \(t\) from 0 °C to 100 °C. Plot them, choose ranges for the intercept and gradient from the graph, and find the least-squares line by a brute-force search. From it, calculate the temperature coefficient of the thermometer, \(\alpha = \theta_2/\theta_1\), the fractional change in its resistance per degree. Then plot the residuals. What do they show?
t_C = np.arange(0, 101, 10.0) # °C
R = np.array([100.002, 103.897, 107.797, 111.678, 115.531, 119.391, 123.243,
127.074, 130.897, 134.703, 138.510]) # Ω
Show solution
The graph shows a straight line rising from about 100 Ω to about 138.5 Ω, so that the intercept is close to 100 Ω and the gradient close to 0.385 Ω per degree. The search below uses steps of 0.0025 Ω and \(2.5 \times 10^{-5}\) Ω per degree.
theta1_R = np.linspace(99.5, 100.5, 401) # Ω
theta2_R = np.linspace(0.380, 0.390, 401) # Ω per degree
R0, slope = best_line(sum_of_squares(t_C, R, theta1_R, theta2_R), theta1_R, theta2_R)
print(f"Intercept {R0:.3f} Ω, gradient {slope:.6f} Ω per degree; alpha = {slope / R0:.6f} per degree")
Intercept 100.085 Ω, gradient 0.385075 Ω per degree; alpha = 0.003847 per degree
fig, ax = plt.subplots(figsize=(6.4, 2.8))
ax.axhline(0, color=GREY, lw=0.8)
ax.plot(t_C, R - (R0 + slope * t_C), "o", color=INK, ms=4)
ax.set_xlabel("$t$ / °C")
ax.set_ylabel(r"$r_i$ / $\Omega$")
plt.show()
The temperature coefficient, 0.003847 per degree, is close to the 0.00385 per degree of the international standard for industrial platinum thermometers, IEC 60751. The residuals, though, do not scatter about zero: they form an arch, about −0.08 Ω at both ends and up to +0.05 Ω in the middle, far larger than the resolution of the readings, 0.001 Ω. The resistance is not quite proportional to the temperature, but rises a little less steeply as the temperature rises, and no straight line can follow the curve. The standard describes it by the grandly-named Callendar–Van Dusen equation, which between 0 °C and 850 °C is the quadratic \(R = R_0(1 + At + Bt^2)\), with a small negative \(B\); the lesson on linear models fits such a curve. A graph of the residuals shows a curve that a graph of the data hides.
Exercise 1.2 ★ #
Show that the residuals from a straight line sum to zero if, and only if, the line passes through the centroid of the data, \((\bar{x}, \bar{y})\).
Show solution
The sum of the residuals is
since \(\sum_i y_i = N\bar{y}\) and \(\sum_i x_i = N\bar{x}\). It is zero if, and only if, \(\bar{y} = \theta_1 + \theta_2\bar{x}\), which is the condition for the point \((\bar{x}, \bar{y})\) to lie on the line. The gradient does not enter the condition, and so every line through the centroid, whatever its gradient, has residuals that sum to zero.
Exercise 1.3 ★★ #
Use the brute-force search to find the line that minimises the sum of the absolute values of the residuals, \(\sum_i \lvert r_i \rvert\), for the spring’s lengths, and compare it with the least-squares line. Then suppose that the length measured with the 300 g mass had been misread, as 20 mm too long, and find both lines again. Which line moves further, and why?
Show solution
The function sum_of_absolute_values is sum_of_squares with the absolute value in place of the square.
def sum_of_absolute_values(x, y, theta1, theta2):
"""Return the sum of |r_i| for every pair of an intercept and a gradient."""
r = y - (theta1[:, None, None] + theta2[None, :, None] * x)
return np.sum(np.abs(r), axis=-1)
y_misread = y.copy()
y_misread[5] += 20.0 # the length with the 300 g mass, mm
for name, lengths in [("As measured", y), ("Misread", y_misread)]:
ls = best_line(sum_of_squares(x, lengths, theta1, theta2), theta1, theta2)
la = best_line(sum_of_absolute_values(x, lengths, theta1, theta2), theta1, theta2)
print(f"{name:11s}: least squares {ls[0]:.2f} mm, {ls[1]:.2f} mm.kg-1; "
f"least absolute values {la[0]:.2f} mm, {la[1]:.2f} mm.kg-1")
print(" residuals from the least-absolute-values line (mm):",
" ".join(f"{r_i:.2f}" for r_i in lengths - (la[0] + la[1] * x)))
As measured: least squares 119.30 mm, 247.75 mm.kg-1; least absolute values 118.50 mm, 249.85 mm.kg-1
residuals from the least-absolute-values line (mm): 1.65 -0.01 -0.02 -4.30 3.95 2.41 -0.76 1.21 -0.01 -1.91
Misread : least squares 120.60 mm, 250.30 mm.kg-1; least absolute values 118.50 mm, 249.85 mm.kg-1
residuals from the least-absolute-values line (mm): 1.65 -0.01 -0.02 -4.30 3.95 22.41 -0.76 1.21 -0.01 -1.91
For the lengths as measured, the line of least absolute values has an intercept of 118.50 mm and a gradient of 249.85 mm/kg, close to the least-squares line’s 119.30 mm and 247.75 mm/kg, and it passes within 0.02 mm of three of the points (at 100 g, 150 g and 450 g): a line that minimises the absolute residuals always passes through at least two of the points. With the misread length, the least-squares line moves, to 120.60 mm and 250.30 mm/kg, but the line of least absolute values does not move at all. The derivative of \(r^2\) is \(2r\), so that each point pulls the least-squares line towards itself in proportion to its residual, and the misread point, with a residual of 20 mm, pulls hardest. The derivative of \(\lvert r \rvert\) is \(\pm 1\), so that each point pulls the other line with the same strength, whatever its residual, and as long as the misread point stays above the line, how far above it lies makes no difference. The least squares method gives a single wild point a large influence, which a later lesson, on outliers, describes how to limit.
Notes #
- 1. The translation is by H. A. Ruger and H. M. Walker, in D. E. Smith, A Source Book in Mathematics (McGraw-Hill, 1929); the University of York has the translation and the original online. ↩