The closest reachable observation
Suppose consists of measurements and is the vector of predictions. There may be no exact solution. Least squares minimises The fitted vector is the orthogonal projection of onto the column space, because that is where every candidate prediction lies. The residual is orthogonal to every column. This gives the normal equations
Conversely, any solution of these equations is a least-squares solution by the squared-distance decomposition. The fitted vector is unique even if the coefficients are not. Any two coefficient vectors producing the same fit differ by a null-space vector.
For data use columns of ones and input values, in that order. The normal equations for intercept and slope are and Subtraction gives and then The residuals sum to zero and also have zero dot product with
Solve with QR
For independent columns, write and express the projection as Matching coefficients in the columns of gives This is a triangular solve. It avoids forming whose condition number is the square of that of Module 11 derives that ratio.
Small perturbations in observations can force a large change in coefficients when the columns are nearly dependent. For increasing the second observation by increases the second coefficient by and decreases the first by The prediction has only changed a little. Treat a small residual as evidence about fit to the measurements, and examine sensitivity separately.
from sympy import Matrix
A = Matrix([[1, 0], [1, 1], [1, 2]])
b = Matrix([1, 2, 2])
Q, R = A.QRdecomposition()
x = R.upper_triangular_solve(Q.T * b)
print(list(x))
print(list(A.T * (b - A * x)))[7/6, 1/2]
[0, 0]NumPy’s least-squares solver returns the coefficients and a numerical rank. Give the column order a name before interpreting the result. The residual norm measures the size of the fit error in observation coordinates.
import numpy as np
x_data = np.array([0., 1., 2.])
y_data = np.array([1., 2., 2.])
design = np.column_stack((np.ones(x_data.size), x_data))
coefficients, _, rank, _ = np.linalg.lstsq(design, y_data, rcond=None)
residual = y_data - design @ coefficients
print(f"intercept={coefficients[0]:.3f}, slope={coefficients[1]:.3f}")
print(f"rank={rank}, residual norm={np.linalg.norm(residual):.3f}")intercept=1.167, slope=0.500
rank=2, residual norm=0.408Exercises
What constant best fits in the least-squares sense?
Show solution✓ Checked
The design matrix is a column of ones. Residual orthogonality says their sum vanishes, so the fitted constant is the mean
For and find the fitted vector and describe all coefficients.
Show solution✓ Checked
The column space is the first axis, so the fit is Any coefficients with produce it, for instance
For compare the coefficient change when the second observation moves by with the first observation fixed.
Show solution✓ Checked
The second row forces the second coefficient to increase by The first row fixes the sum, so the first coefficient decreases by