Skip to main content

Welcome to a Grasp lesson

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

Lesson 4

Gradient Descent Fundamentals

This lesson is built with resources from youtube.com, linkedin.com and 1 more site.

Hello! Welcome to your fourth lesson in the "Mathematical Foundations for AI" module.

In the last lesson, we explored the "why" behind model improvement. You learned that the gradient () is a vector of partial derivatives that points in the direction of the steepest ascent of a function. We concluded that to minimize an error or cost function, we must move in the direction opposite to the gradient.

Today, we'll put that theory into practice. This lesson is all about turning that concept into a working algorithm. Our learning outcome is to calculate gradients and implement gradient descent to minimize a simple function. This algorithm is the engine that drives training for almost all modern machine learning models. For you as a software engineer, this is where the math meets the code.

1. The Gradient Descent Algorithm: Rolling Down the Hill

The core idea of gradient descent is beautifully simple and is often explained with an analogy: imagine you are standing on a hill in thick fog and want to get to the lowest point. You can't see the whole landscape, but you can feel the slope under your feet. The most straightforward strategy is to find the direction of the steepest descent and take a small step that way. Repeat this process, and you will eventually find your way to a valley.

This image illustrates the iterative process of gradient descent. Starting at an initial weight (`w_old`), we compute the gradient (the slope δJ/δw) and take a step downhill, determined by the learning rate (α), to find a `w_new` with a lower loss.

This iterative process is captured by a single update rule:

Let's break this down:

  • (theta) represents all the parameters of our model (the weights and biases). In our simple examples today, it might just be a single variable like .
  • is the cost function we want to minimize.
  • is the gradient of the cost function. It tells us the direction of the steepest ascent.
  • (alpha) is the learning rate, a small positive number. This is a crucial hyperparameter that controls how big of a step we take.

To get a deeper intuition for this, the following video provides a fantastic conceptual overview.

Gradient descent, how neural networks learn Chapter 2, Deep learning

This classic video from 3Blue1Brown, 'Gradient descent, how neural networks learn,' perfectly visualizes the concepts of a cost function and how repeatedly stepping in the direction of the negative gradient leads to a minimum.

About five minutes in, watch the segment on gradient descent analogies. Focus on how the idea of finding the slope for a 1D function extends to finding the gradient vector for a 2D function. This will solidify the 'ball rolling downhill' analogy.


2. Gradient Descent in Action: Implementation from Scratch

Now it's time to build this algorithm. The best way to understand gradient descent is to implement it yourself. We'll use a video that walks through the entire process in Python, from a simple 2D function to a more complex 3D one. This will give you a clear, practical model to follow.

Gradient Descent From Scratch in Python - Visual Explanation

The video 'Gradient Descent From Scratch in Python' by NeuralNine is a complete, hands-on tutorial. It's perfect for your background as it focuses on clear code and visual results.

Please watch the first part of the video. This section covers the implementation for a simple 1D function, y = x^2, and demonstrates the critical role of the learning rate. Follow along with the code logic.

Let's summarize the key steps from the video for the 1D case:

  1. Define the Function and its Derivative: For a simple function like , the derivative is . In 1D, the "gradient" is just this single derivative.
  2. Initialize Parameters: We need to set three things:
    • A starting position (e.g., current_position = 80).
    • A learning rate (e.g., learning_rate = 0.01).
    • The number of steps to take (e.g., iterations = 1000).
  3. Create the Iterative Loop: A for loop runs for the specified number of iterations.
  4. Apply the Update Rule: Inside the loop, the core logic is executed:
    • grad = derivative(current_x)
    • new_x = current_x - learning_rate * grad
    • The position is updated for the next iteration.

As the video clearly shows, the learning rate is critical.

  • A small learning rate leads to very slow, but stable, convergence.
  • A large learning rate can cause the algorithm to overshoot the minimum, leading to oscillation or even divergence (where the error gets worse and worse). Finding a good learning rate is a key part of training machine learning models.
Test your understanding!

Imagine you are using gradient descent on the function , where the gradient is . Your starting point is and your learning rate is exactly 0.9. What will happen over the first few iterations? Will it converge?

Show answer

Let's trace the steps:

  • Start:
  • Iteration 1:
    • Gradient at :
    • New position:
  • Iteration 2:
    • Gradient at :
    • New position:
  • Iteration 3:
    • Gradient at :
    • New position:

The algorithm is oscillating back and forth across the minimum at , but the steps are getting smaller. It is converging, but slowly and with a lot of overshooting. If the learning rate were 1.0 or higher, it would diverge.


3. Extending to Multiple Dimensions

Real-world cost functions depend on millions of parameters, not just one. This is where the gradient vector you learned about in the previous lesson becomes essential. Instead of a single derivative, we have a vector of partial derivatives, one for each parameter.

The update rule remains conceptually the same, but it becomes a vector operation:

Here, is the vector of all parameters, and is the gradient vector. Each parameter is updated simultaneously based on its partial derivative.

Let's see this in action by continuing with the video.

Gradient Descent From Scratch in Python - Visual Explanation

The second half of the NeuralNine video extends the concept to a 3D function, providing a clear visualization of how gradient descent works in a higher-dimensional space.

Starting around 17 minutes in, watch the implementation of gradient descent for a function z(x, y). Notice how it calculates a gradient vector [x_derivative, y_derivative] and updates both x and y in each step. This directly visualizes the concepts from our last lesson.

The key takeaway is that the logic doesn't change. We just calculate the partial derivative for each variable (x and y in the video's example) and update each variable according to its own partial derivative. The principle scales up to millions of parameters in a large neural network.


Your Turn: Putting it All Together

Watching the implementation is a great start, but true understanding comes from doing. Your task now is to replicate the gradient descent algorithm yourself. The resources below provide clean, complete code examples that you can use as a reference.

Python Practice: Implementing Gradient Descent

This article, 'Python Practice: Implementing Gradient Descent,' provides a concise, well-commented implementation for minimizing a 1D quadratic function. It's a great static reference to complement the video.

Read through the article and try to implement the gradient_descent function in a Python environment (see the implementation setup). Then, as the article suggests, review the parameter experiments and experiment by changing the initial_x, learning_rate, and iterations to see how it affects the outcome.

When writing the code, focus on:

  • Defining the function and its gradient separately.
  • Setting up the hyperparameters.
  • Implementing the core update loop.

This hands-on practice will solidify your understanding of the algorithm that powers nearly all of deep learning.


Conclusion

In this lesson, you bridged the gap between theory and practice. You've successfully implemented one of the most fundamental algorithms in machine learning.

Here are the key takeaways:

  • Gradient Descent is an iterative optimization algorithm that minimizes a function by repeatedly taking steps in the direction opposite to the gradient.
  • The core of the algorithm is the update rule: new_params = old_params - learning_rate * gradient.
  • The learning rate () is a critical hyperparameter that controls the step size and must be tuned carefully to ensure stable and efficient convergence.
  • The algorithm scales from a single variable to millions by using the gradient vector, where each parameter is updated based on its corresponding partial derivative.

You've now covered the essentials of calculus for AI: derivatives, gradients, and gradient descent.

In the next lesson, we will shift gears and move to the second pillar of mathematical foundations: probability and statistics. You will start by learning to describe common probability distributions, which are essential for modeling data and uncertainty in AI.