Articles / AI · Part 23

Gradient Descent in Artificial Intelligence

Understand how Gradient Descent helps machine learning models learn by reducing their errors. Explore its mathematical formula, Python implementation, learning rate, types, limitations, and applications.

Gradient Descent in Artificial Intelligence

Imagine you are standing on a mountain, and your goal is to reach the lowest point in the valley.

You cannot see the entire landscape. You can only examine the slope beneath your feet and decide which direction takes you downhill. You take a step, check the slope again, and repeat the process until you reach a point where further movement does not reduce your height.

This is the basic intuition behind Gradient Descent, one of the most important optimisation algorithms used in Artificial Intelligence and Machine Learning.

In machine learning, models make predictions and calculate how far those predictions are from the actual answers. Gradient Descent helps improve the model by adjusting its parameters to reduce this error.

Let’s understand how it works.

1. What Is Gradient Descent?

Gradient Descent is an optimisation algorithm that minimises a function by repeatedly adjusting its parameters in the direction of the steepest decrease.

In Machine Learning, this function is often called the Loss Function or Cost Function. It measures how far a model’s predictions are from the expected results.

The objective is simple: find parameter values that produce a lower loss.

For example, suppose a model predicts house prices. Its predictions may initially be far from the actual prices. By adjusting its parameters, the model can gradually reduce its prediction error.

Gradient Descent provides a systematic way to make these adjustments.

2. Understanding the Gradient

To understand Gradient Descent, we first need to understand the term gradient.

A gradient tells us how a function changes as its input variables change. It points in the direction of the steepest increase in the function.

If we want to minimise the function, we move in the opposite direction of the gradient.

Consider a simple curve representing a cost function.

  • A positive slope means the function increases as we move to the right.
  • A negative slope means the function decreases as we move to the right.
  • A zero slope indicates a stationary point, where the derivative is zero.

The gradient helps determine which direction to move to reduce the cost.

For a function with one variable, the gradient is simply its derivative. For a function with multiple variables, it is a vector containing the partial derivatives with respect to each variable.

3. The Gradient Descent Formula

The standard parameter update rule is:

\[
\theta_{\text{new}}=\theta_{\text{old}}-\alpha\nabla J(\theta)
\]

Let’s understand each part.

  • \(\theta\): The model parameters that we want to optimise.
  • \(J(\theta)\): The cost or loss function.
  • \(\nabla J(\theta)\): The gradient of the cost function.
  • \(\alpha\): The learning rate, which controls the size of each update.

The minus sign is important. Since the gradient points towards the steepest increase, subtracting it moves the parameters towards a decrease in the cost.

The algorithm repeats this update until it reaches a suitable stopping condition, such as a small change in the cost or a maximum number of iterations.

4. How Does Gradient Descent Work?

Let’s break the process into simple steps.

Step 1: Initialise the parameters

Choose initial values for the parameters. These values may be selected randomly or using a suitable initialisation method.

Step 2: Calculate the cost

Use the current parameters to calculate the model’s loss.

Step 3: Calculate the gradient

Find how the cost changes with respect to each parameter.

Step 4: Update the parameters

Move the parameters in the opposite direction of the gradient, using the learning rate.

Step 5: Repeat

Calculate the new cost and gradient, then update the parameters again.

The process continues until a stopping condition is reached.

5. A Simple Mathematical Example

Suppose we want to minimise this function:

\[
J(x)=(x-3)^2
\]

The minimum occurs at \(x=3\), where the function has a value of zero.

First, calculate the derivative:

 

\[
\frac{dJ}{dx}=2(x-3)
\]

Now, use the Gradient Descent update rule:

\[
x_{\text{new}}=x_{\text{old}}-\alpha\cdot 2(x_{\text{old}}-3)
\]

Assume:

  • Initial value: \(x=0\)
  • Learning rate: \(\alpha=0.1\)

The first update becomes:

\[
x_{\text{new}}=0-0.1[2(0-3)]
\]

\[
x_{\text{new}}=0.6
\]

The new value is closer to 3.

Repeating the same process gradually moves the value towards the minimum.

Iteration Approximate x Cost (J(x))
0 0.000 9.000
1 0.600 5.760
2 1.080 3.686
3 1.464 2.359
4 1.771 1.510
5 2.017 0.966

Notice how the cost decreases with each update. The algorithm is gradually approaching the minimum at (x=3).

6. Python Implementation

Let’s implement the same example using Python.

def cost(x):
    return (x - 3) ** 2


def gradient(x):
    return 2 * (x - 3)


x = 0
learning_rate = 0.1
iterations = 20

for i in range(iterations):
    x = x - learning_rate * gradient(x)

    print(
        f"Iteration {i + 1}: "
        f"x = {x:.4f}, cost = {cost(x):.4f}"
    )

print("Final value:", x)
print("Final cost:", cost(x))

The program begins at \(x=0\). It calculates the gradient, updates the value of x, and repeats the process 20 times.

The final value gets closer to 3, and the cost approaches zero.

This is a simple one-variable example. Real machine learning models may have thousands or millions of parameters, but the central idea remains the same.

7. Understanding the Learning Rate

The learning rate is one of the most important settings in Gradient Descent.

It determines how large each parameter update will be.

A very small learning rate

The algorithm takes tiny steps. It may reach the minimum eventually, but learning can become very slow.

A very large learning rate

The algorithm takes excessively large steps. It may jump over the minimum, oscillate, or even move further away instead of converging.

A suitable learning rate

The algorithm can make steady progress towards a minimum.

Choosing a good learning rate is important because it directly affects the speed and stability of optimisation.

8. Types of Gradient Descent

Gradient Descent has three commonly used variations. They mainly differ in how much training data is used to calculate each update.

A. Batch Gradient Descent

Batch Gradient Descent calculates the gradient using the entire training dataset before updating the parameters.

For example, if a dataset contains 10,000 training examples, the algorithm processes all 10,000 examples to calculate one update.

Advantages:

  • The gradient is calculated using the full dataset.
  • Updates are generally more stable.

Limitations:

  • Each update can be computationally expensive.
  • Large datasets require more memory and processing time.

B. Stochastic Gradient Descent (SGD)

Stochastic Gradient Descent updates the parameters using one randomly selected training example at a time.

Instead of waiting for the entire dataset, the model can update its parameters after processing a single example.

Advantages:

  • Updates can happen quickly.
  • Useful for large or continuously arriving datasets.

Limitations:

  • Updates can be noisy.
  • The cost may fluctuate instead of decreasing smoothly.

C. Mini-Batch Gradient Descent

Mini-Batch Gradient Descent uses a small group of training examples to calculate each update.

For example, instead of processing all 10,000 examples or just one, the model might use batches of 32 or 64 examples.

It combines some advantages of Batch Gradient Descent and Stochastic Gradient Descent.

Mini-batch training is widely used in modern deep learning because it works efficiently with hardware such as GPUs.

9. Problems and Limitations of Gradient Descent

Gradient Descent is powerful, but it is not without challenges.

Local Minima: In a non-convex function, the algorithm may reach a local minimum instead of the global minimum.

Saddle Points: A saddle point is a stationary point where the gradient may be zero, but the point is not a minimum or maximum. Optimisation can slow down near such regions.

Learning Rate Selection: A poor learning rate can make optimisation very slow or unstable.

Slow Convergence: Some functions have long, narrow valleys where progress towards the minimum can be slow.

Feature Scaling: When input features have very different scales, optimisation can become less efficient. Standardisation or normalisation can often help.

These challenges have motivated the development of improved optimisation methods.

10. Applications in Artificial Intelligence

Gradient Descent is widely used in machine learning because many learning tasks involve minimising a loss function.

Some important applications include:

  • Neural Networks: Adjusting weights and biases to reduce prediction errors.
  • Deep Learning: Training deep neural networks with many layers and parameters.
  • Linear Regression: Finding parameters that minimise prediction error.
  • Logistic Regression: Optimising parameters for classification tasks.
  • Computer Vision: Training models to recognise objects, faces, and images.
  • Natural Language Processing: Training language models and other systems that learn from text.

Whenever a machine learning model learns by minimising a differentiable loss function, Gradient Descent or one of its variants may be involved.

11. Gradient Descent and Hill Climbing

We have now studied two optimisation approaches: Hill Climbing and Gradient Descent.

They share an important idea: improving a solution step by step.

However, their methods are different.

Hill Climbing Gradient Descent
Examines neighbouring states Uses the gradient of a function
Moves towards a better state Moves opposite to the gradient
Can work without derivatives Requires gradient information
Often used in discrete or combinatorial search Commonly used for differentiable optimisation
Can maximise or minimise an objective Usually formulated as minimisation

Hill Climbing chooses among neighbouring solutions, while Gradient Descent uses mathematical information about the slope of a function.

Conclusion

Gradient Descent is one of the foundations of modern Machine Learning. It allows models to improve by repeatedly adjusting their parameters in the direction that reduces their loss.

From simple mathematical functions to large neural networks, the same principle is used: calculate the gradient, take a step in the opposite direction, and repeat.

However, the learning rate, shape of the cost function, and quality of the optimisation process all influence the result.

Understanding Gradient Descent gives us a clearer picture of how machines learn from data and improve their predictions.

In the next article, we will explore Genetic Algorithms, an optimisation approach inspired by natural selection and evolution.

Quick quiz

5 questions
What is the main purpose of Gradient Descent?
What does the gradient indicate?
What does the learning rate control?
Which type uses the entire dataset for each update?
Which method uses small groups of training examples?

Keep a copy

Read offline as a printout or PDF.

farhanpaal.com

Keep reading

AI · Part 35

Fuzzy Sets and Fuzzification

Understand fuzzy sets, membership functions, and fuzzification in Artificial Intelligence. Explore triangular, trapezoidal, Gaussian, and sigmoidal membership functions, with practical temperature-control examples…

8 min read

Ask Farhan

Ask anything about Farhan