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

Matrix Calculus for OLS

Introduction

Welcome to the module on Numerical Optimization. In our last lesson, we explored how information theory gives us principled objective functions like cross-entropy, which quantify the "distance" between our model's predictions and the ground truth. We now have a clear understanding of what we are trying to minimize. The crucial next question is how we minimize it.

Today, we'll start this journey by examining Ordinary Least Squares (OLS), the cornerstone of classical linear regression. OLS is a perfect starting point because it represents a class of optimization problems that can be solved directly and exactly, yielding what is known as a closed-form solution. By deriving this solution from first principles, you will master a fundamental technique and, more importantly, build a conceptual anchor for understanding why deep learning requires a completely different, iterative approach.

Our goal is to derive the famous OLS formula using the matrix calculus and linear algebra tools we've developed in previous modules.

Setting Up the Linear Regression Problem

At its core, linear regression models a relationship between a set of independent variables (or features) and a dependent variable (the target) as a linear equation. Let's formalize this using matrix notation, which is the natural language for these problems.

Suppose we have observations. For each observation , we have features.

  • Let be an vector of the observed target values.
  • Let be an matrix, often called the design matrix, where each row is an observation and each column is a feature.
  • Let be a vector of unknown parameters or weights that we want to estimate.
  • Let be an vector of unobserved random errors.

The underlying "true" model is assumed to be:

This equation states that our observed data is generated by a systematic, linear part and a stochastic, random part . Our goal is to find the best possible estimate of the unknown parameters , which we'll call .

To ground these definitions, please review the first section of the following document from Stanford.

OLS in Matrix Form

This document provides a clear, formal definition of the linear model in matrix form.

Focus on the section "The True Model". Pay close attention to the dimensions of each matrix and vector (y, X, \beta, \epsilon) to ensure you understand how they fit together.

The OLS Objective: Minimizing Residuals

How do we define the "best" estimate ? OLS provides a clear criterion: the best is the one that minimizes the Sum of Squared Residuals (RSS).

First, let's define the residuals. For a given estimate , our model's predictions are . The residuals are the differences between the observed values and our predicted values . The vector of residuals, , is:

The RSS is simply the sum of the squares of these individual residuals, . In vector notation, this is the squared L2-norm of the residual vector, which can be elegantly written as the dot product .

So, the OLS optimization problem is to find the that minimizes this objective function, :

The image below illustrates this concept. The blue dots are the data points, the red line is the fitted model . The dotted red lines are the residuals , and the goal of OLS is to adjust the slope and intercept of the red line to make the total area of the red squares (the squared residuals) as small as possible.

On the left, the vertical dotted lines show the residuals—the error between each data point and the regression line. On the right, the red squares visualize the squared residuals. OLS minimizes the sum of the areas of these squares.

The Geometric Viewpoint

There's a beautiful geometric interpretation of this process that directly leverages our work on vector projections. The vector of predictions, , is a linear combination of the columns of . This means must lie in the column space of , denoted .

The OLS problem is thus equivalent to finding the vector in the subspace that is closest to the observed vector . As we know from our lesson on projections, the vector in the subspace closest to is its orthogonal projection. This means the residual vector, , must be orthogonal to the entire column space of .

This diagram shows the geometric view of OLS. The vector \(y\) is projected orthogonally onto the subspace spanned by the columns of X (the blue plane). The projection, \(X\hat{\beta}_{\text{OLS}}\), is our vector of predictions \(\hat{y}\), and the residual vector \(\epsilon\) (labeled here, but representing our residual vector \(e\)) is orthogonal to the subspace.

The Derivation: Applying Matrix Calculus

We have our objective function: . From calculus, we know that to find the minimum of a function, we take its derivative, set it to zero, and solve. Here, our variable is a vector, so we need to compute the gradient.

This leads to our Socratic question for today:

We need to find . Let's first expand the objective function. What does become when you apply the transpose rules?

Think about how you would expand . The matrix equivalent is which expands to .

Let's apply this:

Notice that is a scalar (a ). The transpose of a scalar is just itself. So, . This means the two middle terms are identical. Our objective function simplifies to:

Now, we need to differentiate this expression with respect to the vector . This requires a couple of key matrix calculus identities. The following video provides excellent intuition by building up from simple scalar derivatives to the vector and matrix forms we need.

Derivative of a Matrix : Data Science Basics

This video from ritvikmath builds the necessary matrix derivative rules from first principles, starting with scalar analogies.

Watch the introduction from the start to see the analogy with scalar derivatives. Next, watch the derivation of \frac{d}{dx}(Ax) = A from this segment. This is analogous to our term -2\hat{\beta}^T X^T y. Finally, watch the derivation of \frac{d}{dx}(x^T A x) = 2Ax from this final part. This is what we need for the term \hat{\beta}^T X^T X \hat{\beta}.

From the video and our calculus background, we have the two main results we need:

  1. (for a symmetric matrix )

Let's apply these to our objective function term by term:

  • Term 1: is a scalar constant with respect to , so its derivative is .
  • Term 2: Using , we treat as and as . The derivative is .
  • Term 3: Using , we treat as and as . Note that is always symmetric, so the rule applies. The derivative is .

Combining these, we get the gradient:

To find the minimum, we set the gradient to zero:

This gives us the famous Normal Equations:

This equation is fundamental. It arises directly from the condition that the residual vector must be orthogonal to the column space of , i.e., , which simplifies to the same result.

To get the final solution for , we just need to solve this linear system. If the matrix is invertible (which is true if the columns of are linearly independent), we can pre-multiply both sides by its inverse:

And there we have it, the closed-form solution for the Ordinary Least Squares estimator:

For a comprehensive walkthrough of this entire derivation, I highly recommend the following reading and video.

OLS in Matrix Form

This document formally derives the Normal Equation and the OLS estimator.

Read the section "Criteria for Estimates" to see the objective function being set up and expanded. Carefully study the section starting from the differentiation to the final solution. This section also includes a handy summary of the matrix differentiation rules we used.

Normal Equation Derivation for Regression

This video by Shivank Goel provides a step-by-step narration of the derivation, which can help solidify your understanding.

Watch from the start to see the loss function set up in matrix notation. The segment from here introduces the concept of the gradient and the derivative rules. Finally, watch the core derivation from this point, where the gradient is computed, set to zero, and solved.

Conclusion

In this lesson, we have derived the closed-form solution for Ordinary Least Squares from first principles. This is a classic result in statistics and machine learning and a perfect illustration of an optimization problem that can be solved analytically. By defining a cost function—the sum of squared residuals—we were able to use matrix calculus to find the exact parameters that minimize it.

Key Takeaways:

  • Linear regression can be expressed compactly using matrix notation as .
  • The OLS objective is to minimize the sum of squared residuals, .
  • Geometrically, OLS finds the orthogonal projection of the observed data vector onto the subspace spanned by the feature matrix .
  • By setting the gradient of the objective function to zero, we derive the Normal Equations: .
  • Solving the Normal Equations gives the closed-form OLS solution: .

Preview of the Next Lesson:

The ability to find a direct, analytical solution like this is powerful, but rare. The calculation involves inverting the matrix, an operation that is computationally expensive and numerically unstable for very large or ill-conditioned matrices. More importantly, for the vast majority of models in deep learning—with their nested non-linear functions and millions of parameters—no such closed-form solution exists. We simply cannot "solve for " by inverting a matrix.

This limitation is precisely what motivates the need for iterative optimization. In our next lesson, we will explore the fundamental trade-offs between closed-form and iterative methods and derive the workhorse algorithm of all of deep learning: gradient descent.

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

Sign up