Application: Least Squares and Curve Fitting
When a system has more equations than unknowns it usually has no solution. Least squares picks the that makes as close to as possible, and that single idea is behind linear regression, curve fitting and calibration code everywhere.
The problem
Suppose we measured four points and want the line through them:
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 1 | 3 | 4 | 7 |
Each point gives one equation . In matrix form:
Four equations, two unknowns, no exact solution. Instead we minimize the squared error .
Geometry gives the normal equations
As varies, runs over the column space of . By the best approximation theorem from Orthogonal Projections, the closest point to is the projection of onto that column space, and it is characterized by the residual being orthogonal to every column:
If the columns of are independent, is invertible (and positive definite) and the least squares solution is unique: .
Exact arithmetic first:
from sympy import Matrix
A = Matrix([[1, 0], [1, 1], [1, 2], [1, 3]])
b = Matrix([1, 3, 4, 7])
AtA, Atb = A.T * A, A.T * b
print("A^T A =", AtA.tolist(), " A^T b =", list(Atb))
x = AtA.solve(Atb)
print("c0, c1 =", list(x))
r = b - A * x
print("residual =", list(r), " A^T r =", list(A.T * r))
print("sum of squared residuals =", r.dot(r))A^T A = [[4, 6], [6, 14]] A^T b = [15, 32]
c0, c1 = [9/10, 19/10]
residual = [1/10, 1/5, -7/10, 2/5] A^T r = [0, 0]
sum of squared residuals = 7/10
The best line is , and no other line has total squared error below 0.7.
Curve fitting: any model linear in its coefficients
"Linear" least squares only needs the model to be linear in the unknown coefficients. A parabola , an exponential trend after taking logs, or a sum of sines all fit the same way: each basis function becomes a column of (a design matrix).
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
t = np.linspace(0, 4, 12)
y = 2.0 - 1.5 * t + 0.8 * t**2 + rng.normal(0, 0.4, t.size) # made-up measurements
A = np.column_stack([np.ones_like(t), t, t**2])
x_normal = np.linalg.solve(A.T @ A, A.T @ y)
x_lstsq, res, rank, sv = np.linalg.lstsq(A, y, rcond=None)
print("normal equations:", np.round(x_normal, 4))
print("lstsq :", np.round(x_lstsq, 4), " rank:", int(rank))
print("residual sum of squares:", round(float(res[0]), 4))
tt = np.linspace(0, 4, 200)
plt.figure(figsize=(6, 4))
plt.plot(t, y, "o", label="data")
plt.plot(tt, x_lstsq[0] + x_lstsq[1] * tt + x_lstsq[2] * tt**2, label="least squares parabola")
plt.legend(); plt.xlabel("t"); plt.ylabel("y")normal equations: [ 1.9975 -1.6636 0.8521]
lstsq : [ 1.9975 -1.6636 0.8521] rank: 3
residual sum of squares: 0.6711
The fitted coefficients are close to the true 2, −1.5, 0.8 used to generate the data; the noise accounts for the difference.
Normal equations vs lstsq
Both give the same answer on well-behaved problems, but they are not equally good numerically.
| Method | How | Trade-off |
|---|---|---|
| Normal equations | solve | fast and simple, but , so accuracy is lost when columns are nearly dependent |
| QR | , solve | stable, the standard choice (Gram-Schmidt) |
SVD (np.linalg.lstsq) |
pseudoinverse | most robust; handles rank-deficient and reports the rank (SVD) |
import numpy as np
t = np.linspace(0, 1, 30)
A = np.column_stack([t**k for k in range(9)]) # degree-8 polynomial: nearly dependent columns
x_true = np.ones(9)
b = A @ x_true
print(f"cond(A) = {np.linalg.cond(A):.2e}")
print(f"cond(A^T A) = {np.linalg.cond(A.T @ A):.2e}")
x_ne = np.linalg.solve(A.T @ A, A.T @ b)
x_ls = np.linalg.lstsq(A, b, rcond=None)[0]
print(f"max error, normal equations: {np.max(np.abs(x_ne - x_true)):.1e}")
print(f"max error, lstsq (SVD) : {np.max(np.abs(x_ls - x_true)):.1e}")cond(A) = 6.08e+05
cond(A^T A) = 3.70e+11
max error, normal equations: 3.9e-06
max error, lstsq (SVD) : 6.5e-11
Squaring the condition number cost about five digits of accuracy here. See Numerical Linear Algebra for more on conditioning.
Tip: In production code call
np.linalg.lstsq,scipy.linalg.lstsqorsklearn.linear_model.LinearRegression. Write out the normal equations only to understand them or for tiny, well-scaled problems.
In software
- Machine learning. Ordinary linear regression and polynomial regression are exactly this computation; ridge regression solves , which also fixes the conditioning.
- Sensors and robotics. Calibrating an accelerometer, fitting a circle to lidar points, or estimating a camera pose from many point matches are overdetermined systems solved by least squares.
- Graphics. Fitting a smooth curve through mouse strokes, or computing the best-fit plane to a point cloud.
- Nonlinear fits (
scipy.optimize.curve_fit, see SciPy curve fitting) repeat a linear least squares step on a linearized model (Gauss-Newton).
Go further: Linear Regression and the Normal Equation solves these normal equations from scratch as a regression model and fits it to real data.
Exercises
Exercise 1: Best constant
Show that the least squares fit of a constant to data is the mean.
Answer
.
Solution
is a column of ones, so and . The normal equation is .
Exercise 2: A line by hand
Fit to , , .
Answer
.
Solution
Exercise 3: Inconsistent system
Find the least squares solution of , , .
Answer
, .
Solution
, . , . Solving , gives , .
from sympy import Matrix
A = Matrix([[1, 0], [0, 1], [1, 1]]); b = Matrix([1, 2, 4])
print(list((A.T * A).solve(A.T * b)))[4/3, 7/3]
Exercise 4: Fit an exponential (code)
Data looks exponential. Fit by least squares on .
Answer
, .
Solution
is linear in , so fit a line to and exponentiate the intercept. Note this minimizes error in , not in .
import numpy as np
t = np.array([0, 1, 2, 3, 4.0]); y = np.array([3.1, 4.4, 6.6, 9.9, 15.0])
A = np.column_stack([np.ones_like(t), t])
lnC, k = np.linalg.lstsq(A, np.log(y), rcond=None)[0]
print(round(float(k), 4), round(float(np.exp(lnC)), 4))0.3964 3.0261
Test yourself
The least squares solution makes the residual …
- zero
- orthogonal to the column space of
- parallel to
- orthogonal to
Why is np.linalg.lstsq preferred to solving ?
- It gives a different, better-fitting answer
- Forming squares the condition number and loses accuracy
- The normal equations only work for lines
- lstsq does not need
Which model can NOT be fitted by linear least squares directly?