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

Comparing Closed-Form and Iterative Optimization

Introduction

In our last lesson, we successfully derived the elegant closed-form solution for Ordinary Least Squares, . This is a powerful result, representing a class of optimization problems that can be solved directly and exactly, much like solving a simple algebraic equation. It gives us the precise location of the minimum of our cost function in a single calculation.

However, in the world of deep learning, you almost never hear about closed-form solutions. Instead, the entire field is built upon iterative methods, with Gradient Descent being the foundational algorithm. This lesson serves as the critical bridge between the classical, analytical world of OLS and the modern, iterative world of deep learning. Our objective is to dissect the fundamental trade-offs between these two approaches. We will explore why an exact solution isn't always the best one, especially from a computational performance perspective that is central to low-level engineering and high-performance systems.

Two Paths to Optimization: Direct vs. Iterative

Imagine you are at the top of a hilly terrain and want to find the lowest point in a specific valley. You have two ways to get there:

  1. The Direct Path (Closed-Form Solution): You use a satellite map and advanced calculations to pinpoint the exact coordinates of the valley's bottom. You then instantly teleport to that location. This is analogous to the OLS Normal Equation—one calculation, one perfect answer.
  2. The Iterative Path (Iterative Method): You are in a thick fog with only a compass and an altimeter. You check the steepness of the ground around you, take a step in the steepest downward direction, and repeat. You will eventually reach the bottom, step-by-step. This is the core idea of Gradient Descent.

The image below provides a great visual metaphor for these two strategies.

OLS provides a "one-shot" analytical solution, directly reaching the best fit. Gradient Descent is an iterative, "step-by-step" process that progressively moves towards the best fit.

For linear regression, where the cost function is a smooth, convex bowl, both paths lead to the same destination: the global minimum. The crucial question is, which path is more efficient? The answer depends entirely on the scale and complexity of the problem.

The Cost of an "Exact" Answer

Let's put on our performance engineer hats and analyze the computational cost of the OLS Normal Equation:

Here, is our design matrix (N observations, P features), and is our vector of parameters.

My question for you is: Looking at this formula, which single operation do you think becomes the primary computational bottleneck as the number of features, , becomes very large (e.g., thousands or millions)?

The most expensive operation here is the matrix inversion: . Let's break down the complexity:

  1. Forming : The matrix is and is . Multiplying them results in a matrix. This operation has a computational complexity of roughly .
  2. Inverting : Inverting a general matrix using standard algorithms like Gaussian elimination has a complexity of .
  3. Final Multiplications: The remaining multiplications, , are less costly, dominated by the first two steps.

When is large, the term for inversion dominates everything else. If you have 1,000 features, you're looking at an operation on the order of billion floating-point operations. If you have a million features (not uncommon in some modern ML contexts), this becomes ^3 = operations, which is computationally infeasible.

This analysis reveals the Achilles' heel of the Normal Equation: it scales poorly with the number of features.

The following reading from a university lecture slide deck crisply summarizes this exact point.

Lecture 2 - Linear Methods for Regression, Optimization

These slides from the University of Toronto's Introduction to Machine Learning course directly compare the efficiency of a direct solution versus gradient descent.

Focus on the slide titled "Why gradient descent, if we can find the optimum directly?". Pay close attention to the computational complexity comparison: O(D^3) for matrix inversion versus O(ND) for a Gradient Descent update. Note that their D (for dimension) is the same as our P (for parameters/features).

The Cost of an "Approximate" Step

Now, let's analyze the iterative approach. As the UofT slides mention, the core of Gradient Descent is an update rule we will derive formally in the next lesson. For now, we can state its form:

This means we update our current parameter estimate by taking a small step (controlled by the learning rate ) in the direction of the negative gradient of our cost function, .

For OLS, we already found the gradient: (including the averaging factor often used in ML). Let's analyze the cost of computing this gradient once:

  1. Compute predictions: requires operations.
  2. Compute residuals: is an element-wise subtraction, .
  3. Compute final gradient: requires operations.

The total cost for one step of this "batch" gradient descent (so-called because it uses the entire batch of N data points) is . If we need iterations to converge, the total cost is .

The Computational Trade-Off

We now have the two sides of our trade-off:

  • Normal Equation Cost:
  • Gradient Descent Cost:

Let's analyze two scenarios that are common in machine learning.

Scenario 1: High Dimensionality (Large )

Imagine a genomics problem where you have a few thousand patients () but are measuring millions of genetic markers ().

  • Normal Equation: The term becomes astronomical. It's simply not possible to invert a million-by-million matrix.
  • Gradient Descent: The cost is . While large, this is linear in and is far more manageable than the cubic relationship of the Normal Equation.

Conclusion: For problems with a large number of features, Gradient Descent is the only viable option. This is the primary reason it is the default choice for deep neural networks, which are effectively functions with millions of parameters ().

Scenario 2: Massive Datasets (Large )

Now consider a web-scale problem, like predicting ad click-through rates. You might have only a few hundred features (), but billions of user interactions ().

  • Normal Equation: The term is tiny ( million). The term becomes , which is large but potentially a one-time cost. The method is still computationally viable.
  • Batch Gradient Descent: The cost of a single step, , becomes . This means every single step requires a full pass over the entire massive dataset, which can be prohibitively slow.

This seems to favor the Normal Equation. However, the iterative approach has another trick up its sleeve: Stochastic Gradient Descent (SGD).

Instead of computing the gradient over the entire dataset of points, SGD computes it using just one randomly chosen data point at a time. The update cost plummets from to just . A common compromise is mini-batch SGD, which uses a small batch of samples (), for a cost of .

This allows the algorithm to make rapid, albeit noisy, progress. While each step might not point perfectly downhill, the average direction over many steps does, and it can approach the minimum far more quickly in terms of wall-clock time than a single, slow batch gradient descent step.

Andrew Ng's lecture on this topic provides an excellent explanation of this specific trade-off.

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

This section from Stanford's classic CS229 lecture clearly distinguishes between batch and stochastic gradient descent and their implications for large datasets.

Watch the segment from Batch vs. Stochastic Gradient Descent. Focus on the core argument: with very large datasets (large M, which is our N), computing the sum over all M examples for a single update in batch gradient descent is too slow. Stochastic gradient descent provides a way to make progress much more quickly by using single examples.

Beyond Computational Cost: Generality and Stability

The trade-offs don't end with speed. There are other crucial factors that make iterative methods the de facto standard for modern AI.

  1. Generality: The Normal Equation is specific to the linear regression model with a squared-error cost function. It relies on the cost function having a single global minimum that can be found by setting the gradient to zero. Most interesting problems, including nearly all of deep learning, involve non-linear models and non-convex cost functions with many local minima. For these, no closed-form solution exists. Gradient descent, however, is a general-purpose tool; as long as you can compute a gradient, you can apply it.

  2. Numerical Stability: The matrix inversion is numerically unstable if the matrix is "ill-conditioned." This happens when features are highly correlated (multicollinearity), making the matrix nearly singular (i.e., its determinant is close to zero). In such cases, small changes in the input data can lead to huge changes in the resulting inverse, making the solution unreliable. Gradient descent does not suffer from this specific instability.

  3. Online Learning: With SGD, the model can be updated as new data arrives one point at a time. This is essential for "online" systems that must learn continuously from a stream of data, a scenario where re-calculating the Normal Equation from scratch would be infeasible.

The StackExchange discussion below provides further excellent points from practitioners on this topic.

Why use gradient descent for linear regression, when a ...

This is a highly-cited discussion on StackExchange where several experts weigh in on the practical reasons for choosing gradient descent over the normal equation.

Read the first section of the top answer for a clear breakdown of the computational complexity. Continue with the next few paragraphs in the same answer, which discuss parallelization, memory requirements, and numerical stability with collinear predictors. Read the answer beginning with "In high level...", which frames the problem as "direct vs. iterative" methods and highlights the generality of gradient descent for other models like neural networks. Finally, read the short answer beginning with "One other reason...", which reinforces the point about non-convex problems where closed-form solutions are impossible.

Conclusion

We have established that choosing an optimization algorithm is a classic engineering decision involving critical trade-offs. While the Normal Equation provides an elegant, exact solution for linear regression, it is a specialist tool that breaks down under the scale and complexity of modern machine learning problems.

Key Takeaways:

  • Optimization Methods: Can be broadly categorized into direct (closed-form) and iterative methods.
  • Computational Cost: The Normal Equation's cost makes it infeasible for problems with many features (). Gradient Descent's cost is more scalable.
  • Scalability with Data Size: Batch Gradient Descent is slow for large datasets (), but this is solved by using Stochastic Gradient Descent (SGD), which updates on single points or small mini-batches.
  • Generality is Key: Iterative methods like Gradient Descent are far more general. They can be applied to almost any model for which we can compute a gradient, including the complex, non-linear, and non-convex models used in deep learning, where no closed-form solution exists.

The limitations of the closed-form solution are not a failure, but rather the primary motivation for developing the powerful, flexible, and scalable iterative methods that underpin all of modern AI.

Preview of the Next Lesson:

We have now established the "why" and "when" of iterative optimization. In our next lesson, we will dive into the "how." We will formally derive the gradient descent update rule from first principles using a first-order Taylor approximation of the loss function, giving us a rigorous mathematical foundation for the intuitive idea of "walking downhill" to find a minimum.

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

Sign up