Week 04 · Least squares and QR
Fit a line by minimizing squared error and use residual orthogonality to verify the solution.
Subject contents · Week 3 · Week 5
Fit a line by minimizing squared error and use residual orthogonality to verify the solution.
Fit a line to measurements that disagree
Suppose a transfer takes 1 second at size 0, then 2 seconds at sizes 1 and 2. Three noisy readings need not lie on a single line. A line can still be useful as a baseline prediction. We need a criterion for selecting it and a way to check that the result satisfies that criterion.
The residuals here measure errors in the response at the observed input values. That is why the figure draws vertical segments. If input measurements themselves are substantially noisy, or if one large error should carry less weight, the choice of fitting method matters.
The idea
Suppose the input is x and the model predicts ŷ = β₀ + β₁x. Put a column of ones and a column of x values into a design matrix A. The ones let the intercept contribute equally to every prediction. The residual r = y − Aβ records the difference between each observation and its prediction.
Ordinary least squares chooses β to minimize r · r. Differentiating the objective gives the condition Aᵀ(y − Aβ) = 0. The residual is perpendicular to both columns of the design matrix. With an intercept, that implies the residuals sum to zero.
QR writes A = QR, where the columns of Q are orthonormal and R is upper triangular. For a full-column-rank matrix, the least-squares solution solves Rβ = Qᵀy. This avoids explicitly forming AᵀA, which can worsen conditioning. Use a rank-aware least-squares routine when columns may be dependent.
Derive the equations from the error you want to minimize
Each row of A is [1, xᵢ]. The coefficient vector β contains the intercept β₀ and slope β₁. The residual for row i is rᵢ = yᵢ − (β₀ + β₁xᵢ), and the total squared error is J = Σᵢ rᵢ². Squaring makes errors on either side count positively and gives large errors more influence.
Changing β₀ shifts every prediction equally. Changing β₁ shifts prediction i by xᵢ times the change. Differentiating J gives −2Σᵢrᵢ for the intercept and −2Σᵢxᵢrᵢ for the slope. At the minimum, both are zero. Together they say Aᵀr = 0, the projection check from Week 3.
The first equation also implies β₀ = ȳ − β₁x̄. Substitute it into the second and solve for β₁ to get the centered formula used below. For these three observations the centered inputs are −1, 0, 1. The numerator is (−1)(−2/3) + 0(1/3) + 1(1/3) = 1. The denominator is 1 + 0 + 1 = 2. If all input values were equal, this denominator would be zero and the data would not identify a separate slope.
Work it out
Fit a line to (0, 1), (1, 2), and (2, 2). The mean input is 1 and the mean output is 5/3. The slope is Σ(xᵢ − x̄)(yᵢ − ȳ)/Σ(xᵢ − x̄)² = 1/2. The intercept is 5/3 − (1/2) × 1 = 7/6.
The predictions are (7/6, 5/3, 13/6). The residuals are (−1/6, 1/3, −1/6). They sum to zero, and the dot product with the input column (0, 1, 2) is also zero. The sum of squared errors is 1/6.
Least squares minimizes the squared lengths of the vertical residuals.
Run the Python lab
import numpy as np
x = np.array([0., 1., 2.])
y = np.array([1., 2., 2.])
A = np.column_stack([np.ones(x.size), x])
Q, R = np.linalg.qr(A, mode="reduced")
beta = np.linalg.solve(R, Q.T @ y)
residual = y - A @ beta
print("intercept and slope:", np.round(beta, 6).tolist())
print(f"squared error: {residual @ residual:.6f}")
np.testing.assert_allclose(beta, [7 / 6, 1 / 2])
np.testing.assert_allclose(A.T @ residual, [0, 0], atol=1e-12)
np.testing.assert_allclose(
beta, np.linalg.lstsq(A, y, rcond=None)[0]
)
Expected output
intercept and slope: [1.166667, 0.5]
squared error: 0.166667
Check the fit in two ways
The QR lab first computes Qᵀy, the coordinates of y along the orthonormal columns of Q. Solving with R turns those coordinates back into intercept and slope. The check against np.linalg.lstsq independently compares the coefficients. The check on A.T @ residual verifies the geometry of the solution even when the observations do not all fit.
The residual sum of squares is 1/6 in this example. To compare an average error across datasets with different row counts, divide by the number of rows for mean squared error. Taking its square root produces an error in seconds again. Both are summaries of error on the three fitted rows. To estimate predictive error, evaluate on measurements the fit never used.
Try it yourself
- Fit the same observations without an intercept. What slope do you get, and which residual check still holds?
- Set every x to 1. Which combination of coefficients can the data determine?
Check your work. Without an intercept, the slope is (x · y)/(x · x) = 6/5. The residual is still perpendicular to x, but it need not sum to zero. With constant x = 1, the model can determine β₀ + β₁, but cannot separate the two terms.