Machine Learning
&
Neural Networks Blog

Gradient Descent Explained with Visualizations

Calin Sandu | Published on October 14, 2024

Gradient Descent is one of the most fundamental optimization algorithms used in machine learning and deep learning. It helps minimize the cost function by iteratively adjusting model parameters to find the optimal solution. Imagine you are standing on the top of a hill, and your goal is to find the lowest point in the valley. In Gradient Descent, the cost function represents the terrain, and the algorithm helps you "walk downhill" toward the minimum point. At each step, you calculate the slope (or gradient) of the hill and take a small step in the opposite direction to move closer to the valley.

How It Works
Start at Random: Initially, you begin at a random point on the hill (i.e., random parameter values for the model). The first thing the algorithm does is compute the slope at that point.
Calculate Gradient: Using calculus, Gradient Descent calculates the gradient of the cost function. This is a vector of partial derivatives that points in the direction of the steepest ascent.
Update Parameters: Instead of moving uphill, the algorithm updates the model parameters in the opposite direction of the gradient (steepest descent). This process repeats until you reach a point where the slope is zero or near zero (indicating a minimum).

Visualizing Gradient Descent
Cost Function Landscape: Visualize the cost function as a 3D surface where the x and y axes represent different model parameters, and the z-axis represents the cost (or error). The surface may have multiple peaks (local maxima) and valleys (local minima), with one global minimum. Gradient Descent moves the model's parameters down this surface, trying to reach the lowest point possible.
Path of Descent: Imagine a point or ball rolling down this surface, starting at a high point and gradually moving downhill. The path it takes is the trajectory of the model parameters being updated. Initially, the steps may be large, but as the point approaches the minimum, the steps become smaller and more refined.
Learning Rate:
○ High Learning Rate: If the learning rate is too high, the algorithm takes large steps and may overshoot the minimum or even diverge entirely, bouncing around the surface without converging.
○ Low Learning Rate: If the learning rate is too small, the steps are very small, and the algorithm may take an excessive number of iterations to reach the minimum, or it may get stuck in a local minimum.
○ Optimal Learning Rate: The key is to find a learning rate that is neither too large nor too small, allowing the algorithm to converge efficiently to the global minimum.

Types of Gradient Descent
1. Batch Gradient Descent:
○ Details: This method computes the gradient using the entire dataset before updating the parameters. It provides a smooth and stable path toward the minimum but can be computationally expensive, especially with large datasets.
○ Visualization: In visual terms, you can imagine the ball moving smoothly down the slope with a clear, uninterrupted path toward the minimum. However, it may take longer to process a single step.
2. Stochastic Gradient Descent (SGD):
○ Details: In this approach, the gradient is calculated using a single random data point from the dataset at each iteration. This makes SGD much faster, but the path to the minimum is noisy and less stable, as the gradient fluctuates based on individual samples.
○ Visualization: Here, the ball zig-zags down the slope, sometimes moving erratically, but on average moving downward toward the minimum. Despite the noise, it often converges faster.
3. Mini-Batch Gradient Descent:
○ Details: Mini-batch Gradient Descent is a compromise between Batch Gradient Descent and SGD. It calculates the gradient using a small, random subset of the data (a mini-batch) at each step, balancing the stability of Batch Gradient Descent with the speed of SGD.
○ Visualization: The ball moves in relatively stable, controlled steps, combining the benefits of both methods. It has a smoother path than SGD but can still update the model more frequently than full Batch Gradient Descent.

Convergence and Local Minima
Global vs. Local Minima: Depending on the shape of the cost function, Gradient Descent may converge to a local minimum rather than the global minimum. This happens when the algorithm gets stuck in a valley that is not the lowest point on the entire surface. In practice, techniques like momentum or more advanced optimizers (e.g., Adam) help mitigate this by giving the algorithm the ability to escape shallow local minima and continue searching for the global minimum.
Plateaus and Saddle Points: Plateaus: Gradient Descent can get stuck or slow down if the cost function has flat regions where the gradient is near zero. This slows the algorithm’s progress, as updates to parameters become very small; Saddle Points: A saddle point is a region where the gradient is zero in one direction but not in others. The algorithm can be tricked into stopping here, although it is not a minimum.

Improvements to Gradient Descent
○ Momentum: Momentum adds a fraction of the previous step to the current update, allowing the algorithm to maintain speed when moving downhill and helping it push through small local minima or plateaus. It is visualized as the ball gaining inertia as it descends, smoothing the path.
○ Adam Optimizer: The Adam (Adaptive Moment Estimation) optimizer adjusts the learning rate for each parameter individually based on its past gradients. This improves the algorithm's convergence, especially in deep learning models with many parameters.
○ Learning Rate Scheduling: A common improvement is to reduce the learning rate as the algorithm progresses, allowing for larger steps early on and finer adjustments near the minimum. Visualizing this, the ball moves quickly at first, then slows as it approaches the bottom of the valley.


Below is an example Python code that uses Matplotlib and NumPy to visualize the gradient descent process on a simple quadratic function. This code demonstrates how gradient descent navigates the surface of the cost function and finds the minimum.


 import numpy as np
 import matplotlib.pyplot as plt
                            
 # Define the cost function J(theta) = (theta - 3)^2 (a simple quadratic)
 def cost_function(theta):
    return (theta - 3) ** 2
                            
 # Define the gradient of the cost function
 def gradient(theta):
    return 2 * (theta - 3)
                            
# Gradient descent function
def gradient_descent(starting_theta, learning_rate, num_iterations):
    theta_history = []
    cost_history = []
                            
    theta = starting_theta
                            
    for _ in range(num_iterations):
        cost = cost_function(theta)
        theta_history.append(theta)
        cost_history.append(cost)
                            
        theta -= learning_rate * gradient(theta)
                            
    return theta, theta_history, cost_history
                            
 # Initial parameters
 starting_theta = 0.0  # Starting point
 learning_rate = 0.1  # Learning rate
 num_iterations = 20  # Number of iterations
 
 # Execute gradient descent
 final_theta, theta_history, cost_history = gradient_descent(starting_theta, learning_rate, num_iterations)
                            
 # Plotting
 x = np.linspace(-2, 6, 100)  # X values for cost function
 y = cost_function(x)  # Y values for cost function
                            
 plt.figure(figsize=(12, 6))
                            
 # Subplot for cost function
 plt.subplot(1, 2, 1)
 plt.plot(x, y, label='Cost Function J(theta)')
 plt.scatter(theta_history, cost_function(np.array(theta_history)), color='red', label='Theta Updates')
 plt.title('Cost Function with Gradient Descent Updates')
 plt.xlabel('Theta')
 plt.ylabel('Cost J(theta)')
 plt.axhline(0, color='black', lw=0.5, ls='--')
 plt.axvline(3, color='green', lw=0.5, ls='--', label='Minimum (Theta = 3)')
 plt.legend()
                            
 # Subplot for cost history
 plt.subplot(1, 2, 2)
 plt.plot(range(len(cost_history)), cost_history, marker='o', label='Cost History')
 plt.title('Cost History throughout Gradient Descent')
 plt.xlabel('Iterations')
 plt.ylabel('Cost J(theta)')
 plt.axhline(0, color='black', lw=0.5, ls='--')
 plt.legend()
                            
 plt.tight_layout()
 plt.show()
                            


gradient

gradient

Gradient Descent is a powerful and versatile algorithm that lies at the heart of many machine learning models. By iteratively adjusting parameters and descending the cost function landscape, the algorithm finds the optimal solution. Understanding how it works, along with its limitations like local minima and learning rate challenges, can help you better tune your models for performance. Visualizing the process of Gradient Descent is essential to grasp its mechanics and improve its efficiency with advanced techniques like momentum, Adam, or learning rate schedules.


You might also like:

If you found this article useful and informative, you can support my work by accessing the below link.

Boost Your Brand's Visibility

Partner with us to boost your brand's visibility and connect with our community of tech enthusiasts and professionals. Our platform offers great opportunities for engagement and brand recognition.

Interested in advertising on our website? Reach out to us at office@ml-nn.eu.