Skip to main content

Welcome to a Grasp lesson

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

Lesson 61

Optimizing Linear Regression with Gradient Descent

Recommended resources

Hello! Welcome to your next lesson in the "Foundations of Machine learning" module.

In our last lesson, you learned how to describe a linear regression model using a mathematical equation, , and how to measure its performance with the Mean Squared Error (MSE) cost function, . We ended with a key question: how do we find the values of and that make the cost as low as possible?

Today, we'll answer that question. Your learning outcome is to apply gradient descent to optimize the cost function of a linear regression model. This powerful algorithm is the engine that drives the learning process for linear regression and many other models you'll encounter in your journey toward the GATE exam.

1. The Intuition Behind Gradient Descent

Imagine you are standing on a foggy hill and want to get to the lowest point in the valley. Because of the fog, you can't see the bottom. What's a sensible strategy? You could look at the ground beneath your feet, find the direction of the steepest downward slope, and take a step in that direction. If you repeat this process, you will eventually reach the bottom.

This is exactly the intuition behind gradient descent. In our case:

  • The "hill" is our cost function, . The height at any point is the cost.
  • Our "position" is determined by the current values of our parameters, and .
  • The "lowest point" is the minimum cost, which corresponds to the best-fit line.
  • Finding the "steepest downward slope" involves a bit of calculus.

The following video from StatQuest provides an excellent step-by-step walkthrough of this idea. It starts by optimizing just one parameter (the intercept) to make the concept clear, before moving on to both.

Gradient Descent, Step-by-Step

This video, titled 'Gradient Descent, Step-by-Step' from the StatQuest channel, is fantastic for building a strong intuition. It visually and methodically explains how the algorithm takes iterative steps to find the optimal parameter values.

Please watch from the beginning up to 15:49. Focus on understanding: The overall goal: to find the parameters that minimize the sum of squared residuals (our cost function). How to take a derivative of the cost function to find the slope. The concept of a learning rate and how it's used to calculate the step size. The iterative process of updating the parameter until the steps become very small.


2. The Mathematics of Gradient Descent

As you saw in the video, the "direction of steepest descent" is found by calculating the derivative of the cost function. When we have more than one parameter, like and , we use partial derivatives. The collection of all partial derivatives is called the gradient.

The core of the gradient descent algorithm is the update rule, which is applied repeatedly to each parameter:

Let's break this down:

  • : The parameter we are updating (either or ).
  • :=: This means "is updated to". We are assigning a new value to .
  • (alpha): The learning rate. This is a small positive number (e.g., 0.01) that controls how big of a step we take.
  • : The partial derivative of the cost function with respect to the parameter . This term gives us the slope of the cost function.

The entire term is the step size you saw in the video. By subtracting this step, we are moving "downhill" against the gradient.

The Update Rules for Linear Regression

For our linear regression cost function, the partial derivatives are:

  • For the intercept :
  • For the slope :

(You don't need to derive these from scratch for the GATE exam, but you should understand their role. They represent the slope of the cost function with respect to each parameter.)

So, in each step of gradient descent, we simultaneously update our parameters using these specific rules:

To see how this works with both parameters, let's continue with the StatQuest video.

Gradient Descent, Step-by-Step

This next segment extends the concept to optimizing both the intercept and slope at the same time, which is exactly what we need for our linear regression model.

Please watch from 15:49 to 21:55. Notice how we now have two derivatives (a 'gradient') and we update both parameters in each step.

Test your understanding!

Imagine you are at a point on the cost "hill" where the partial derivative with respect to is negative (i.e., ). According to the update rule, will the value of increase or decrease in the next step? Why is this a good thing?

Show answer

The update rule is . Subtracting a negative number is the same as adding a positive number. Therefore, will increase.

This is desirable because a negative derivative means the cost function slopes downwards as increases. By increasing , we are moving "downhill" towards the minimum cost.


3. The Algorithm in Practice: A Python Implementation

Now that you have the theory and intuition, let's see how this translates into code. Since you prefer a balanced approach, we'll dive into a from-scratch implementation. This will solidify your understanding far better than just using a pre-built library function.

The following article, which you started in the last lesson, provides a clean Python implementation of linear regression using gradient descent.

A Deep Dive into Linear Regression: Cost Functions, ...

The article 'A Deep Dive into Linear Regression' by Cəlal İbrahimli provides a full implementation of the concepts we've just discussed. Studying this will connect the math directly to practical code.

Please read Section 3: Applying Gradient Descent and Section 4: Linear Regression in Python. Focus on: How the 'foggy hill' analogy connects to the mathematical update rule. The role of the learning rate, α. In the Python code, pay close attention to the fit method. Identify where the predictions (y_pred), errors, gradients (grad_k, grad_b), and parameter updates are calculated within the loop. This directly maps to the update rules we just discussed.

Let's quickly summarize the complete algorithm, as seen in the article's code:

  1. Initialize parameters: Start with some initial values for and (e.g., self.k_ = 0.0, self.b_ = 0.0).
  2. Set hyperparameters: Choose a learning_rate () and the number of n_iters (iterations).
  3. Iterate: Loop for the specified number of iterations. In each iteration:
    a. Calculate predictions (): Use the current and to predict for all data points.
    b. Calculate the gradients: Use the derivative formulas to compute the gradients for and .
    c. Update parameters: Apply the update rules to get the new values for and .
  4. Finish: After the loop finishes, the final values of and define your best-fit line.

The image below beautifully connects the process of descending the cost function to finding the best-fit line for the data.

Gradient Descent for Linear Regression Visualization
This image shows the two key aspects of our task. On the left, the red arrows show our algorithm taking steps down the bowl-shaped cost function to find the minimum. On the right, the blue line shows the result of this optimization: a line that fits the data points well.

Conclusion

Congratulations! You have now learned the complete process of training a simple linear regression model. You not only understand the model's equation but also the optimization algorithm that brings it to life.

Key Takeaways:

  • Gradient Descent is an iterative optimization algorithm used to find the minimum of a cost function.
  • It works by repeatedly taking steps in the direction opposite to the gradient (the direction of steepest ascent).
  • The learning rate () is a crucial hyperparameter that controls the size of each step. If it's too large, the algorithm might fail to converge; if it's too small, training will be very slow.
  • The update rule for each parameter is: .
  • In Python, this process is implemented as a loop that calculates predictions, computes gradients, and updates the parameters at each step.

Preview of the Next Lesson:
Linear regression is a powerful parametric model, where our goal is to learn a fixed set of parameters ( and ). In the next lesson, we will explore a completely different approach to prediction by implementing the k-Nearest Neighbors (k-NN) algorithm. This is a non-parametric model, which will give you a broader perspective on the different ways machine learning algorithms can learn from data.