Gradient Descent: How Machines Learn by Minimizing Errors

Quick summary
  • Training adjusts model parameters to minimize a loss that measures prediction error.
  • The gradient gives a direction of steepest increase, and gradient descent steps in the opposite direction.
  • Mini-batches, backpropagation, and optimizers make gradient-based learning practical for neural networks.
Ask AI to explain

Get a plain-language summary and explore the key ideas.

From mathematical gradients to stochastic optimization and neural network training.

Imagine trying to find the lowest point in a valley while standing somewhere on a mountain. You cannot see the entire landscape, and you have no map showing where the bottom is. All you can do is observe the slope beneath your feet and decide which direction to take next.

This is a useful way to think about how machine learning models learn.

A model does not initially know the parameters needed to make accurate predictions. It starts with initial values, evaluates how well it performs, and gradually adjusts those values to reduce its errors.

One of the fundamental algorithms behind this process is gradient descent.

The idea is simple, but understanding it connects several concepts: loss functions, derivatives, gradients, learning rates, and optimization strategies. Let’s build that understanding step by step.

1. Understanding the problem: what are we trying to minimize?

Before discussing gradient descent, we need to understand what a machine learning model is trying to achieve.

Consider a model that predicts house prices. It receives information such as property size, location, and number of bedrooms, then produces an estimated price. Its predictions will not necessarily match the actual prices.

Suppose the model predicts $400,000 for a property that is actually worth $500,000. The prediction has an error of $100,000. How can the model improve?

We need a mathematical way to measure how far its predictions are from the expected results. This is the role of a loss function.

A loss function quantifies the error produced by a model. During training, our objective is to find parameter values that minimize this function. For example:

Plain text
L(x) = (x - 3)^2

Our objective is to find the value of x that produces the smallest possible loss. In this example, the answer is 3, where the loss reaches zero.

Real machine learning models are considerably more complex, often involving thousands or millions of parameters. The underlying objective remains the same: minimize a mathematical function that represents prediction error.

2. The gradient: understanding the direction of change

Now that we understand what we want to minimize, we need a way to determine how a function behaves around a particular point. This is where the mathematical concept of a gradient becomes important.

In calculus, the derivative measures how a function changes as its input changes. For a function with multiple variables, the gradient generalizes this idea into a vector containing the partial derivatives with respect to each variable.

Consider:

Plain text
f(x) = (x - 3)^2

Its derivative is:

Plain text
f′(x) = 2(x - 3)

This derivative tells us the slope of the function at any given point.

  • If the derivative is negative, the function decreases locally as x increases.
  • If the derivative is positive, the function increases locally as x increases.
  • If the derivative is zero, the point is stationary. It could be a minimum, a maximum, or a saddle point.

For a differentiable function, its gradient points in the direction of steepest local increase under the usual Euclidean measure of distance.

This distinction matters: the gradient itself does not optimize anything. It provides information about how the function changes. An optimization algorithm can use that information to decide how to adjust its parameters.

3. Gradient descent: moving toward a minimum

If the gradient indicates the direction of steepest increase, moving in the opposite direction leads toward a region where the function decreases. This is the central idea behind gradient descent.

Gradient descent is an iterative optimization algorithm. It uses gradient information to update model parameters and reduce a loss function. Its general update rule is:

Plain text
θ_(t+1) = θ_t - α ∇L(θ_t)

where:

  • θ_t represents the current model parameters.
  • α is the learning rate.
  • ∇L(θ_t) is the gradient of the loss function.
  • θ_(t+1) represents the updated parameters.

The negative sign is important. It means we move in the direction opposite to the gradient.

Return to our example:

Plain text
L(x) = (x - 3)^2,    L′(x) = 2(x - 3)

Suppose we start with x = 0 and choose a learning rate of 0.1. Our first update is:

Plain text
x_new = 0 - 0.1 × 2(0 - 3) = 0.6

The parameter moves from 0 to 0.6. Repeating the same operation gives:

IterationParameterLoss
00.00009.0000
10.60005.7600
21.08003.6864
31.46402.3593
41.77121.5099
52.01690.9664

The parameter approaches 3 while the loss decreases. The algorithm does not need to know the answer beforehand. It uses local gradient information to determine its next adjustment.

On the loss curve, each update moves the parameter from x₀ to x₁, then to x₂, bringing it closer to the minimum at x = 3. Each step follows the negative gradient.

4. Learning rate: how large should each step be?

One of the most important hyperparameters in gradient descent is the learning rate. It determines how much the parameters change during each optimization step.

Imagine descending a mountain again. Taking extremely small steps might eventually get you to the bottom, but the process could take a long time. Taking excessively large steps could cause you to repeatedly overshoot the valley.

The same principle applies to optimization. A learning rate that is too small can make convergence unnecessarily slow. A learning rate that is too large can cause oscillations, overshooting, or even divergence.

An appropriate learning rate allows the algorithm to make meaningful progress while keeping optimization stable. There is no universally optimal value. Its effectiveness depends on the loss landscape, parameter scales, model architecture, and optimization method. This is why learning-rate selection and scheduling are important topics in modern deep learning.

5. From one parameter to millions of parameters

So far, we have used a simple function with one variable. Real machine learning models usually contain many parameters.

Consider a linear regression model:

Plain text
ŷ = w_1 x_1 + w_2 x_2 + b

The model has three parameters:

  • w_1: the weight associated with the first feature.
  • w_2: the weight associated with the second feature.
  • b: the bias or intercept.

Instead of calculating a single derivative, we calculate a gradient vector:

Plain text
∇L = [∂L/∂w_1, ∂L/∂w_2, ∂L/∂b]ᵀ

Each component describes how the loss changes with respect to one parameter. The algorithm updates all parameters using the same principle:

Plain text
θ_new = θ_current - α ∇L(θ)

This extends gradient descent from simple functions to models with many dimensions.

6. Batch gradient descent vs. stochastic gradient descent

Optimization strategies differ in how much training data they use to calculate a gradient before updating the parameters.

Batch gradient descent

Batch gradient descent calculates the gradient using the entire training dataset before performing an update. For a dataset with 100,000 records, the algorithm processes all 100,000, calculates the average loss and its gradient, then updates the parameters.

This generally produces more stable gradient estimates, but each update can be computationally expensive.

Stochastic gradient descent (SGD)

Stochastic gradient descent calculates the gradient using one training example per update. With the same dataset, the algorithm can update the model after processing each individual example.

Its update rule can be written as:

Plain text
θ_(t+1) = θ_t - α ∇L_i(θ_t)

Here, L_i is the loss for one training example. Each update costs less to calculate, but the gradient estimates are noisier. The optimization path can fluctuate instead of following a smooth route. That noise can sometimes help an optimizer move away from certain saddle regions, but it does not guarantee a global minimum.

Mini-batch gradient descent

Between these approaches is a widely used alternative: mini-batch gradient descent. It uses a small batch of examples for each update rather than the entire dataset or a single example.

For example:

  • Dataset size: 100,000 examples.
  • Batch size: 100 examples.
  • Updates per epoch: 1,000.

The algorithm processes 100 examples, calculates their average loss and gradient, updates the parameters, and continues with the next batch.

Optimization strategyExamples per updateUpdates per epoch
Batch gradient descent100,0001
Stochastic gradient descent1100,000
Mini-batch gradient descent1001,000

Mini-batches balance computational efficiency, gradient stability, and hardware utilization. They are especially useful in deep learning, where GPUs can process multiple examples in parallel.

7. Backpropagation: how neural networks calculate gradients

We understand how gradients update model parameters, but how does a neural network calculate those gradients when it contains millions of parameters and multiple layers? This is where backpropagation comes in.

A neural network performs a forward pass first. Input data travels through its layers and activation functions until the model generates a prediction. A loss function then compares that prediction with the expected output.

Backpropagation calculates how the loss changes with respect to the network’s parameters. It applies the chain rule of calculus to propagate gradient information backward through the computational graph. Once the gradients are calculated, an optimizer uses them to update the parameters.

The process is:

  1. Forward propagation: Generate predictions from input data.
  2. Loss calculation: Measure the difference between predictions and expected outputs.
  3. Backpropagation: Calculate gradients for the network parameters.
  4. Optimization: Update parameters using an optimization algorithm.

These steps repeat throughout training. Their responsibilities are different:

  • The loss function measures prediction error.
  • Backpropagation calculates gradients.
  • Gradient descent and other optimizers use those gradients to update parameters.

Backpropagation is not an optimization algorithm. It is a mechanism for efficiently calculating derivatives.

8. Beyond basic gradient descent: modern optimizers

Gradient descent provides a foundation for many optimization algorithms, but it is not the only strategy available. Modern deep learning commonly uses more sophisticated optimizers.

  • Stochastic gradient descent (SGD): Uses stochastic or mini-batch gradient estimates to update parameters.
  • Momentum: Incorporates information from previous gradients to smooth updates and accelerate movement in consistent directions.
  • RMSProp: Adjusts effective learning rates using moving averages of squared gradients.
  • Adam (Adaptive Moment Estimation): Combines momentum-like behavior with adaptive estimates based on the first and second moments of gradients.

Adam is popular because it often optimizes effectively with relatively little initial hyperparameter tuning. No optimizer is universally superior. Performance depends on the model, dataset, objective, and training configuration.

9. A practical implementation in Python

The concepts become clearer when implemented directly. Here is a simple gradient descent algorithm without a machine learning framework:

Python
def loss(x):
    return (x - 3) ** 2


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


learning_rate = 0.1
iterations = 20

x = 0.0

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

    print(
        f"Step: {step + 1}, "
        f"x: {x:.4f}, "
        f"loss: {loss(x):.6f}"
    )

print(f"Final parameter: {x}")

This implementation shows the fundamental optimization loop:

  1. Calculate the gradient.
  2. Update the parameter.
  3. Repeat.

Frameworks such as PyTorch, TensorFlow, and JAX provide automatic differentiation, which handles much of the derivative calculation. A typical PyTorch training loop looks like this:

Python
for batch in dataloader:
    optimizer.zero_grad()

    predictions = model(batch["input"])
    loss = criterion(predictions, batch["target"])

    loss.backward()
    optimizer.step()

Although the implementation is more abstract, the underlying concepts remain the same. The model generates predictions, calculates its loss, computes gradients through backpropagation, and updates its parameters through an optimizer.

10. Final thoughts: optimization is the foundation of learning

Understanding gradient descent means understanding one of the fundamental mechanisms that make machine learning possible.

A model does not simply memorize the correct answer to every input. During training, it adjusts its parameters based on information about how its predictions differ from expected outcomes. The gradient describes how the loss changes. Gradient descent uses that information to move parameters toward lower-loss regions.

Stochastic and mini-batch variations change how gradient estimates are calculated, making optimization practical for large datasets. Backpropagation enables neural networks to calculate gradients efficiently, while optimizers such as Adam add strategies to improve parameter updates.

Together, these concepts form a foundation for understanding how modern neural networks are trained. Machine learning optimization is an iterative process: measure the error, calculate how the parameters influence it, adjust them, and repeat.

Learning is not a single operation. It is the result of continuously improving through optimization.

Further reading