TExcelTAD
Home › Numerical Methods › Fitting Functions to Data

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 Ac≈yA\mathbf{c} \approx \mathbf{y}.

The problem

Fit a model f(t)=c1ϕ1(t)+⋯+cnϕn(t)f(t) = c_1\phi_1(t) + \cdots + c_n\phi_n(t), linear in the unknown coefficients, to data (ti,yi)(t_i, y_i), i=1,…,mi = 1, \ldots, m with m>nm > n. Each data point gives one row:

A=(ϕ1(t1)⋯ϕn(t1)⋮⋮ϕ1(tm)⋯ϕn(tm)),min⁡c∥y−Ac∥22.A = \begin{pmatrix} \phi_1(t_1) & \cdots & \phi_n(t_1) \\ \vdots & & \vdots \\ \phi_1(t_m) & \cdots & \phi_n(t_m)\end{pmatrix}, \qquad \min_{\mathbf{c}}\lVert\mathbf{y} - A\mathbf{c}\rVert_2^2.

The basis functions ϕj\phi_j can be anything (1,t,t21, t, t^2, sin⁡t\sin t, e−te^{-t}): only linearity in c\mathbf{c} matters.

A straight-line fit

python · try it yourself
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
y=aebty = ae^{bt} ln⁡y=ln⁡a+bt\ln y = \ln a + bt line in (t,ln⁡y)(t, \ln y)
y=atby = at^b ln⁡y=ln⁡a+bln⁡t\ln y = \ln a + b\ln t line in (ln⁡t,ln⁡y)(\ln t, \ln y)
y=a1+bty = \frac{a}{1 + bt} 1y=1a+bat\frac{1}{y} = \frac{1}{a} + \frac{b}{a}t line in (t,1/y)(t, 1/y)

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.

python · try it yourself
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 1,t,cos⁡ωt,sin⁡ωt1, t, \cos\omega t, \sin\omega t:

python · try it yourself
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 c\mathbf{c}: 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 LAPACK gelsd), scipy.linalg.lstsq, np.polyfit (QR on a scaled Vandermonde matrix), scipy.optimize.curve_fit (nonlinear, Levenberg-Marquardt).
  • Excel's LINEST and trendlines, and every regression library, solve this same problem.

Exercises

Exercise 1: Build the matrix

Write the matrix AA for fitting y=c1+c2t2y = c_1 + c_2t^2 to data at t=0,1,2,3t = 0, 1, 2, 3.

Answer

(10111419)\begin{pmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 4 \\ 1 & 9\end{pmatrix}.

Solution

Each row is (ϕ1(ti),ϕ2(ti))=(1,ti2)(\phi_1(t_i), \phi_2(t_i)) = (1, t_i^2).

Exercise 2: Linear or not?

Is fitting y=c1sin⁡(c2t)y = c_1\sin(c_2t) a linear least-squares problem?

Answer

No.

Solution

The model is not linear in c2c_2. With ω\omega known, y=c1sin⁡ωt+c2cos⁡ωty = c_1\sin\omega t + c_2\cos\omega t would be linear.

Exercise 3: A power law (code)

Fit y=atby = at^b to t=1,2,…,10t = 1, 2, \ldots, 10, y=2t1.5(1+noise)y = 2t^{1.5}(1 + \text{noise}) with 3 % noise (seed 24) by a log-log line.

Answer

a≈2a \approx 2 and b≈1.5b \approx 1.5 (see the output for the exact values).

Solution
python · try it yourself
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…

  1. the largest residual
  2. the sum of squared residuals
  3. the number of residuals
  4. the sum of absolute residuals

Which model can be fitted by linear least squares directly?

  1. y=c1ec2ty = c_1e^{c_2t}
  2. y=c1+c2ln⁡t+c3t2y = c_1 + c_2\ln t + c_3t^2
  3. y=sin⁡(c1t)y = \sin(c_1t)
  4. y=c1/(c2+t)y = c_1/(c_2 + t)

For mm data points and nn parameters, the matrix AA is…

  1. n×mn \times m
  2. m×nm \times n
  3. m×mm \times m
  4. n×nn \times n