Linear Regression and the Least Squares Objective
Suppose a hospital wants to predict a patient's blood pressure. It uses age, weight, and sodium intake as inputs. The relationship is unlikely to be perfectly linear. Still, a straight-line approximation is often good enough. It is easy to fit and easy to interpret. Linear regression formalizes this instinct. It assumes the target is a weighted sum of the inputs plus noise. Then it chooses weights that make predictions match observed data as closely as possible. This idea sits at the foundation of statistical modeling and machine learning. It is the first algorithm most practitioners learn. Yet it powers real systems: econometric forecasting, A/B test analysis, risk scoring. It also appears in the last layer of many neural networks. It drives control systems that need fast, interpretable predictions. Its popularity comes from a rare combination. It has a convex objective with a closed-form solution. It has strong statistical theory. And its predictions can be explained in one sentence ("each extra kilogram adds 0.4 mmHg"). The big picture is this: pick a hypothesis class (linear functions). Pick a loss that measures prediction error (squared error). Then find the parameters that minimize total loss over training data. This "model + loss + optimizer" template is the scaffolding. It supports essentially all of supervised learning. This ranges from linear regression to deep neural networks. Linear regression is the cleanest possible instance of that template. That is exactly why it is worth mastering deeply. It should not be treated as a footnote. This article defines the linear model and the least-squares objective precisely. It derives why squared error is a natural choice. It works through the geometry and calculus of the loss surface. It also traces a full numerical example by hand. It sets up — without yet solving — two standard ways to find optimal weights. One is an exact formula: the normal equations. The other is an iterative method: gradient descent. Both are covered in their own articles.
- Linear regression models a target as , a weighted sum of features plus a bias.
- The least-squares objective is the mean (or sum) of squared residuals between predictions and true values.
- Squared error is not arbitrary: it falls out of assuming Gaussian noise and maximizing likelihood.
- The loss is a convex quadratic bowl in weight space, guaranteeing a unique global minimum (generically).
- Fitting means minimizing this bowl — done exactly via the Normal Equations or iteratively via Gradient Descent.
- The framework generalizes directly to Ridge Regression (add a penalty) and Logistic Regression (change the link function).
Linear regression finds the weights that minimize total squared prediction error, which is equivalent to finding the maximum-likelihood fit under Gaussian noise.
The idea
A linear model predicts a scalar target from a feature vector as
where is the weight vector and is the bias (or intercept). It is common to absorb the bias into by appending a constant feature to every input, giving the compact form with . The model is called linear because is a linear (affine) function of the parameters — not necessarily of the raw inputs, since features can include polynomials, logs, or interactions of the original variables. Given a training set , the natural way to judge a candidate is to look at the residuals . The least-squares objective (also called the sum of squared errors, SSE, or residual sum of squares, RSS) is
Dividing by gives the mean squared error (MSE), which is scale-independent across dataset sizes and is the version most often reported and optimized in practice:
Fitting the model means solving
Why squares, rather than absolute residuals or some other penalty? Two independent reasons converge on the same answer. Geometrically, minimizing the sum of squared residuals is equivalent to finding the orthogonal projection of the target vector onto the subspace spanned by the feature columns — the unique point in that subspace closest to in Euclidean distance, which makes squared error the natural companion to linear algebra. Statistically, if we assume with independent noise , the likelihood of the data is
Taking the log and dropping constants that don't depend on , maximizing the log-likelihood is exactly the same as minimizing . So least squares is the maximum-likelihood estimator under Gaussian noise — not an ad hoc choice but the loss implied by the simplest and most common noise assumption.
How it works
Fitting a linear regression model has three conceptual steps: represent the data as matrices, write down the loss as a function of , and minimize it. The minimization itself can be done in closed form or iteratively; this article treats the setup and the shape of the objective, while the actual solvers are developed in their own right in The Normal Equations and Closed-Form Solution and Gradient Descent for Parameter Estimation. Stack the feature vectors (each with a leading 1 for the bias) into a design matrix , and stack the targets into . The predictions for the whole dataset are , and the least-squares objective becomes
This is a quadratic function of . Expanding it,
which is a sum of a constant, a linear term in , and a quadratic term with matrix . Because is positive semi-definite (it equals for some , and for all ), is a convex function of : its graph is a bowl, possibly with a flat direction but never a saddle or a local bump. This convexity is the single most important structural fact about linear regression — it is what guarantees that "find the minimum" is a well-posed, solvable problem rather than a search over an unpredictable landscape. To find the minimizer, take the gradient of with respect to and set it to zero:
These are the normal equations; when is invertible, solves the problem exactly in one step. When is singular or the data is very large, iterative methods like gradient descent are preferred instead. Both routes are explored in depth in their dedicated articles — the point here is that the objective itself, being a convex quadratic, is what makes both routes work. ``` ALGORITHM FitLinearRegressionBySSE(X, y) Input: X, an n x d matrix of feature rows (bias column optionally prepended) y, a length-n vector of targets Output: w, the least-squares weight vector 1. Augment X with a column of ones -> X' (n x (d+1)), unless already done 2. Define J(w) = (y - X' w)^T (y - X' w) # the objective to minimize 3. Solve for the stationary point of J: gradient(w) = -2 X'^T y + 2 X'^T X' w set gradient(w) = 0 ==> X'^T X' w = X'^T y # normal equations 4. If X'^T X' is invertible: w <- (X'^T X')^{-1} X'^T y # closed form, see Normal Equations article else: w <- solve via gradient descent or pseudo-inverse # see Gradient Descent article 5. return w ``` ``` ALGORITHM PredictAndEvaluate(w, X_new, y_new) Input: fitted weights w, new feature matrix X_new, true targets y_new (for evaluation) Output: predictions, and MSE 1. y_hat <- X_new w 2. residuals <- y_new - y_hat 3. MSE <- (1/n) sum(residuals[i]^2 for i in 1..n) 4. return y_hat, MSE ```
Complexity & correctness
Objective construction. Building the design matrix costs to lay out; computing costs multiply-adds (each of the entries is an inner product over rows), and costs . Evaluating the loss for a given costs — one pass over the data to compute residuals and square them.
Solving for depends on the chosen method:
- Closed form via the normal equations requires inverting (or factorizing) the matrix , which costs using standard Gaussian elimination or Cholesky decomposition, on top of the to form . Total: . This is efficient when is small to moderate (up to a few thousand) even for very large , since the cost grows only linearly in .
- Iterative solvers (gradient descent) cost per iteration and typically run for iterations, giving total — attractive when is huge or is ill-conditioned or too large to form explicitly.
Space. Storing costs ; storing costs , independent of , which is why the normal-equation route scales gracefully to huge as long as stays modest.
Correctness — why minimizing is the right thing to do. The argument has two independent legs. Geometric leg. The set of vectors reachable as for some is exactly the column space of , a subspace . Minimizing over all is minimizing distance from to a point in . Basic Euclidean geometry says the closest point in a subspace to an external point is its orthogonal projection, and the residual vector at that closest point must be perpendicular to every vector in the subspace — in particular perpendicular to every column of :
which is precisely the normal equations derived from calculus above. The two derivations (orthogonality and vanishing gradient) agreeing is not a coincidence — the same minimum has both a geometric and a calculus certificate. Convexity leg. has Hessian , which is positive semi-definite for any (shown above). A twice-differentiable function with PSD Hessian everywhere is convex, and for a convex function any stationary point (where the gradient vanishes) is a global minimum, not merely a local one. If is strictly positive definite (full column rank, i.e., and no exact linear dependencies among features), the minimum is additionally unique. If is singular (more features than independent data directions, or collinear features), infinitely many achieve the same minimal loss, and regularization — see Ridge Regression and L2 Regularization — is used to pick out one well-behaved solution.
Honest tradeoffs. Squared error weights large residuals quadratically, so a single wild outlier can dominate the fit far more than it should — the least-squares line can be dragged noticeably toward one bad point. Squared error also implicitly assumes a symmetric, Gaussian-shaped noise process; if the true noise is heavy-tailed or skewed, the maximum-likelihood justification for least squares no longer holds, and alternatives like least-absolute-deviations (L1 loss) or robust regression are more appropriate. Linear regression is also, by construction, blind to nonlinear relationships in the raw features — it fits a linear function of whatever features you give it, so nonlinearity in the true relationship must be captured by feature engineering (polynomial terms, interactions) rather than by the model itself.
Worked example
Consider predicting exam score from hours studied , using four students, and fit a model (one feature plus bias).
| Student | Hours () | Score () |
|---|---|---|
| A | 1 | 52 |
| B | 2 | 63 |
| C | 3 | 75 |
| D | 5 | 90 |
Build the design matrix (bias column first) and target vector:
Step 1 — form and .
(Check: the (1,1) entry of is ; the (1,2) entry is ; the (2,2) entry is . And ; — let's recompute carefully: , , , ; sum . So .)
Step 2 — solve the normal equations :
Determinant of : . Inverse: .
Compute each entry: ; ; so numerator , giving . ; ; so numerator , giving . So the fitted model is approximately
Step 3 — check residuals and the loss.
| Student | residual | ||||
|---|---|---|---|---|---|
| A | 1 | 52 | 53.40 | −1.40 | 1.96 |
| B | 2 | 63 | 62.89 | 0.11 | 0.01 |
| C | 3 | 75 | 72.37 | 2.63 | 6.92 |
| D | 5 | 90 | 91.34 | −1.34 | 1.80 |
Sum of squared residuals . Mean squared error .
Sanity check via orthogonality. The correctness argument above claims at the optimum, i.e., residuals sum to zero and are uncorrelated with . Sum of residuals: (up to rounding) — confirmed. This is not a coincidence; it is the geometric fact that the residual vector is orthogonal to the column space of , and the all-ones column forces exactly at the true optimum.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Forgetting the bias term | Omitting the constant column in forces the line through the origin | Systematically biased predictions when data is not centered at zero |
| Using SSE instead of MSE when comparing models across dataset sizes | SSE grows with ; MSE does not | Misleading comparisons between train/test sets of different sizes |
| Ignoring collinear or duplicated features | becomes singular or near-singular | Normal equations have no unique solution; numerically unstable weights |
| Treating a large as proof the linear model is "correct" | Squared-error fit can look good even when residuals show clear nonlinear structure | Undetected model misspecification; poor extrapolation |
| Blindly trusting one huge outlier's influence | Squared loss penalizes large residuals quadratically | One bad data point can rotate the fitted line substantially |
| Confusing "linear in " with "linear in " | The model is linear in the parameters, not necessarily in the raw features | Missing the fact that polynomial or log features still fit within linear regression |
Pioneers & history
The least-squares method predates modern machine learning by two centuries and was developed to solve an astronomical problem: reconciling noisy, overdetermined observations of planetary and cometary orbits.
Origins · 1 minAdrien-Marie Legendre and how this was discovered
Legendre published the method of least squares in 1805 in an appendix on determining the orbits of comets, explicitly proposing the minimization of the sum of squared errors as the criterion for choosing the best-fitting curve through noisy data — the first public statement of the method that bears its name today.
Gauss claimed to have used least squares as early as 1795 and, crucially, supplied its probabilistic justification: he showed that least squares is the maximum-likelihood estimator when errors follow what is now called the Gaussian (normal) distribution, connecting the geometric fitting procedure to a rigorous statistical foundation.
Where this matters
Linear regression fit by least squares is the workhorse of quantitative fields far beyond machine learning. In economics and finance, it underlies hedonic pricing models, CAPM asset-pricing regressions, and demand forecasting. In the sciences, it is the default tool for quantifying how one measured quantity depends on another, and its assumptions (linearity, homoscedastic Gaussian noise) are taught as the baseline model against which more complex ones are judged. In engineering, it is used for calibration curves, sensor fusion, and system identification, where fast, interpretable, closed-form fits are valuable in real time. Inside machine learning systems, least-squares linear regression appears as a baseline model against which every fancier method is benchmarked, as the final layer of many regression networks (a linear readout on top of learned features), and as the core building block generalized by Ridge Regression and L2 Regularization (adding a penalty for numerical stability and to control overfitting) and by Logistic Regression and the Sigmoid (replacing the identity output with a sigmoid for classification). The two solution methods it sets up — direct linear-algebra solves via the Normal Equations and iterative first-order optimization via Gradient Descent — recur throughout the rest of supervised learning, from support vector machines to the training of deep neural networks, making this simple model an essential template rather than a historical curiosity.
Ask the tutor: If two features in my dataset are almost perfectly correlated, what happens to the least-squares weights, and how does ridge regression fix it?
Is linear regression only useful when the true relationship is a straight line?
No. The model is linear in its parameters , not necessarily in the raw input variables. By constructing features such as , , or interaction terms like and feeding them into the same linear model, you can fit curves, polynomials, and more complex surfaces while keeping the convex least-squares machinery intact. This is why linear regression underlies polynomial regression and many basis-function methods — the fitting procedure stays exactly the same; only the feature construction step changes. The key restriction is that predictions must remain a linear (affine) combination of whatever features are given.
What's the difference between minimizing SSE and minimizing MSE?
Sum of squared errors (SSE) is ; mean squared error (MSE) divides that by . Since dividing by the constant does not change where the minimum occurs, both objectives yield the identical optimal weight vector . The distinction matters for interpretation and comparison: MSE is comparable across datasets of different sizes and has natural units (squared target units), while SSE grows mechanically with more data and is harder to compare across experiments. Most practical reporting and many optimization libraries default to MSE for this reason.
Why does linear regression require X^T X to be invertible, and what happens if it isn't?
The closed-form solution requires to be invertible, which holds precisely when the columns of (the features) are linearly independent and there are at least as many independent data points as features. If features are collinear (e.g., one is an exact multiple of another) or there are more features than examples, is singular, and infinitely many weight vectors achieve the same minimal loss. In practice this is handled either by removing redundant features, using a pseudo-inverse for a minimum-norm solution, or adding an L2 penalty as in Ridge Regression and L2 Regularization, which makes the matrix invertible by construction.
How is linear regression related to maximum likelihood estimation?
If you assume the target is generated as with independently for each example, the log-likelihood of the observed data as a function of reduces to a negative constant times the sum of squared residuals, plus terms that don't depend on . Maximizing this log-likelihood over is therefore mathematically identical to minimizing the sum of squared residuals. This equivalence is why least squares is described as the maximum-likelihood estimator under Gaussian noise, and it is the deeper statistical reason squared error was chosen rather than, say, absolute error.
Does a low training loss mean the linear model has found the "true" relationship?
Not necessarily. A low sum-of-squared-errors on the training data only shows the model fits the observed points well; it says nothing directly about how well it will predict new, unseen data, nor whether a linear function is even the right shape for the underlying relationship. Overfitting can occur with enough features (especially engineered polynomial ones), and misspecification can occur if the true relationship is genuinely nonlinear even though the fitted line looks reasonable on a scatter plot. Practitioners check residual plots, use held-out test sets, and compare against regularized or nonlinear alternatives before trusting a fit.
How does linear regression connect to gradient descent and the normal equations?
Least squares defines what to optimize — the convex quadratic objective — but not how to optimize it. The normal equations exploit the fact that this specific objective has a closed-form stationary point reachable via linear algebra, solved in one shot for moderate feature counts. Gradient descent instead follows the negative gradient of downhill iteratively, useful when the feature count is huge or the matrix inversion is impractical. Both methods provably converge to the same global minimum precisely because is convex, which is the central correctness guarantee established in this article.
What's the difference between linear regression and logistic regression?
Linear regression predicts a continuous, unbounded target using and squared-error loss, which matches a Gaussian noise assumption. Logistic regression instead predicts a probability in for a binary outcome, applying a sigmoid function to and fitting parameters by maximizing likelihood under a Bernoulli (rather than Gaussian) assumption, which yields the cross-entropy loss instead of squared error. Both share the same underlying "linear score, then loss derived from a noise/observation model" structure, which is why Logistic Regression and the Sigmoid is best understood as a direct extension of the ideas developed here.