Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Deriving OLS from Normal Equations

Welcome to our fourth lesson. In the previous session, we established the essential vocabulary of supervised learning: hypothesis spaces, parameters, and hyperparameters. We are now equipped to transition from abstract definitions to concrete application. This lesson marks our first deep dive into a specific learning algorithm, where we will derive the optimal parameters for a model from first principles.

Our focus will be on linear regression, a cornerstone of machine learning. The learning outcome for this lesson is to derive the ordinary least squares solution for linear regression from the normal equations. We will define a linear model, formulate an objective function based on minimizing squared error, and then use two powerful perspectives—one geometric and one based on calculus—to arrive at a closed-form solution for the model's parameters. This process will transform the abstract idea of a learning algorithm "searching" a hypothesis space into a precise, mathematical procedure.

The Linear Regression Model

Let's begin by formally defining our model. In linear regression, we assume the relationship between a set of input features and an output target is linear. For a single data example with features, , we predict the target value using a linear combination of these features:

Here, are the model parameters (weights) corresponding to each feature, and is the bias or intercept term.

To make the derivation cleaner, we can absorb the bias term into the weight vector. We do this by introducing an extra feature, , that is always equal to 1 for every data point. Our feature vector becomes , and our parameter vector becomes . With this trick, the hypothesis is now a simple dot product:

Now, let's extend this to our entire dataset. Suppose we have training examples. We can stack our feature vectors into a design matrix of size , where each row corresponds to one training example. We can also stack our true target values into a vector of size .

Using this matrix notation, we can compute all predictions at once with a single matrix-vector multiplication:

The following video lecture from Stanford's CS229 course provides an excellent overview of this notational setup, which is standard across machine learning.

Stanford CS229: Machine Learning - Linear Regression and Gradient Descent | Lecture 2 (Autumn 2018)

This segment of the lecture introduces the linear regression problem and methodically builds up the matrix and vector notation we will be using.

Watch the segment from the beginning to where the notation is fully established. Pay close attention to how the data (features and labels) are organized into the design matrix \mathbf{X} and the target vector \mathbf{y}, and how the hypothesis is expressed in matrix form.

The Cost Function: Ordinary Least Squares (OLS)

Our goal is to find the parameter vector that makes our predictions as close as possible to the true values . We need a way to quantify the total error. In Ordinary Least Squares (OLS), we use the Sum of Squared Errors (SSE), also known as the Residual Sum of Squares (RSS).

The vector of errors, or residuals, is . The SSE is the sum of the squares of these individual errors. In vector terms, this is the squared Euclidean norm (or L2 norm) of the residual vector:

Our optimization problem is therefore to find the that minimizes this cost function:

This formulation is the heart of OLS. We are looking for the linear model that minimizes the squared vertical distances between the observed data points and the regression line, as illustrated below.

A linear regression model fit to data. The red line represents the predictions \(\hat{y}\), the black dots are the true data points \(y\), and the vertical lines represent the residuals whose sum of squares is minimized by OLS.

The Geometric Derivation of the Normal Equations

One of the most elegant ways to derive the solution is through geometric intuition. Your background in linear algebra will be particularly useful here.

The vector of predictions, , is a linear combination of the columns of the design matrix . This means that must lie within the column space of , denoted .

Our problem is to find a vector in that is closest to our observed data vector . Geometrically, the vector in a subspace that is closest to an external point is the orthogonal projection of that point onto the subspace.

Geometric interpretation of OLS. The vector \(\mathbf{y}\) is projected onto the column space of \(\mathbf{X}\) to find the closest vector \(\mathbf{X}\hat{\beta}\) (using \(\beta\) instead of \(\mathbf{w}\)). The residual vector \(\hat{\epsilon} = \mathbf{y} - \mathbf{X}\hat{\beta}\) is orthogonal to the column space.

This means the residual vector, , must be orthogonal to the entire column space of . For to be orthogonal to , it must be orthogonal to every column in . This condition can be stated compactly using the transpose of :

Substituting , we get:

Rearranging this gives us the Normal Equations:

This is a remarkable result. We have transformed a complex minimization problem into a straightforward system of linear equations. The following video provides a concise walkthrough of this geometric derivation.

Normal equation solution of the least-squares problem | Lecture 27 | Matrix Algebra for Engineers

This video explains the geometric view of the least-squares problem, framing it as a projection and cleanly deriving the normal equations.

Watch the first two sections of the video, from the beginning up to the derivation. The key idea is understanding why multiplying by \mathbf{A}^T (our \mathbf{X}^T) effectively projects the vector \mathbf{b} (our \mathbf{y}) onto the column space.

The Calculus Derivation of the Normal Equations

An alternative path to the same result is through multivariable calculus. Since you have a strong mathematical background, seeing the problem from this angle will reinforce the solution's validity. We start again with the cost function and find the point where its gradient is zero.

The cost function is . Let's write this using the dot product definition of the squared norm, .

Expanding this expression:

Note that is a scalar, so it's equal to its own transpose: . Thus, we can combine the two middle terms:

To find the minimum, we take the gradient of with respect to and set it to the zero vector. Using the following standard matrix calculus identities:

  • (for symmetric ; note is symmetric)

We get:

Setting the gradient to zero:

Once again, we arrive at the Normal Equations. The following lecture notes provide a rigorous, step-by-step walkthrough of both the geometric and calculus-based derivations.

Lecture 2: Least squares estimation - Laurent Lessard

These notes from a course on advanced control systems offer a concise and mathematically precise derivation of the normal equations.

Please read Sections 1.1 and 1.2. Start with the geometric argument. This formalizes the projection concept we just discussed. Then, read the calculus argument. This shows the derivation by taking the gradient of the loss function, including a helpful lemma on matrix derivatives.

The Closed-Form Solution

The Normal Equations give us a system of linear equations with unknowns (the elements of ). We can solve for directly.

If the matrix is invertible, we can pre-multiply both sides by its inverse to isolate :

This gives us the celebrated closed-form solution for Ordinary Least Squares:

This equation is a significant result. It tells us that, unlike many other machine learning algorithms that require iterative optimization, we can calculate the optimal parameters for linear regression directly through a sequence of matrix operations.

The condition for this to work is that must be invertible. This is true if and only if the columns of the design matrix are linearly independent. In a machine learning context, this means you don't have redundant features (e.g., including a feature for temperature in Celsius and another for temperature in Fahrenheit) or more features than data points.

The text from Dive into Deep Learning provides a succinct summary of this final step.

3.1. Linear Regression

This section presents the derivation and the final analytic solution in a very clear, ML-oriented fashion.

Read the section titled "Analytic Solution." It begins after the definition of the loss function. Focus on the final two equations, where they set the derivative to zero and then solve for the optimal weights \mathbf{w}^* in the final equation.

Connection to Maximum Likelihood Estimation

Why the squared error? While it's computationally convenient, there's a deeper probabilistic justification. If we assume that the target variable is generated from a linear function of plus some Gaussian (normal) noise, , where , then the OLS solution is also the Maximum Likelihood Estimate (MLE) for .

In essence, under the assumption of Gaussian noise, the parameters that are most likely to have generated our observed data are exactly the same parameters that minimize the sum of squared errors. This provides a powerful theoretical justification for the OLS cost function.

You will explore MLE in more detail in a future lesson, but it is a key principle that connects probabilistic modeling and optimization in machine learning. The section on "The Normal Distribution and Squared Loss" in the Dive into Deep Learning resource (ID LINK) explains this connection well if you wish to read ahead.

Conclusion

In this lesson, we have performed our first end-to-end derivation of a machine learning model's training process. We moved from the abstract concept of finding the "best" parameters to a concrete, analytical solution.

Key takeaways from this lesson include:

  • Model Formulation: Linear regression can be expressed compactly using matrix notation as .
  • Cost Function: The OLS objective is to minimize the Sum of Squared Errors (SSE), which is equivalent to minimizing the squared L2 norm of the residual vector, .
  • The Normal Equations: By using either geometric arguments (orthogonality of residuals) or calculus (setting the gradient to zero), we can transform the minimization problem into a system of linear equations: .
  • The Closed-Form Solution: When the features are linearly independent, the normal equations can be solved directly, yielding the unique OLS solution: .

You now have a complete theoretical understanding of how to find the optimal parameters for a linear regression model. In our next lesson, we will move to classification problems and derive the logistic regression model. This will provide a crucial contrast, as we will see that logistic regression does not have a closed-form solution, forcing us to explore the iterative optimization methods that are far more common in modern machine learning.

Can't find a good explanation? Sign up and we'll make it for you

Sign up