Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 57

Gradient Descent for Linear Regression

Recommended resources

Hello! Welcome to the final lesson in our module on Matrix Calculus and Optimization.

In our last lesson, we mastered the Gradient Descent algorithm, our tool for finding the minimum of a function by taking iterative steps "downhill." We saw that the core of the algorithm is the update rule , which requires the gradient, .

Today, we'll put all the pieces together. Our goal is to apply this to a foundational machine learning model: linear regression. To do this, we need to:

  1. Define the model and its associated cost function.
  2. Use our matrix calculus skills to derive the gradient of that cost function.

This is a milestone lesson. By the end, you will have derived the complete update rule for training a linear regression model, a cornerstone of both statistics and machine learning, and a key pattern you'll see again in your deep learning studies.


1. Setting Up the Linear Regression Problem

Let's start by formalizing what we mean by "linear regression." Imagine we want to predict house prices based on features like size, number of bedrooms, etc. This is a classic regression task.

The following video from Stanford's CS229 Machine Learning course provides an excellent introduction. It defines the model's structure (the "hypothesis"), the notation, and the cost function we aim to minimize.

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

Watch this segment from Andrew Ng's lecture on Linear Regression. It will set up the entire problem, from defining the hypothesis function to formalizing the cost function that measures our model's error.

Please watch from 01:46 to 17:15. Part 1 (01:46 - 12:36): Focus on how the hypothesis function, h(x), is defined. Pay attention to the introduction of the 'dummy feature' x_0=1, which allows the intercept term ( heta_0) to be included in the vector dot product. This is a standard and very useful trick. Part 2 (12:46 - 17:15): This part introduces the cost function, J( heta), which is the Mean Squared Error (MSE). Understand its structure as the average squared difference between predictions and actual values.

Let's summarize the key definitions from the video:

  • Hypothesis Function: Our model's prediction for a given input is a linear function of its features:

    By defining , we can write this compactly using vector notation:

    Here, is the vector of parameters (or weights) we want to learn.

  • Cost Function (Mean Squared Error): To measure how well our model performs, we use the cost function . It calculates the average of the squared errors over all training examples.

    The is included for mathematical convenience, as it will cancel out when we take the derivative. Minimizing this function means finding the parameters that make our predictions as close as possible to the true values .

Scatterplot with Regression Line for Linear Regression Model Evaluation
This plot visualizes the goal of linear regression. The green dots are the actual data points. The blue line is our model's prediction, \(h_\theta(x)\), determined by the parameters \(\theta\). Our task is to find the \(\theta\) that makes this line the "best fit" by minimizing the cost function.


2. Deriving the Gradient of the Cost Function

Now for the main event. We have our optimization algorithm (Gradient Descent) and our target function to minimize (). The missing ingredient is the gradient, . We will derive this first using familiar single-variable calculus rules, and then using the more powerful matrix calculus notation.

2.1 The Scalar (Component-wise) Approach

Let's find the partial derivative of with respect to a single parameter, . This tells us how a small change in just one weight affects the total error.

The video you just watched provides a quick derivation. The following video from StatQuest gives a more deliberate, step-by-step walkthrough of the same process. Seeing it twice from different perspectives will help solidify your understanding.

Gradient Descent, Step-by-Step

This StatQuest video breaks down the derivative calculation very clearly. It starts with the derivative for the intercept and then generalizes to the slope, which maps directly to our heta_j.

Watch from 07:18 to 09:00 and from 15:32 to 19:26. Part 1 (07:18 - 09:00): This shows the application of the chain rule to a squared error term for a single parameter (the intercept). Part 2 (15:32 - 19:26): This extends the concept to finding partial derivatives for both the intercept and the slope, defining the 'gradient' as the collection of these partial derivatives.

Let's write out the steps formally. We want to compute .

  1. Start with the cost function:

  2. Differentiate with respect to . We can move the derivative inside the sum:

  3. Apply the chain rule, :

  4. The derivative of the inner part is . The only term in the sum that depends on is , so the derivative is simply .

  5. Substitute back and simplify (the 2 and cancel):

This gives us the formula for each component of the gradient vector. We could implement gradient descent using this formula in a loop, but there is a more elegant way.

2.2 The Matrix Calculus Approach

Now, let's use matrix notation to find the entire gradient vector in one go. This is more concise and, given your computer science background, you'll appreciate that it maps directly to highly optimized library functions (like in NumPy or PyTorch).

This article provides an excellent, compact derivation using the matrix calculus identities we've discussed.

Linear Regression, in Two Ways

The article 'Linear Regression, in Two Ways' by Jake Tae provides a beautiful derivation of the gradient using matrix calculus. It's exactly the application we've been building towards.

Read the sections 'The Gradient' and 'Error Minimization'. 'The Gradient' section will refresh your memory on the key identities: ( abla_x b^T x = b) and ( abla_x x^T A x = 2Ax). 'Error Minimization' is the core of this lesson. Follow the steps: rewriting the MSE in matrix form, expanding the terms, and finally taking the gradient.

Let's retrace the key steps from the article.

  1. Define the Matrices:

    • : The design matrix of size , where each row is a training example .
    • : The vector of true values of size .
    • : The vector of parameters of size .
  2. Rewrite the Cost Function in Matrix Form:
    The vector of all predictions is . The vector of errors is . The sum of squared errors is the squared Euclidean norm of the error vector, which can be written as .

  3. Expand the Expression:

    Since is a scalar, it equals its own transpose: . So the two middle terms are identical.

  4. Take the Gradient: Now we differentiate this expression with respect to , using the identities and .

    Simplifying gives us our final result:

This compact, elegant formula is the gradient of the linear regression cost function.

Test your understanding!

Look at the two forms of the gradient we derived:

  1. Scalar component:
  2. Matrix form:

Can you explain why the -th row of the matrix result is equal to the scalar formula? (Hint: Think about what the matrix-vector product represents).

Show answer

Let's break down the matrix form .

  • The term is an column vector of the errors for each training example: .
  • The matrix is an matrix. Its -th row is .

When we perform the matrix-vector multiplication , the -th element of the resulting vector is the dot product of the -th row of and the error vector.

This dot product is:

Which can be written as a sum:

Finally, dividing by gives us , which is exactly the scalar formula for . This confirms the two derivations are consistent!



Conclusion

Congratulations on completing the final lesson of this module! We have successfully connected all the dots, from the abstract concept of a gradient to its practical application in a core machine learning algorithm.

Key Takeaways:

  • The linear regression model is defined by the hypothesis .
  • The performance of the model is measured by the Mean Squared Error cost function: .
  • Using matrix calculus, we derived the gradient of this cost function: .
  • This gradient is the final piece needed to apply the Gradient Descent algorithm, whose update rule for linear regression is:

Preview of the Next Module:

You have now completed the "Matrix Calculus and Optimization" module. We've journeyed from fundamental derivative rules to building and applying the most important optimization algorithm in machine learning.

In the Stanford video, you may have noticed a brief mention of the "Normal Equation," an alternative, non-iterative method for solving for by setting the gradient to zero directly. This provides a perfect bridge to our next module, "Applications in Data Analysis." We will start by exploring this analytical solution to the least squares problem, connecting our optimization knowledge to direct methods of solving linear systems, which are heavily used in data science.