Gradient Descent and Its Variants

Gradient Descent Illustration
Title: Gradient Descent Illustration
Source: AI Mind on Medium

Introduction

Optimization is the beating heart of machine learning. Training a model means minimizing a loss function, which essentially means some value that measures how wrong the model is. The most pervasive approach to this minimization is gradient descent (GD), which updates parameters by following (the negative of) the gradient. You can think of it as going in the direction opposite of the gradient, so we should expect a minus sign somewhere, right? What if we moved along with the gradient? Hint: Gradient Ascent!!

In this article you’ll learn:

  1. Intuition for gradient descent: why moving against the gradient lowers the loss
  2. Variants you’ll actually use: batch GD, stochastic GD (SGD), and mini-batch SGD
  3. Mathematical grounding with simple but revealing examples (1D quadratic, 3D valley)
  4. Practicalities: learning rate, batch size, convergence quirks
  5. Beyond vanilla GD: momentum, Nesterov, RMSProp, Adam → how and why they help

Throughout this article, we’ll point to figures (e.g., Figure 1). The accompanying notebook will generate these programmatically and dive deeper into understanding the concepts from a programming perspective.

Gradient Descent: The Big Idea

Let $f(\theta)$ be the objective (loss), with parameters $\theta \in \mathbb{R}^d $. The classic update is

$$ \theta_{t+1} = \theta_t – \eta ,\nabla_{\theta} f(\theta_t), $$

where $ \eta > 0 $ is the learning rate. The gradient $ \nabla f(\theta_t) $ points in steepest ascent; stepping in the opposite direction nudges us toward lower loss.

Physical intuition. Imagine standing on a smooth hillside (the graph of $ f $) while blindfolded. Feeling only the local slope, the fastest way down is to step downhill a small amount, then re-measure the slope and repeat.

A Gentle 1D Start: The Quadratic

Let’s use a practical example to understand the general concept. Take the canonical convex function

$$ f(\theta) = \theta^2, \qquad \nabla f(\theta) = 2\theta. $$


Starting at $ \theta_0 = 5 $ with $ \eta = 0.1 $ (the learning rate):

$$ \theta_1 = 5 – 0.1(2\cdot 5) = 4,\quad \theta_2 = 4 – 0.1(2\cdot 4) = 3.2,\ \ldots $$


The sequence shrinks toward the global minimum at $ \theta^\star=0 $.

Let’s start with a learning rate of 0.01 and see how we converge.

lr = 0.01

1D GD path graph, lr = 0.01
Title: 1D GD path, lr = 0.01
Source: AIML.com Research

You will notice that we never reached the bottom because the number of iterations were exhausted. Let’s try a larger learning rate with the same number of iterations (0.1).

lr = 0.1

1D GD path, lr = 0.1
Title: 1D GD path, lr = 0.1
Source: AIML.com Research

Much better! What happens as we increase the learning rate? When will it be too much? If you are interested in a mathematical derivation of this answer, please kindly refer to the accompanying notebook.

lr = 0.875

1D GD path graph, lr = 0.8875
Title: 1D GD path, lr = 0.875
Source: AIML.com Research

lr = 1

1D GD path graph, lr = 1
Title: 1D GD path, lr = 1
Source: AIML.com Research

lr = 0.875

1D GD path graph, lr = 0.875
Title: 1D GD path, lr = 0.875
Source: AIML.com Research

lr = 1.05

1D GD path graph, lr = 1.05
Title: 1D GD path, lr = 1.05
Source: AIML.com Research


As we increase the learning rate, we notice that we start moving back and forth, over the optimal solution until we reach it. However, too high of a learning rate and we hover between peaks (see learning rate of 1). What happens if we go higher than 1? As seen from a learning rate of 1.05, we end up diverging from the optimal solution completely. Can you guess why that is? (Hint: see notebook or plug in the equation above). In this case, the optimal learning rate we found was 0.5 as we obtained optimality with a single step, the fastest we could reach. Try plugging in 0.5 for eta above, what happens after a single iteration?

$$ \theta_1 = 5 – 0.5(2\cdot 5) = 0. $$

The Three Workhorses: Batch GD, SGD, Mini-Batch SGD

In supervised learning, the loss decomposes over data ${(x_i,y_i)}_{i=1}^N$. How much data you use per update changes speed, stability, and generalization.

Batch Gradient Descent (a.k.a. “full-batch”)

Compute the gradient on all $N$ samples each step:

$$ \theta_{t+1} = \theta_t – \eta \cdot \frac{1}{N}\sum_{i=1}^{N}\nabla_{\theta} L(x_i,y_i;\theta_t). $$


Pros: Smooth, stable updates; exact gradient of empirical risk.
Cons: Each step can be expensive for large $N$; slow “wall-clock” progress.

Stochastic Gradient Descent (SGD)

Update using one sample (or one random index $i_t$) per step:

$$ \theta_{t+1} = \theta_t – \eta \cdot \nabla_{\theta} L(x_{i_t},y_{i_t};\theta_t). $$


Pros: Very fast steps; the noise can help escape shallow traps/saddles.
Cons: Trajectory is noisy; can oscillate near minima.

Mini-Batch SGD (the industry standard)

Use a small batch of size $m$ (e.g., 32, 64, 128):

$$ \theta_{t+1} = \theta_t – \eta \cdot \frac{1}{m}\sum_{j=1}^{m}\nabla_{\theta} L(x_{i_j},y_{i_j};\theta_t). $$


Pros: Vectorized on GPUs (fast), more stable than SGD, far cheaper than full-batch.
Cons: Batch size $m$ is a hyperparameter; too small → noisy, too large → slow/memory-heavy.

Comparing the Methods Visually

We generate synthetic data from a linear model and optimize using mean squared error (MSE) as the loss (derivation shown in the notebook). From the figures, we see that SGD achieves the fastest apparent convergence when measured per-sample processed, since each update uses only one example. Mini-batch SGD (batch size = 64) provides a good compromise: it converges nearly as efficiently as SGD but with much less noise. Batch GD is smoothest per update but looks slow in terms of efficiency, since each step processes the entire dataset. Importantly, the per-update loss is noisiest with SGD, somewhat noisy with Mini-batch, and smoothest with Batch GD. For clarity, I applied exponential moving average (EMA) smoothing to better reveal the underlying trends; this does not affect the actual optimization.

Loss vs. samples processed graph with Batch GD, SGD, and mini-batch 64
Title: Loss vs. samples processed
Source: AIML.com Research

Per-update loss (noisy batches) with EMA smoothing graph, comparing Batch GD, SGD, and mini-batch 64
Title: Per-update loss (noisy batches) with EMA smoothing
Source: AIML.com Research

The GIF of parameter-space trajectories with true-loss contours shows how the three methods move through the optimization landscape. Batch GD follows a smooth, direct path toward the optimum, reflecting its use of the full gradient. Mini-batch SGD moves in the same general direction but with small oscillations, taking slightly longer to converge. SGD, by contrast, zig-zags chaotically across the contours; near the optimum it continues to hover and jitter instead of settling cleanly. This behavior highlights a key property: convergence is not just about reaching a low loss value but also about stability of the iterates. In practice, this is why stopping criteria, learning rate schedules, and advanced optimizers (e.g., Momentum, Adam) are often used to dampen noise and accelerate convergence.

Parameter-space trajectories with true-loss contours graph
Title: Parameter-space trajectories with true-loss contours
Source: AIML.com

Quick cheat sheet

AlgorithmData used per updateSpeedConvergence StabilityTypical Use
Batch GDAll samplesSlowHighSmall/medium datasets
SGD1 sampleFastLow (noisy)Huge datasets
Mini-Batch SGD32–512 samplesFastest on GPUsMedium/HighDeep learning default

Source: AIML.com Research


For an excellent classical treatment of SGD’s large-scale behavior, see Bottou [1].

From Valleys to Saddles: Geometry in 2D/3D

Up to now, we’ve only seen gradient descent on simple convex bowls where curvature is uniform. But in practice, the landscapes of neural networks are far from isotropic. They are anisotropic, meaning the curvature is very different in different directions. This mismatch is a key reason vanilla gradient descent struggles in real-world deep learning.

Consider the quadratic function:

$$f(\theta_1, \theta_2) = \theta_1^2 + 0.1 \theta_2^2.$$


Here, curvature in $\theta_1$ is ten times larger than in $\theta_2$. The result is a narrow, elongated valley. Gradient descent on such landscapes tends to zig-zag: updates overshoot in the steep direction but barely make progress in the flat direction. Learning rates that are stable for $\theta_1$ are often too small to be efficient for $\theta_2$, and vice versa.

This simple anisotropic bowl captures the challenges of optimization in high-dimensional deep networks:

  • Ill-conditioning (different scales of curvature) slows down vanilla GD
  • Momentum and NAG reduce zig-zagging by accumulating velocity
  • Adaptive methods (RMSProp, Adam) scale learning rates per parameter, accelerating progress along flat directions

The plots below illustrate these dynamics:

  • The 3D surface plot makes the anisotropic valley visible
  • The contour plot with optimizer trajectories shows how different methods behave: GD zig-zags, momentum overshoots, and Adam smoothly converges

3D path (Adam) simulation
Title: 3D path (Adam) graph
Source: AIML.com

Graph of Optimizer trajectories (contours)
Title: Optimizer trajectories (contours)
Source: AIML.com Research

Side Note: Saddles vs. Minima in High Dimensions

Classic intuition suggests the difficulty in training deep networks comes from being trapped in poor local minima. But as Dauphin et al. [2] show, this picture is misleading in high dimensions. Using arguments from statistical physics and random matrix theory, they demonstrate that saddle points, not bad local minima, dominate the error landscape.

Why? In high dimensions, the probability that all directions around a critical point curve upward (a true local minimum) is exponentially small. Instead, most critical points have a mix of positive and negative curvature (i.e. they are saddles). These saddles are often surrounded by broad, flat plateaus where gradients vanish, giving the illusion of being stuck in a local minimum while actually hovering near a saddle.

This explains two key observations:

  • he stochasticity pushes iterates off these plateaus, making escape possible
  • Second-order methods can fail: Newton’s method, which rescales steps by Hessian eigenvalues, actually makes saddles attractive since it steps the wrong way along negative curvature directions

Dauphin et al. proposed the Saddle-Free Newton method (SFN), which flips the signs of negative eigenvalues, turning saddles into repellers rather than traps. Their work shifted the narrative: the central challenge in deep learning optimization is not escaping bad minima, but navigating the ocean of saddles and flat regions.

This means that the same noise that makes SGD’s trajectory look jittery in valleys is also what helps it escape plateaus and saddles, enabling progress in landscapes where plain GD might stall.

Practicalities that Matter

  • Learning rate $\eta$
    • Too small → glacial convergence
    • Too large → divergence/oscillation
    • Start modestly, monitor loss, consider schedules (step decay, cosine, warmup)

  • Initialization
  • Batch size
    • Affects generalization and hardware efficiency
    • Mini-batches in the 32 to 512 range are common
    • Very large batches may require tuned learning-rate scaling and warmup

  • Normalization & regularization
    • Feature scaling/BatchNorm and weight decay interact with optimization
    • They can dramatically improve conditioning and stability

Beyond Vanilla GD: Momentum, Nesterov, RMSProp, Adam

Classical GD struggles in narrow valleys, plateaus, and ill-conditioned regions. Modern optimizers improve direction choice and step scaling.

Momentum (Polyak, 1964) [3]

Accumulates an exponentially weighted moving average of past gradients, effectively smoothing the direction of travel and dampening zig-zags:

$$ v_{t+1} = \mu v_t + \nabla f(\theta_t),\qquad \theta_{t+1} = \theta_t – \eta, v_{t+1}, $$

with momentum coefficient $\mu \in [0,1) $.

GD vs. Momentum on anisotrophic contours
Title: GD vs. Momentum on anisotrophic contours
Source: AIML.com

From the figure above, we see that vanilla GD does not reach optimality within the number of steps defined, whereas, Momentum does, albeit circling back to optimality. Playing around with the momentum value could yield a smoother, curving trajectory down the valley.

Nesterov Accelerated Gradient (NAG) [4]

Idea (look-ahead momentum). Instead of taking the gradient at the current iterate, NAG first looks ahead in the momentum direction and evaluates the gradient there. This anticipatory step improves responsiveness on curved/anisotropic surfaces and typically yields a small but consistent gain over classical momentum.

There are two equivalent ways you’ll see NAG written.

(a) Look-ahead (velocity) form

$$ \begin{aligned} &\text{(look ahead)} && \tilde{\theta}t = \theta_t – \mu, v_t \\ &\text{(grad at look-ahead)} && g_t = \nabla f(\tilde{\theta}t) \\ &\text{(velocity update)} && v{t+1} = \mu, v_t + g_t \\ &\text{(parameter step)} && \theta{t+1} = \theta_t – \eta, v_{t+1}, \end{aligned} $$

where $\eta>0$ is the learning rate and $\mu\in[0,1)$ is the momentum coefficient. Compare to classical momentum, which uses $g_t=\nabla f(\theta_t)$ (no look-ahead).

(b) Two-stage (“$\phi$” intermediate) form

Define the gradient step

$$ \phi_{t+1} = \theta_t – \eta, \nabla f(\theta_t), $$

then apply a momentum-like correction on the displacement:

$$ \theta_{t+1} = \phi_{t+1} + \mu,(\phi_{t+1}-\phi_t). $$

This form matches what you described (with $\phi_t$ denoting the post-GD state at step $t$).
Under a change of variables, $A$ and $B$ are equivalent views of NAG.

By probing the loss at $\theta_t-\mu v_t$, NAG “sees” upcoming curvature and partially corrects overshoot, reducing zig-zag in steep directions while maintaining longer strides along flat ones.

Practical notes

  • Typical defaults: $\mu\approx0.9$ (sometimes scheduled), $\eta$ tuned as usual
  • NAG is most beneficial in ill-conditioned valleys; gains over classical momentum are often modest but reliable

RMSProp (Tieleman & Hinton, 2012) [5]

Maintains an exponential average of squared gradients to scale each parameter’s step by its recent variability:

$$ s_{t+1}=\rho s_t + (1-\rho)g_t^2,\qquad \theta_{t+1} = \theta_t – \frac{\eta}{\sqrt{s_{t+1}}+\epsilon} g_t. $$

This helps in ill-conditioned landscapes where different coordinates need different “step sizes”.

Adam (Kingma & Ba, 2015) [6]

Combines momentum (first-moment estimate) and RMSProp-style variance adaptation (second-moment estimate), with bias correction:

\[ m_{t}=\beta_1 m_{t-1}+(1-\beta_1)g_t,\ \ v_{t}=\beta_2 v_{t-1}+(1-\beta_2)g_t^2, \] \[ \hat m_t=\frac{m_t}{1-\beta_1^t},\quad \hat v_t=\frac{v_t}{1-\beta_2^t},\quad \theta_{t+1} = \theta_t – \eta \frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}. \]

Defaults $(\beta_1=0.9,\ \beta_2=0.999)$ work strikingly well across tasks. This is the most popular at time of writing.

GD vs. Adam on anisotrophic contours graph
Title: GD vs. Adam on anisotrophic contours
Source: AIML.com Research

From the figure above, we see Adam’s adaptive steps show faster progress along flat directions and tempered steps along steep directions on an anisotropic contour plot. Adam reaches optimality faster than vanilla GD with a much more direct path.

Where Each Method Shines

  • Batch GD: establishing a foundation for understanding such algorithms, exact gradients for small datasets; baseline for convex problems
  • SGD: streaming/online settings; when you want maximum update frequency and don’t mind noise
  • Mini-Batch SGD: the default for deep learning (GPU-friendly, good balance)
  • Momentum/NAG: helps traverse ravines quickly
  • RMSProp/Adam: great when curvature varies by parameter and you want strong defaults that “just work”

Summary & Key Takeaways

  • Gradient descent is the foundational tool for optimization in ML/DL
  • Batch vs. SGD vs. Mini-Batch is mainly a trade-off among stability, speed, and compute
  • Geometry matters: anisotropy and saddles shape trajectories; visualizing them builds intuition
  • Momentum, RMSProp, and Adam solve concrete shortcomings of vanilla GD by smoothing directions and adapting step sizes
  • For most deep learning tasks today, mini-batch SGD with a modern optimizer (often Adam) is the practical default

Video Explanations:

  • This video by Visually Explained on Youtube provides a quick and strong beginner’s introduction to Gradient Descent, with diagrams and visual demonstrations. The video also dicusses flavors of Gradient Descent including vanilla, schochastic, adaptive, and more. (Runtime: 3 mins)
YouTube video
Gradient Descent in 3 minutes by Visually Explained on Youtube
  • This video by IBM Technology covers an introduction to Gradient Descent with an examples, its different types. Concepts explained by IBM Master Inventor Martin Keen. (Runtime: 7 mins)
YouTube video
Gradient Descent Explained by IBM Technology on Youtube

References

Academic Papers

  1. Bottou, L. (2010). Large-Scale Machine Learning with Stochastic Gradient Descent. COMPSTAT. https://leon.bottou.org/publications/pdf/compstat-2010.pdf
  2. Dauphin, Y. N., Pascanu, R., Gulcehre, C., Cho, K., Ganguli, S., & Bengio, Y. (2014). Identifying and attacking the saddle point problem in high-dimensional non-convex optimization. NeurIPS. https://arxiv.org/pdf/1406.2572
  3. Polyak, B. T. (1964). Some methods of speeding up the convergence of iteration methods. USSR Computational Mathematics and Mathematical Physics. https://www.sciencedirect.com/science/article/pii/0041555364901375
  4. Yurii Nesterov. A method for unconstrained convex minimization problem with the rate of convergence O(1/k2 ). In Doklady AN USSR, volume 269, pages 543–547, 1983.
  5. Tieleman, T., & Hinton, G. (2012). Lecture 6.5 — RMSProp: Divide the gradient by a running average of its recent magnitude. Coursera: Neural Networks for Machine Learning. https://www.cs.toronto.edu/~hinton/coursera/lecture6/lec6.pdf
  6. Kingma, D. P., & Ba, J. (2015). Adam: A Method for Stochastic Optimization. ICLR. https://arxiv.org/pdf/1412.6980.pdf

Tutorials & Books

  1. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. Chapter 8 (Optimization).
    Online: https://www.deeplearningbook.org/
  2. Stanford CS231n (Fei-Fei Li, Justin Johnson, Serena Yeung), Optimization notes/slides.
    Slides (2017): http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture6.pdf
  3. Andrew Ng’s Machine Learning (Coursera): optimization modules and GD demos.
    Course: https://www.coursera.org/learn/machine-learning

Blog-Style (Intuition & Figures)

  1. Ruder, S. (2016). An overview of gradient descent optimization algorithms.
    Blog: https://ruder.io/optimizing-gradient-descent/
  2. Distill.pub (2017). Visualizing Optimization Algorithms (Momentum, Nesterov, etc.).
    Interactive: https://distill.pub/2017/momentum/

Source Video

  1. Regularization and Optimization
    Stanford CS231N | Spring 2025 | Lecture 3: Regularization and Optimization
  1. What are the different types of Gradient Descent?
  2. How does gradient descent differ from coordinate descent?

Author

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute