Regression begins with a modelling choice: which combinations of the measured variables should be allowed to explain the response? Once those combinations are fixed, least squares selects their coefficients by measuring the remaining error. The resulting calculation connects a data table, a quadratic objective, and an orthogonal projection. Understanding that connection makes it possible to check a fitted model rather than treating its coefficients as unexplained software output.
Motivation
Suppose an experiment records a predictor and a response on each of occasions. A line offers a compact description of how the response changes with the predictor. Real observations usually do not lie on one line, so the equations may be inconsistent. We can still ask for the line whose predictions come closest to the observations under a specified measure of error.
For this model, the residual at observation is the vertical difference . Its sign records whether the observed response lies above or below the prediction. Adding signed residuals alone would allow positive and negative errors to cancel. Squaring before adding produces a nonnegative objective and gives larger discrepancies greater influence. This choice also makes the objective a quadratic function of the unknown coefficients.
The data determine where the model is evaluated; the chosen features determine which prediction vectors are possible. A straight line, a polynomial, and a model with several measured predictors therefore share the same linear algebra once their features have been collected into a matrix.
Definitions
Definition
Design matrix, fitted values, and residuals
Let contain one row per observation and one column per chosen feature. Let be the response vector and the coefficient vector. Define
A least-squares coefficient vector minimizes over .
For a line, the feature functions are and , so
The column of ones supplies the intercept: its coefficient shifts every fitted response by the same amount. Omitting that column specifies a different model, one constrained to pass through the origin. The model should make that choice explicit before any calculation begins.
With measured predictors, row is and . The same construction allows fixed feature functions , with . A polynomial model uses powers of the input as its features. Although its graph may curve, it remains linear in the unknown coefficients. Throughout the least-squares optimization, and are fixed; only varies.
The vector belongs to . This is a space of possible responses at all observed inputs, rather than a space of individual predictor values. Its ambient dimension is the number of observations. This distinction explains where the projection geometry lives.
Theorem/proposition
Proposition
Normal equations and orthogonal residuals
For any real matrix , a vector minimizes exactly when
Its residual is perpendicular to every column of . Consequently, is the orthogonal projection of onto .
Proposition
When coefficients are unique
The matrix is invertible exactly when has linearly independent columns. In that case the unique least-squares coefficient vector is
For an arbitrary , the fitted vector is still unique. If is one minimizer, all minimizers are with .
These statements separate two questions that arise in modelling. The fitted responses may be determined even when the data cannot determine how their contributions should be divided among redundant features. Having more observations than coefficients does not by itself remove that redundancy: independence of the columns is the decisive condition.
Proof sketch or proof idea
For a candidate , write . A change in the coefficients gives the exact identity
If , the cross term disappears. Every coefficient change therefore adds the nonnegative amount to the objective, proving global minimality. Conversely, at a minimizer the function of one real variable has derivative zero at for every . Its derivative there is , forcing . This proves both directions, including cases with dependent columns.
Proof
Rank, existence, and the unique fitted vector
For every ,
Thus has zero kernel precisely when does. For independent columns this quadratic form is positive for every nonzero , and the inverse formula follows from the normal equations.
For existence, project onto the finite-dimensional subspace . The projection has the form , and its orthogonal residual satisfies the normal equations. If two coefficient vectors satisfy those equations, their difference satisfies . Multiplying by gives , so both vectors produce exactly the same fitted responses. Adding a vector in leaves those responses unchanged, which describes the entire family of minimizers.
An intercept has an immediate diagnostic consequence. Its column is the vector , so the normal equations include . Hence the residuals sum to zero and the average fitted response equals the average observed response. Other feature columns impose their own orthogonality equations. These equations test optimality jointly; checking the residual sum alone tests only the intercept equation.
Worked examples
Worked example
Example 1: Fit a line and verify its residuals
Use the three observations , , and . Then
The normal equations are and . Subtracting yields , followed by . Therefore
The residual sum is zero. Its dot product with the predictor column is also zero: . These two checks verify the full normal equations. The determinant of is , so the coefficients are unique. The positive residual sum of squares quantifies the fact that the three observations do not lie on one straight line.
The line also passes through the sample-mean point , as follows from the intercept equation. This is a consequence of the fit, rather than an extra constraint added to the optimization. It supplies a useful arithmetic check when solving a small regression problem by hand.
Worked example
Example 2: Unique fitted values with ambiguous coefficients
Suppose all three inputs equal , while the responses are , , and . The model still has the form , but
Every prediction equals the single value . The objective becomes
It is minimized at , so all coefficient vectors , with , are minimizers. Each gives , residual , and objective value . The normal equations consistently reduce to .
The nullspace direction is : changing the coefficients along it has no effect at the observed input. At the new input , however, these models predict . Thus agreement of fitted responses does not identify a unique prediction rule away from the observed inputs. The data contain no variation in from which to determine the slope.
Worked example
Example 3: Weights on residuals and weights in the objective
Fit a constant to responses , , and , with objective weights . The objective is
Its derivative vanishes when
The residuals are . Their weighted sum is zero: . The weighted objective value is . For comparison, equal objective weights give the ordinary mean . Reducing the influence of the largest response moves the fitted constant toward the other two observations.
To express this problem as ordinary least squares, multiply the residuals by . Squaring their lengths then produces the objective weights , , and . The distinction matters: multiplying the last residual by would instead give it objective weight and solve a different problem.
Weighted models and computation
In general, positive objective weights define
Apply the normal equations to the transformed matrix and response :
Equivalently, if , the equation is . This convention keeps the objective weights and the factors multiplying individual residuals distinct. Positive weights make invertible, so has the same column rank as . The uniqueness condition is consequently unchanged. Orthogonality now means , with respect to the weighted inner product.
For numerical computation, solve the least-squares problem directly. The inverse formula expresses the mathematical solution when full column rank holds; a direct least-squares routine can use orthogonal factorizations without explicitly forming that inverse. For the first example:
import numpy as np
x = np.array([0.0, 1.0, 2.0])
y = np.array([1.0, 2.0, 2.0])
A = np.column_stack((np.ones_like(x), x))
beta, _, rank, singular_values = np.linalg.lstsq(A, y, rcond=None)
residual = y - A @ beta
rss = residual @ residual
# beta is approximately [1.16666667, 0.5]; rss is approximately 1/6
The returned rank describes how many independent feature directions the routine
detects. Computing the residual vector explicitly makes its sign convention
and the objective visible. For positive objective weights stored in q, the
corresponding call uses np.sqrt(q)[:, None] * A and np.sqrt(q) * y. The
singular values also connect this computation to dimensionality reduction.
QR and triangular least-squares solving
When has full column rank and , orthonormalizing its columns gives a thin QR factorization
Here is invertible and upper triangular. Split the response into its projection and its orthogonal remainder. Because and preserves lengths of coefficient vectors,
The second term does not depend on . The first can be made zero, so the unique minimizer solves . Back substitution starts with the last row of this triangular system, then uses the known coefficient in the preceding row. This route gives the same normal-equation solution while avoiding explicit construction of or its inverse. The full column-rank condition makes invertible; a rank-deficient design instead needs the least-squares or pseudoinverse treatment above.
Worked example
A triangular regression calculation
Use rows and response . Choose columns of as and . Then
The last triangular equation gives slope ; the first gives intercept . The fitted response is , and the residual is . Its squared norm is , exactly the orthogonal remainder term in the decomposition.
Feature choice and the meaning of the objective
A quadratic response model uses the three features , , and . For the inputs in Example 1 its design matrix is
The coefficients of the polynomial reproduce all three responses, giving zero training residual. Each former straight-line model remains available by setting the quadratic coefficient to zero, so this smaller minimum also follows from inclusion of the feature spaces. The extra feature changes the set over which we minimize; it does not improve the solution of the original two-feature optimization problem.
At a new input , this quadratic predicts , whereas the fitted line predicts . Both calculations are determined by their chosen models, but the original three observations provide no response at that new input with which to compare them. Selecting a feature space and estimating coefficients within it are therefore different tasks. Least squares solves the latter once the former is fixed.
Transforming a response also changes what an error means. For observations satisfying and , fit the power model with . Logarithms give
Least squares with response and features , minimizes squared differences on the logarithmic response scale. Exponentiating the fitted intercept recovers the coefficient , but does not turn that objective into squared differences on the original response scale. On the logarithmic scale, equal multiplicative ratios give equal residual differences; on the original scale, equal additive differences do. This is a mathematical change to the fitting criterion, not simply a convenient rewrite of the same loss. The positivity assumptions specify the domain in which the transformation is defined.
Other linearized models
The same design-matrix method handles several other models. The response column determines the scale on which squared errors are minimized:
| Model | Feature row and fitted response | Domain conditions |
|---|---|---|
| ; response | , , | |
| ; response | ||
| ; response | ||
| ; response | ; prediction requires | |
| ; response | , ; prediction requires |
For the exponential model, solve , then recover and . Its inputs can be any real numbers; only its observed responses must be positive for this logarithmic fit. Logarithmic regression instead transforms only the inputs, so its responses may be negative or zero. The input-reciprocal model also preserves the original response SSE. Transforming the response by a logarithm or reciprocal selects a different loss.
For each two-column design above, unique coefficients require that its transformed input values are not all equal. Linearization makes coefficients linear in the transformed equation; it does not remove a rank deficiency.
Worked example
Example 4: Exact exponential and input-reciprocal fits
For , , and , the log responses lie on
Thus the transformed least-squares fit has , , and the recovered model is . The input zero is allowed here because the input itself is not logged.
For , , and , use the transformed inputs , , and . They give the exact line . This fit minimizes original response SSE, which is zero. It is defined for every , including negative inputs; there is no response-positivity restriction.
Worked example
Example 5: Taking response reciprocals changes the objective
Take and . Fitting the reciprocal responses with features gives
Restoring the response gives predictions . Their original response SSE is , rather than . In general,
The denominator depends on the prediction, so this is not the original SSE or a predetermined observation-weighted SSE. The fitted denominator is nonzero at all three observations, but vanishes at , where the model has no defined response. Evaluate a model's domain as well as its chosen loss before using a transformed fit for prediction.
Finally, interpret residual checks relative to the actual feature matrix. If Example 1 is fitted through the origin using only the feature , its one coefficient is . The residual becomes . Its dot product with the predictor column is zero, as optimality requires, while its entries sum to . There is no intercept column imposing a zero-sum condition. Changing the model changes the diagnostic equations along with the fitted values. Recording the matrix next to the coefficients keeps those equations unambiguous.
Common mistakes
Common mistake
Confusing three different claims about a fit
The normal equations characterize the smallest training residual sum of squares within the chosen feature space. A zero residual additionally means that the observations lie in that space. Unique coefficients additionally require independent feature columns. These are three separate mathematical claims, each with its own test.
Adding features enlarges the possible fitted-response space and can only decrease its minimum training error, because the old model remains available by setting the new coefficients to zero. Prediction on unseen observations is a further modelling question. A smaller training error alone does not compare those prediction errors.
A second frequent error is to assume that every residual is perpendicular to the fitted line drawn in the predictor-response plane. Ordinary least squares uses vertical response differences. The perpendicularity theorem concerns the whole residual vector in and the columns of the design matrix. For weighted problems, the corresponding theorem uses the weighted inner product. Keeping the ambient space explicit resolves this apparent geometric conflict.
Summary
Choose features first, assemble one design-matrix row per observation, and minimize the squared residual norm. Check a candidate with the normal equations. Column rank determines coefficient uniqueness; orthogonal projection determines the unique fitted vector. With weighted observations, take square roots of objective weights when scaling rows for an ordinary least-squares solver.
Exercises
Checkpoint
Exercise 1: Fit a constant to responses , , and . Find the minimizer, residual vector, and residual sum of squares.
The design matrix has a single column of ones. Complete a square or use its one normal equation.
Checkpoint
Exercise 2: Let and propose residual . Can it be the residual of an ordinary least-squares fit with this design matrix?
Check its inner product with every column, including the predictor column.
Checkpoint
Exercise 3: A constant model has responses and , with objective weights and . Find the fitted constant and the diagonal matrix that scales residuals for ordinary least squares.
Write the weighted objective before differentiating. Distinguish an objective weight from its square root.
Checkpoint
Exercise 4: Fit to , , and . Find the exact model. Does the negative response prevent this fit?
Identify which variable is transformed before applying any sign condition.
Solutions
Solution · Exercise 1 solution
The normal equation is , so . The residual vector is and the residual sum of squares is . Its entries sum to zero, as required by the intercept column. Completing a square gives , which also proves uniqueness.
Solution · Exercise 2 solution
The residual sum is zero, but
The second normal equation fails, so this cannot be a least-squares residual for the specified matrix. Orthogonality to the intercept column alone is insufficient.
Solution · Exercise 3 solution
The objective is . Its derivative is , giving . The residual vector has weighted sum . The scaling matrix is , because .
Solution · Exercise 4 solution
The transformed inputs are , with responses . Thus , , and the exact model is . Every input is positive. The response is not logged, so its negative value is allowed; the minimized loss is original response SSE.
Related notes
SVD and principal components uses singular vectors to describe important directions in a data matrix. Gradient descent on quadratics studies iterative optimization of objectives such as the one derived here. The course reading list collects the books for this course.