← All articles
·18 min read

Gradient Descent: The Mathematics Behind How Artificial Intelligence Learns

How does an artificial intelligence model learn? Explore the mathematics of Gradient Descent, from derivatives and loss functions to optimization algorithms, convergence, and neural network training.

artificial-intelligencemachine-learninggradient-descentmathematicsoptimizationneural-networkspython

Gradient Descent: The Mathematics Behind How Artificial Intelligence Learns

Modern artificial intelligence systems rely on mathematical optimization to learn from data. Whether a model predicts housing prices, classifies images, or generates natural language, its training process generally involves adjusting internal parameters to minimize a predefined objective function.

A neural network can be represented as a parameterized function:

$$\hat{y}=f_\theta(x)$$

where $x$ is the input, $\hat{y}$ is the model prediction, and $\theta$ represents the trainable parameters, including weights and biases. Training aims to find parameters that minimize a loss function:

$$\theta^*=\arg\min_\theta L(\theta)$$

The loss function quantifies the discrepancy between predictions and expected outputs. Gradient Descent provides an iterative procedure for reducing this objective using information supplied by its derivatives.

Its fundamental principle is straightforward: determine the direction in which the objective increases most rapidly, then move in the opposite direction.


Defining the learning objective

Consider a dataset containing $N$ observations:

$$D={(x_i,y_i)}_{i=1}^{N}$$

Each observation contains an input $x_i$ and a corresponding target $y_i$. The model generates a prediction $\hat{y}i=f\theta(x_i)$.

For a regression problem, a standard loss function is the squared error:

$$\ell_i(\theta)=\frac{1}{2}(f_\theta(x_i)-y_i)^2$$

The factor $1/2$ simplifies differentiation because it cancels the factor of two produced by differentiating a square. The empirical loss over the whole dataset is:

$$L(\theta)=\frac{1}{N}\sum_{i=1}^{N}\ell_i(\theta)$$

  • Minimizing training loss does not automatically guarantee good performance on unseen observations.

  • Gradient Descent addresses the optimization problem itself; generalization depends additionally on the model architecture, regularization, and dataset quality.


Derivatives and local change

Consider the simple scalar function $L(\theta)=\theta^2$. Its derivative is:

$$\frac{dL}{d\theta}=2\theta$$

The derivative describes the local rate of change:

  • If $\theta > 0$: The derivative is positive. Increasing $\theta$ increases loss.

  • If $\theta < 0$: The derivative is negative. Increasing $\theta$ decreases loss.

  • If $\theta = 0$: The derivative is zero, reaching the global minimum.

For instance, when $\theta=4$, $L(4)=16$ and $L'(4)=8$. The positive derivative indicates that moving in the negative direction reduces the objective, provided the step is sufficiently small. The size of that step is determined by the learning rate.


The gradient in multiple dimensions

Machine learning models typically contain millions of parameters. We represent them as a vector:

$$\theta = \begin{bmatrix} \theta_1 \ \theta_2 \ \vdots \ \theta_n \end{bmatrix}, \qquad \nabla L(\theta) = \begin{bmatrix} \frac{\partial L}{\partial\theta_1} \ \frac{\partial L}{\partial\theta_2} \ \vdots \ \frac{\partial L}{\partial\theta_n} \end{bmatrix}$$

Each component measures how the objective changes when one parameter changes while the others remain fixed. The negative gradient provides the direction of steepest local decrease.

The Gradient Descent update rule is:

$$\boxed{\theta_{t+1}=\theta_t-\eta\nabla L(\theta_t)}$$

Where:

  1. $\theta_t$ represents the parameters at iteration $t$

  2. $\nabla L(\theta_t)$ is the gradient at the current state

  3. $\eta$ is the learning rate governing step size

  4. $\theta_{t+1}$ contains the newly updated parameters


Why Gradient Descent works: Taylor approximation

The update rule can be motivated using a first-order Taylor approximation:

$$L(\theta+\Delta\theta) \approx L(\theta)+\nabla L(\theta)^\top\Delta\theta$$

Choosing a parameter displacement proportional to the negative gradient $\Delta\theta=-\eta\nabla L(\theta)$ yields:

$$L(\theta-\eta\nabla L(\theta)) \approx L(\theta)-\eta\Vert{}\nabla L(\theta)\Vert{}_2^2$$

For a positive learning rate and a nonzero gradient, this predicts a guaranteed reduction in the objective.

Caution: Taylor approximation is purely local. A step size that is too large can overshoot the local region where the approximation holds, causing the objective to increase or diverge entirely.


Numerical example: Minimizing a quadratic function

Let's optimize $L(\theta)=(\theta-3)^2$ starting from $\theta_0=0$ with a learning rate of $\eta=0.1$. The derivative is $L'(\theta)=2(\theta-3)$, giving the recursive update formula $\theta_{t+1}=0.8\theta_t+0.6$.

IterationParameter ($\theta$)Loss ($L(\theta)$)
00.00009.0000
10.60005.7600
21.08003.6864
31.46402.3593
41.77121.5099
52.01700.9664

By defining the error as $e_t=\theta_t-3$, we find $e_{t+1}=(1-2\eta)e_t = 0.8 e_t$. Thus $e_t = 0.8^t e_0$, proving analytical convergence directly to $3$.


Learning rate behavior and scheduling

The learning rate dictates stability and speed. For $L(\theta)=(\theta-3)^2$, convergence requires $\vert{}1-2\eta\vert{} < 1$, which simplifies to $0 < \eta < 1$:

  • $0 < \eta < 0.5$: Smooth, monotonic convergence without changing sign

  • $\eta = 0.5$: Exact global minimum reached in a single step

  • $0.5 < \eta < 1$: Oscillates around the minimum while still converging

  • $\eta \ge 1$: Permanent oscillation or exponential divergence

To balance quick initial progress with precise convergence later, practical systems use Learning Rate Scheduling—such as Exponential Decay ($\eta_t=\eta_0\gamma^t$) or Cosine Decay schedules.


Batch, Stochastic, and Mini-Batch variants

Optimization strategies differ in how much data is evaluated per step:

Batch Gradient Descent

Computes the gradient over all $N$ examples:

$$\nabla L(\theta)=\frac{1}{N}\sum_{i=1}^{N}\nabla_\theta\ell_i(\theta)$$

Guarantees exact gradients, but becomes computationally prohibitive on massive datasets.

Stochastic Gradient Descent (SGD)

Updates parameters using a single random observation $i_t$:

$$\theta_{t+1}=\theta_t-\eta\nabla_\theta\ell_{i_t}(\theta_t)$$

Gives an unbiased estimator $\mathbb{E}[\nabla_\theta\ell_{i_t}(\theta)] = \nabla_\theta L(\theta)$ with high variance, enabling frequent updates.

Mini-Batch Gradient Descent

Calculates the gradient over a balanced subset of size $B$:

$$\nabla L_B(\theta)=\frac{1}{B}\sum_{i\in\mathcal{B}}\nabla_\theta\ell_i(\theta)$$

Combines statistical stability with GPU hardware vectorization.

MethodExamples per updatePrimary advantage
BatchEntire datasetExact empirical gradient
Stochastic (SGD)1 exampleFast updates, escapes loose local traps
Mini-BatchSubset (e.g., 32–512)Parallel GPU processing & optimal variance balance

Loss geometry and the Hessian matrix

Higher-dimensional spaces introduce unique geometric structures:

  • Local vs. Global Minima: Convex functions guarantee every local minimum is global. Non-convex deep networks feature complex landscapes with many local minima.

  • Saddle Points: Stationary points where gradients equal zero, but the surface curves upwards in some directions and downwards in others (e.g., $L(x,y)=x^2-y^2$ at the origin).

Curvature is formally evaluated using the Hessian Matrix of second-order partial derivatives:

$$H_{ij}=\frac{\partial^2L}{\partial\theta_i\partial\theta_j}$$

A positive-definite Hessian indicates a strict local minimum, negative-definite indicates a maximum, and an indefinite Hessian signals a saddle point.


Conditioning and optimization stability

For a quadratic objective $L(\theta)=\frac{1}{2}\theta^\top A\theta$, convergence is bound by the largest eigenvalue $\lambda_{\max}$ of matrix $A$:

$$0 < \eta < \frac{2}{\lambda_{\max}}$$

The ratio between the largest and smallest eigenvalues ($\lambda_{\max}/\lambda_{\min}$) is the condition number. High condition numbers cause poorly conditioned geometry, leading Gradient Descent to take inefficient zigzag trajectories across steep walls rather than moving along the floor toward the minimum.


Advanced optimizers: Momentum and Adam

To resolve poor conditioning and accelerate convergence, modern training uses enhanced updates:

Momentum

Accumulates past velocity to dampen transverse oscillations:

$$v_t = \beta v_{t-1} + \nabla L(\theta_t), \qquad \theta_{t+1} = \theta_t - \eta v_t$$

Adam (Adaptive Moment Estimation)

Tracks both smoothed first moments $m_t$ (mean) and second moments $v_t$ (uncentered variance):

$$m_t = \beta_1 m_{t-1} + (1-\beta_1)g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2$$

With bias corrections $\hat{m}_t = \frac{m_t}{1-\beta_1^t}$ and $\hat{v}_t = \frac{v_t}{1-\beta_2^t}$, the adaptive update is:

$$\theta_{t+1} = \theta_t - \eta\frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon}$$


Python implementation

Below is a complete implementation of basic Gradient Descent and single-variable optimization in Python:

import numpy as np

def loss(theta):
    return (theta - 3.0) ** 2

def gradient(theta):
    return 2.0 * (theta - 3.0)

theta = 0.0
learning_rate = 0.1
iterations = 50

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

    if step % 5 == 0:
        print(f"Step: {step:02d} | Parameter: {theta:.6f} | Loss: {loss(theta):.8f}")

print(f"\nFinal parameter: {theta:.6f}")
print(f"Final loss: {loss(theta):.8f}")

Extending to linear regression

For a linear model $\hat{y} = wx + b$ optimizing Mean Squared Error, both parameters are updated simultaneously:

$$\frac{\partial L}{\partial w} = \frac{2}{N}\sum_{i=1}^{N}(wx_i+b-y_i)x_i, \qquad \frac{\partial L}{\partial b} = \frac{2}{N}\sum_{i=1}^{N}(wx_i+b-y_i)$$

$$w_{t+1} = w_t - \eta\frac{\partial L}{\partial w}, \qquad b_{t+1} = b_t - \eta\frac{\partial L}{\partial b}$$


Practical limitations & mitigations

  • Vanishing/Exploding Gradients: Deep networks cause gradients to shrink to zero or blow up during backpropagation. Mitigation: Proper initialization (He/Xavier), Batch Normalization, and residual connections.

  • Hyperparameter Sensitivity: Bad learning rates cause immediate divergence or stagnant learning. Mitigation: Adaptive algorithms like Adam, learning rate finders, and warmup schedules.

  • Overfitting: Minimizing empirical loss on training data doesn't guarantee generalization. Mitigation: Weight decay ($L_2$ regularization), dropout, and early stopping.


Conclusion

Gradient Descent transforms learning into an iterative optimization procedure. Starting from an objective function, it computes gradients and iteratively steps in the direction of greatest decrease:

$$\boxed{\theta_{t+1}=\theta_t-\eta\nabla L(\theta_t)}$$

While mathematically simple at its core, scaling it to real-world applications requires carefully managing loss geometry, conditioning, stochastic estimation, and adaptive momentum.


References

  1. Goodfellow, I., Bengio, Y., and Courville, A. (2016). Deep Learning. MIT Press. deeplearningbook.org

  2. Ruder, S. (2016). An Overview of Gradient Descent Optimization Algorithms. arXiv:1609.04747

  3. Kingma, D. P., and Ba, J. (2015). Adam: A Method for Stochastic Optimization. arXiv:1412.6980

  4. Bottou, L., Curtis, F. E., and Nocedal, J. (2018). Optimization Methods for Large-Scale Machine Learning. SIAM Review. doi:10.1137/16M1080173

Gradient Descent Explained: Mathematics and AI | Riccardo Zorzan