Fitting Functions to Data
With more data points than parameters, a model usually cannot pass through every point. Linear least squares chooses the parameters that minimize the sum of squared misfits. It is the computational core of regression, calibration, curve fitting and signal processing, and it leads to overdetermined linear systems .
The problem
Fit a model , linear in the unknown coefficients, to data , with . Each data point gives one row:
The basis functions can be anything (, , ): only linearity in matters.
A straight-line fit
import numpy as np
rng = np.random.default_rng(21)
t = np.linspace(0, 10, 25)
y = 1.5 + 0.8 * t + rng.normal(0, 0.6, t.size) # true line 1.5 + 0.8 t
A = np.column_stack([np.ones_like(t), t])
c, res, rank, sv = np.linalg.lstsq(A, y, rcond=None)
print(f"fit: y = {c[0]:.4f} + {c[1]:.4f} t")
print(f"sum of squared residuals: {res[0]:.4f}, rank {rank}")
print("np.polyfit agrees:", np.allclose(np.polyfit(t, y, 1)[::-1], c))fit: y = 1.5122 + 0.8151 t
sum of squared residuals: 10.9729, rank 2
np.polyfit agrees: True
Linearizing nonlinear models
Some nonlinear models become linear after a transformation:
| Model | Transformation | Linear fit |
|---|---|---|
| line in | ||
| line in | ||
| line in |
The transformed fit minimizes a different error (relative rather than absolute for the logarithm), so its result differs from a true nonlinear fit, but it is a fine starting guess for one.
import numpy as np
from scipy.optimize import curve_fit
rng = np.random.default_rng(22)
t = np.linspace(0, 4, 30)
y = 3.0 * np.exp(-0.7 * t) * (1 + rng.normal(0, 0.05, t.size))
b, ln_a = np.polyfit(t, np.log(y), 1)
print(f"log-linear fit : a = {np.exp(ln_a):.4f}, b = {b:.4f}")
popt, _ = curve_fit(lambda t, a, b: a * np.exp(b * t), t, y, p0=[np.exp(ln_a), b])
print(f"nonlinear fit : a = {popt[0]:.4f}, b = {popt[1]:.4f}")log-linear fit : a = 2.9719, b = -0.6988
nonlinear fit : a = 2.8575, b = -0.6621
Mixing basis functions
A periodic signal with a trend uses basis :
import numpy as np
rng = np.random.default_rng(23)
t = np.arange(0, 48.0) # 48 months
y = 10 + 0.2 * t + 3 * np.sin(2 * np.pi * t / 12 + 0.5) + rng.normal(0, 0.5, t.size)
w = 2 * np.pi / 12
A = np.column_stack([np.ones_like(t), t, np.cos(w * t), np.sin(w * t)])
c = np.linalg.lstsq(A, y, rcond=None)[0]
amp = np.hypot(c[2], c[3])
print("coefficients:", np.round(c, 3))
print(f"trend {c[1]:.3f} per month, seasonal amplitude {amp:.3f}")coefficients: [9.973 0.201 1.431 2.461]
trend 0.201 per month, seasonal amplitude 2.847
How to solve it
The next three lessons answer how lstsq computes : via the normal equations (fast, but squares the condition number), the QR factorization (the standard), or the SVD (most robust, handles rank deficiency). Statistics and ML views of the same problem are in Linear Regression.
In software
np.linalg.lstsq(SVD-based LAPACKgelsd),scipy.linalg.lstsq,np.polyfit(QR on a scaled Vandermonde matrix),scipy.optimize.curve_fit(nonlinear, Levenberg-Marquardt).- Excel's
LINESTand trendlines, and every regression library, solve this same problem.
Exercises
Exercise 1: Build the matrix
Write the matrix for fitting to data at .
Answer
.
Solution
Each row is .
Exercise 2: Linear or not?
Is fitting a linear least-squares problem?
Answer
No.
Solution
The model is not linear in . With known, would be linear.
Exercise 3: A power law (code)
Fit to , with 3 % noise (seed 24) by a log-log line.
Answer
and (see the output for the exact values).
Solution
import numpy as np
rng = np.random.default_rng(24)
t = np.arange(1.0, 11.0)
y = 2 * t**1.5 * (1 + rng.normal(0, 0.03, t.size))
b, ln_a = np.polyfit(np.log(t), np.log(y), 1)
print(f"a = {np.exp(ln_a):.4f}, b = {b:.4f}")a = 2.0422, b = 1.4838
Test yourself
Linear least squares minimizes…
- the largest residual
- the sum of squared residuals
- the number of residuals
- the sum of absolute residuals
Which model can be fitted by linear least squares directly?
For data points and parameters, the matrix is…