From first principles
Derive the orthogonality condition for a fit
With more observations than unknown coefficients, the linear prediction \(Ax\) can miss the observed vector \(b\). Suppose squared residuals carry equal weight and choose coefficients to minimize \(\|b-Ax\|_2^2\). Try any change \(x\mapsto x+t d\), where the direction \(d\) is fixed but the scalar \(t\) can have either sign. Expand with \(r=b-Ax\),
At a minimum the linear term must vanish in every direction, so \(A^Tr=0\). This says the residual is perpendicular to every vector the model can generate. Rearranging gives the normal equations,
If \(A\) has independent columns then the quadratic term is positive for every nonzero direction and the minimizer is unique. A thin QR factorization with orthonormal columns \(Q\) and triangular \(R\) yields the equivalent equation \(Rx=Q^Tb\) and avoids explicitly forming products that can worsen numerical conditioning.
Background · Orthogonal projector
Columns of Q must be orthonormal in the stated real inner product. Least squares removes the component of the data orthogonal to the fitted range.
Derivation and applications
Impose one exact calibration condition on a noisy fit
Some data describe noisy readings while another relationship is an exact conservation or calibration requirement. Model noisy data by \(Ax\simeq b\) with independent equal-variance errors, but require \(c^Tx=d\) exactly. Assume \(A\) has full column rank and \(c\ne0\). Write \(H=A^TA\), and let \(x_0\) denote the ordinary least-squares solution. Expanding around \(x_0\) removes the cross term because the residual there is orthogonal to every column of \(A\),
Thus the constrained fit is the closest feasible point in the metric determined by \(H\). Introduce a multiplier \(\lambda\) for the exact condition in half the squared objective. Setting its derivatives to zero and solving the first equation gives
Applying the constraint determines the multiplier and the increase in squared residual,
The denominator is positive. In computation the expression \(H^{-1}c\) denotes a solve, preferably using existing QR factors. An already satisfied constraint leaves the fit unchanged. Directions weakly constrained by the measured data can accommodate an exact calibration with little increase in residual.
Worked example
Reconcile two fitted quantities with an exact total
An ordinary fit gives \(x_0=(2,5)^T\) with \(H=\operatorname{diag}(4,1)\). The correct total is \(x_1+x_2=6\). Now \(H^{-1}c=(0.25,1)^T\), the denominator is \(1.25\), and \(\lambda=0.8\). The adjusted pair is \((1.8,4.2)\). Its extra squared residual is \(4(0.2)^2+(0.8)^2=0.80\), with the less precisely measured second coordinate absorbing most of the correction.
Second application
Enforce a zero offset in a calibration line
Three equally weighted readings at \(t=0,1,2\) are \(1,3,5\). The free fit is \(1+2t\). A separate exact zero calibration demands an intercept of zero. Along that feasible line the slope obeys \((0^2+1^2+2^2)m=0+3+10\), giving \(m=2.6\). The three residuals \(1,0.4,-0.2\) have squared norm \(1.20\), a directly observable cost of the added calibration condition.
Replace exact consistency by an optimisation problem
Three thermometers at different positions need not lie on a common straight temperature profile. Let the rows of \(A\) contain the values of candidate basis functions at those positions and let \(b\) contain the observations. With more independent measurements than unknown coefficients, \(Ax=b\) may have no solution. A least-squares fit chooses \(x\) to minimise \(\|b-Ax\|_2^2\). Equal unweighted terms assume the deviations are comparable in units and importance. If one instrument is much noisier than another, that assumption deserves review before interpreting a fitted slope.
Take any coefficient perturbation \(sd\). Expanding the squared mismatch gives \(\|b-Ax\|^2-2s\,d^TA^T(b-Ax)+s^2\|Ad\|^2\). At a minimum the coefficient of \(s\) must vanish for every \(d\). Hence \(A^TAx=A^Tb\). This is also sufficient: when the linear term vanishes, every perturbation adds a nonnegative square. Geometrically the residual is perpendicular to the column space of \(A\). Full column rank makes the minimiser unique, since no nonzero coefficient perturbation then leaves the fitted values unchanged.
Background · When is a fitted residual independent of the fitted coefficients?
Assume the design matrix has full column rank and the observation errors have covariance \(\sigma^2 I\). Write the parameter error as \(A^+\epsilon\) and the residual as \((I-P)\epsilon\), with \(P=AA^+\). Their cross-covariance is
The last equality follows because \(I-P\) maps every vector into the orthogonal complement of the columns of \(A\), where \(A^+\) vanishes. For Gaussian errors the two quantities are jointly Gaussian, so zero cross-covariance also gives independence. With non-Gaussian noise their projections may still be statistically dependent. Orthogonality is always an algebraic property of the least-squares fit; independence needs an assumption about how errors were generated.
Fit three imperfect readings
Take positions \(t=-1,0,1\) and deviations from a baseline temperature of \(1,2,5\) K. Fit \(b(t)\simeq c+mt\), using a constant and a linear column. Their dot product is zero because the positions sum to zero. Their squared lengths are three and two. Multiplying the observation vector by each column gives 8 and 4, so the normal equations are diagonal and yield \(c=8/3\) K and \(m=2\) K per position unit.
The predicted values are \(2/3,8/3,14/3\) K. The residual \(b-Ax=(1/3,-2/3,1/3)^T\) has zero sum and zero dot product with \((-1,0,1)^T\), as required. Changing the intercept cannot lower the sum of squares because the positive and negative residuals already balance; changing the slope has the analogous weighted balance. The squared residual norm is \(2/3\) K². This measures fit to these readings. It does not tell whether a line will predict temperatures well outside the sampled interval.
Remove redundant precision loss
If \(A\) has full column rank and singular values \(\sigma_i\), then \(A^TA\) has eigenvalues \(\sigma_i^2\). Consequently
When two model columns are nearly parallel, forming the products explicitly can lose significant information about their small difference. For example, a straight-line fit on positions clustered around a very large offset has nearly proportional constant and position columns. Centering and scaling positions improves the parameterisation and gives an intercept with a local physical interpretation.
Alternatively, factor \(A=QR\) with \(Q\) having orthonormal columns and \(R\) upper triangular. Decompose the residual into its orthogonal parts inside and outside the column space:
The second term is independent of the fit. Solve \(Rx=Q^Tb\) by back substitution. Householder reflectors build this factorisation using length-preserving transformations. In the three-temperature example, dividing the constant column by \(\sqrt3\) and the position column by \(\sqrt2\) already produces \(Q\). The transformed data are \(8/\sqrt3\) and \(4/\sqrt2\). Dividing by the diagonal of \(R\) recovers exactly the same fit. When the columns are nearly dependent, inspect the rank explicitly, using column pivoting or singular values, before giving a physical interpretation to individual coefficients.
Include measurement weights explicitly
If an instrument gives independent errors with standard deviations \(s_i\), divide row \(i\) of both \(A\) and \(b\) by \(s_i\). The sum of squares now measures squared differences in units of each sensor’s own standard deviation. For two readings 0 and 10 with standard deviations 1 and 3, a constant fit minimises \(c^2+(10-c)^2/9\). Differentiation gives \(c=1\), versus the unweighted mean of 5. A reliable low reading exerts more influence on the weighted result.
This weighting still assumes independence and an appropriate error description. If both readings share an uncertain offset, repeated observations can reduce independent fluctuations without removing the offset. Near a rank deficiency, a small weighted residual likewise cannot establish separate physical identifiability of the fitted coefficients. Examine uncertainty or singular directions in the parameter map as well as the final mismatch.
Derive a prediction after withholding one observation
Let \(A\) have full column rank and use equal independent data variances. The fitted vector is \(\hat y=Hy\) with \(H=A(A^TA)^{-1}A^T\); implement the projection with a stable factorisation. Suppose row \(i\) is withheld and the reduced design stays full rank. Its new prediction at that location, \(\hat y_i^{(-i)}\), can be obtained without refitting the entire data set. Replace \(y_i\) in the full data by this predicted value. The model fitted to the reduced observations now also satisfies the full normal equations because the added row has precisely zero residual at that fit.
Apply the original hat matrix to the modified vector. Its \(i\)-th fitted value is \(\hat y_i+h_{ii}(\hat y_i^{(-i)}-y_i)\), which must equal \(\hat y_i^{(-i)}\). Rearranging gives
This relation shows how leverage can mask an error inside the training data. If \(h_{ii}=1\), the denominator vanishes because that observation alone identifies some parameter combination. Withholding it then requires a different rank convention or additional modelling information.
Predict the end of a calibration line from its other readings
Fit \(y=a+bt\) to \((t,y)=(0,0),(1,1),(2,4)\). The mean time is one and the mean response is \(5/3\). The slope from centred data is \([(-1)(-5/3)+(1)(7/3)]/[1+1]=2\), giving intercept \(-1/3\). The fitted values are \((-1/3,5/3,11/3)\) and residuals are \((1/3,-2/3,1/3)\). Taken individually, either endpoint looks better fitted than the midpoint. But each endpoint also has disproportionate influence on the slope used to fit itself.
For a straight line the intercept and centred-time columns are orthogonal, so \(h_{ii}=1/3+(t_i-1)^2/2\). The endpoint leverages are \(5/6\), the central leverage is \(1/3\), and their sum is two, the number of fitted parameters. The leave-one-out residuals are consequently \(2,-1,2\). Verify the last directly: the first two readings define the line \(y=t\); it predicts 2 at the final time, while the held-out observation is 4. For the central reading the two endpoints define \(y=2t\), predicting 2 instead of 1.
The scientific question determines whether this test is relevant. Dropping an endpoint forces extrapolation, whereas dropping the midpoint tests interpolation between two retained settings. Averaging these three squared errors mixes two distinct prediction tasks. If future measurements will be taken only inside the calibrated interval, a separate evaluation there is more informative. Serially correlated measurements also invalidate the interpretation of neighbouring held-out readings as independent validation, although the algebraic leave-one-out identity for a fixed design remains valid.
For these three observations the sum of squared training residuals is
The sum after leaving each observation out in turn is \(4+1+4=9\). The discrepancy arises even with an exactly implemented fitting routine. Each training prediction has already used the observation against which it is compared. The difference becomes acute near the boundary because that observation has supplied much of the information about its own fitted value.
Estimate a fitted line beyond its calibration interval
Six independent sensors of equal variance calibrate an intercept and slope. For each proposed location use the row \(c=(1,x)\). The standard error of the fitted mean is \(\sigma\|R^{-\mathsf T}c\|\) from the QR factorisation of the design.

Read values from the plot
| Prediction location | Calibration −1 to 1 | Calibration −0.25 to 0.25 |
|---|---|---|
| −2 | 1.263 | 4.7983 |
| −1 | 0.72375 | 2.4251 |
| 0 | 0.40825 | 0.40825 |
| 1 | 0.72375 | 2.4251 |
| 2 | 1.263 | 4.7983 |
Change parameters · Estimate a fitted line beyond its calibration interval
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Refitting a sensor as observations arrive or disappear · Matrix computations and spectral accuracy
A calibration line receives one new observation at a time. Update its least-squares factorisation using rotations, quantify the influence of a deleted observation and detect when removing a sample destroys identifiability.