TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Least Squares and Curve Fitting

Application: Least Squares and Curve Fitting

When a system Ax=bA\mathbf{x} = \mathbf{b} has more equations than unknowns it usually has no solution. Least squares picks the x\mathbf{x} that makes AxA\mathbf{x} as close to b\mathbf{b} 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 y=c0+c1ty = c_0 + c_1t through them:

tt 0 1 2 3
yy 1 3 4 7

Each point gives one equation c0+c1ti=yic_0 + c_1t_i = y_i. In matrix form:

A=[10111213],b=[1347],A[c0c1]≈bA = \begin{bmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 2 \\ 1 & 3 \end{bmatrix}, \qquad \mathbf{b} = \begin{bmatrix} 1 \\ 3 \\ 4 \\ 7 \end{bmatrix}, \qquad A \begin{bmatrix} c_0 \\ c_1 \end{bmatrix} \approx \mathbf{b}

Four equations, two unknowns, no exact solution. Instead we minimize the squared error ∥Ax−b∥2=∑(residuali)2\lVert A\mathbf{x} - \mathbf{b} \rVert^2 = \sum (\text{residual}_i)^2.

Geometry gives the normal equations

As x\mathbf{x} varies, AxA\mathbf{x} runs over the column space of AA. By the best approximation theorem from Orthogonal Projections, the closest point to b\mathbf{b} is the projection of b\mathbf{b} onto that column space, and it is characterized by the residual b−Ax^\mathbf{b} - A\hat{\mathbf{x}} being orthogonal to every column:

AT(b−Ax^)=0  ⟺  ATAx^=ATb(the normal equations)A^T(\mathbf{b} - A\hat{\mathbf{x}}) = \mathbf{0} \quad\iff\quad A^TA\hat{\mathbf{x}} = A^T\mathbf{b} \qquad \text{(the normal equations)}

If the columns of AA are independent, ATAA^TA is invertible (and positive definite) and the least squares solution is unique: x^=(ATA)−1ATb\hat{\mathbf{x}} = (A^TA)^{-1}A^T\mathbf{b}.

Exact arithmetic first:

python · try it yourself
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 y=0.9+1.9ty = 0.9 + 1.9t, 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 y=c0+c1t+c2t2y = c_0 + c_1t + c_2t^2, an exponential trend after taking logs, or a sum of sines all fit the same way: each basis function becomes a column of AA (a design matrix).

python · try it yourself
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 ATAx=ATbA^TA\mathbf{x} = A^T\mathbf{b} fast and simple, but cond⁡(ATA)=cond⁡(A)2\operatorname{cond}(A^TA) = \operatorname{cond}(A)^2, so accuracy is lost when columns are nearly dependent
QR A=QRA = QR, solve Rx=QTbR\mathbf{x} = Q^T\mathbf{b} stable, the standard choice (Gram-Schmidt)
SVD (np.linalg.lstsq) pseudoinverse x=A+b\mathbf{x} = A^+\mathbf{b} most robust; handles rank-deficient AA and reports the rank (SVD)
python · try it yourself
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.lstsq or sklearn.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 (ATA+λI)x=ATb(A^TA + \lambda I)\mathbf{x} = A^T\mathbf{b}, 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 y=cy = c to data y1,…,yny_1, \ldots, y_n is the mean.

Answer

c=y1+⋯+ynnc = \frac{y_1 + \cdots + y_n}{n}.

Solution

AA is a column of nn ones, so ATA=nA^TA = n and ATb=∑yiA^T\mathbf{b} = \sum y_i. The normal equation is n⋅c=∑yin \cdot c = \sum y_i.

Exercise 2: A line by hand

Fit y=c0+c1ty = c_0 + c_1t to (−1,0)(-1, 0), (0,1)(0, 1), (1,5)(1, 5).

Answer

y=2+2.5ty = 2 + 2.5t.

Solution
ATA=[3002](the t-values sum to 0)ATb=[0+1+5−0+0+5]=[65]c0=63=2,c1=52\begin{aligned} A^TA &= \begin{bmatrix} 3 & 0 \\ 0 & 2 \end{bmatrix} && \text{(the } t\text{-values sum to 0)} \\ A^T\mathbf{b} &= \begin{bmatrix} 0 + 1 + 5 \\ -0 + 0 + 5 \end{bmatrix} = \begin{bmatrix} 6 \\ 5 \end{bmatrix} \\ c_0 &= \frac{6}{3} = 2, \qquad c_1 = \frac{5}{2} \end{aligned}

Exercise 3: Inconsistent system

Find the least squares solution of x=1x = 1, y=2y = 2, x+y=4x + y = 4.

Answer

x=43x = \frac{4}{3}, y=73y = \frac{7}{3}.

Solution

A=[100111]A = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{bmatrix}, b=(1,2,4)\mathbf{b} = (1, 2, 4). ATA=[2112]A^TA = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}, ATb=(5,6)A^T\mathbf{b} = (5, 6). Solving 2x+y=52x + y = 5, x+2y=6x + 2y = 6 gives x=43x = \frac{4}{3}, y=73y = \frac{7}{3}.

python · try it yourself
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 (t,y)=(0,3.1),(1,4.4),(2,6.6),(3,9.9),(4,15.0)(t, y) = (0, 3.1), (1, 4.4), (2, 6.6), (3, 9.9), (4, 15.0) looks exponential. Fit y=C⋅ekty = C \cdot e^{kt} by least squares on ln⁡y\ln y.

Answer

k≈0.3964k \approx 0.3964, C≈3.0261C \approx 3.0261.

Solution

ln⁡y=ln⁡C+kt\ln y = \ln C + kt is linear in (ln⁡C,k)(\ln C, k), so fit a line to (t,ln⁡y)(t, \ln y) and exponentiate the intercept. Note this minimizes error in ln⁡y\ln y, not in yy.

python · try it yourself
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 x^\hat{\mathbf{x}} makes the residual b−Ax^\mathbf{b} - A\hat{\mathbf{x}}…

  1. zero
  2. orthogonal to the column space of AA
  3. parallel to b\mathbf{b}
  4. orthogonal to x^\hat{\mathbf{x}}

Why is np.linalg.lstsq preferred to solving ATAx=ATbA^TA\mathbf{x} = A^T\mathbf{b}?

  1. It gives a different, better-fitting answer
  2. Forming ATAA^TA squares the condition number and loses accuracy
  3. The normal equations only work for lines
  4. lstsq does not need AA

Which model can NOT be fitted by linear least squares directly?

  1. y=c0+c1t+c2t2y = c_0 + c_1t + c_2t^2
  2. y=c1sin⁡t+c2cos⁡ty = c_1 \sin t + c_2 \cos t
  3. y=c0+c1ln⁡ty = c_0 + c_1 \ln t
  4. y=sin⁡(c1t)y = \sin(c_1 t)