Ordinary Least Squares (OLS) › Formula
Machine Learning from ScratchAll chapters Ordinary Least Squares (OLS) › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
The core of OLS lies in its elegant mathematical formulation. We'll break down the mathematics step by step, starting with the intuitive approach and building up to the matrix notation.
The Objective Function
OLS seeks to minimize the sum of squared errors (SSE) between observed values and predicted values:
where:
- is the observed target value for the -th data point
- is the predicted target value for the -th data point
- is the number of data points
The predicted value comes from the linear model:
where:
- is the intercept
- are the coefficients for the features
- are the feature values for the -th data point
Deriving the Normal Equations
Let's walk through, step by step, how we derive the equations that allow us to solve for the optimal coefficients in OLS regression. This process is rooted in calculus: to find the minimum of a function (in this case, the sum of squared errors), we set its derivatives with respect to each parameter to zero. These resulting equations are called the normal equations.
Step 1: Write the Sum of Squared Errors (SSE)
Recall that the OLS objective is to minimize the sum of squared errors between the observed values and the predicted values :
where
Step 2: Take Partial Derivatives with Respect to Each Coefficient
To find the values of that minimize SSE, we take the partial derivative of SSE with respect to each coefficient and set it to zero. This is because the minimum (or maximum) of a differentiable function occurs where its derivative is zero.these are known as the critical points, and for the SSE (which is a convex function in this case), setting the derivatives to zero guarantees we find the global minimum.
Step 2.1: For the Intercept :
Let's derive the process of taking the derivative of the sum of squared errors (SSE) with respect to the intercept in detail.
Recall the SSE:
where
So, explicitly, the SSE can be written as:
We want to find the value of that minimizes SSE. To do this, we take the partial derivative of SSE with respect to :
Since the sum is over , and appears in every term, we can bring the derivative inside the sum:
Let us denote the prediction error for the -th data point as:
So each term inside the sum is . The derivative of with respect to is:
By the chain rule:
But , so
Therefore,
Putting this back into the sum, we have:
Or, equivalently,
To find the minimum, we set this derivative equal to zero:
Dividing both sides by (which does not affect the equality), we get:
This equation tells us that, at the minimum, the sum of the residuals (the differences between the observed values and the predicted values) is zero.
Now, let's substitute the explicit form of back in:
Or, written out:
This is the normal equation for the intercept in OLS regression. It states that, at the optimal values of the coefficients, the sum of the residuals is zero.
Step 2.2: For Each Slope Coefficient (where ):
Now, let's derive the process of taking the partial derivative of the sum of squared errors (SSE) with respect to a generic slope coefficient (where ):
Recall the sum of squared errors:
where the predicted value for observation is:
We want to compute the partial derivative of SSE with respect to :
Let's break this down step by step:
-
Apply the linearity of differentiation (the derivative of a sum is equal to the sum of the derivatives for each term):
The derivative of a sum is the sum of the derivatives, so we can write: -
Apply the chain rule to each term:
For each , is a function of through . The chain rule gives:Since does not depend on , its derivative is zero. The derivative of with respect to is , because:
Therefore,
So, the derivative for each term is:
-
Sum over all observations:
Putting this back into the sum, we have:Or, equivalently,
-
Set the derivative to zero to find the minimum:
To find the value of that minimizes the SSE, set the derivative equal to zero:Dividing both sides by (which does not affect the equality), we get:
This equation tells us that, at the minimum, the sum of the residuals (errors) weighted by the value of feature for each observation is zero. In other words, the residuals are orthogonal (uncorrelated) to each feature in the model.
-
Substitute the explicit form of :
Recall that . Plugging this in, we get:Or, written out more explicitly:
This is the normal equation for the slope coefficient in OLS regression. It states that, at the optimal values of the coefficients, the sum of the residuals weighted by the corresponding feature values is zero for each feature. This property is fundamental to the OLS solution and ensures that the model's errors are, on average, uncorrelated with each predictor.
Step 3: The System of Equations: The Normal Equations
We now have equations (one for each coefficient, including the intercept) in unknowns:
- One equation from setting the derivative with respect to to zero
- equations from setting the derivatives with respect to each to zero
These equations are called the normal equations. Solving this system gives us the OLS estimates for all coefficients.
In summary:
For the intercept:
For each coefficient :
This system of equations forms the foundation for the matrix solution that follows, and helps explain how OLS "balances" the errors across data points and features to find the best-fitting line or hyperplane.
Matrix Formulation
The system of normal equations we derived above can be written much more compactly and powerfully using matrix notation. Matrix notation makes the equations easier to manipulate and reveals the underlying structure of the OLS solution.especially when dealing with multiple features.
Let's define the key components:
- is the design matrix of shape , where is the number of observations and is the number of features. The first column of is all ones to account for the intercept term, and the remaining columns contain the values of each feature for every observation.
- is the target vector of length , containing the observed values of the dependent variable.
- is the coefficient vector of length , which includes the intercept () and one coefficient for each feature.
In matrix notation, the model is written as:
where is the vector of errors (residuals).
The Normal Equations in Matrix Form
Recall that, for each coefficient, we set the derivative of the sum of squared errors to zero. In matrix terms, this yields the normal equations:
In this expression:
- is a matrix known as the Gram matrix. It summarizes the relationships (covariances) between all pairs of features, including the intercept.
- is a -dimensional vector that captures the relationship between each feature (and the intercept) and the target variable.
Solving for the OLS Coefficients
To find the vector of coefficients that minimizes the sum of squared errors, we solve the normal equations for :
Let's break down each component of this solution:
- (Gram matrix): This matrix encodes how each feature relates to every other feature (including itself). If two features are highly correlated, the corresponding off-diagonal entry will be large.
- (Inverse of Gram matrix): This step "untangles" the relationships between features, allowing us to isolate the effect of each one. The inverse exists only if the features are not perfectly collinear (i.e., no feature is an exact linear combination of others).
- (Feature-target cross-product): This vector measures how each feature (and the intercept) is associated with the target variable across all observations.
- Matrix multiplication : This operation combines all the above information to yield the set of coefficients that minimize the sum of squared errors. Each coefficient in represents the estimated effect of its corresponding feature on the target, holding all other features constant.
Matrix Notation Benefits
This matrix formulation provides the foundation for efficient computation and for extending OLS to more complex models. It allows us to:
- Solve for all coefficients at once, regardless of the number of features
- Generalize easily to multiple regression, polynomial regression, and regularized models
- Use powerful linear algebra libraries for fast computation, even with large datasets
The OLS closed-form solution in matrix notation is:
This formula gives us the unique set of coefficients that minimize the sum of squared errors, provided that is invertible (i.e., the features are linearly independent).
Mathematical Properties
The OLS solution is unique if is invertible (i.e., the features are not perfectly correlated), and it globally minimizes the sum of squared errors. The solution is a linear function of the target values, and, under the Gauss-Markov assumptions, provides unbiased estimates of the true coefficients.
The condition that must be invertible determines whether the solution is unique. This matrix is invertible when:
- The number of observations is greater than or equal to the number of features
- No feature is a perfect linear combination of other features (no multicollinearity)
- No feature is constant (all features have some variation)
When is not invertible (singular), this indicates that the features are linearly dependent. In such cases, the OLS solution is not unique, and the problem is said to be ill-conditioned. This commonly occurs when:
- You have more features than observations ()
- Features are perfectly correlated
- One feature is a linear combination of others
In practice, numerical issues can arise even when the matrix is technically invertible but has a very large condition number, leading to unstable coefficient estimates.
A high condition number means that even tiny errors in the input data or rounding errors during computation can lead to large changes in the estimated coefficients, making them unstable and unreliable. In other words, a large condition number indicates that the matrix is nearly singular, and the OLS solution may be highly sensitive to noise or numerical imprecision.