
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:
- Intuition for gradient descent: why moving against the gradient lowers the loss
- Variants you’ll actually use: batch GD, stochastic GD (SGD), and mini-batch SGD
- Mathematical grounding with simple but revealing examples (1D quadratic, 3D valley)
- Practicalities: learning rate, batch size, convergence quirks
- 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
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
Starting at $ \theta_0 = 5 $ with $ \eta = 0.1 $ (the learning rate):
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

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

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

Source: AIML.com Research
lr = 1

Source: AIML.com Research
lr = 0.875

Source: AIML.com Research
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?
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:
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:
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):
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.

Source: AIML.com Research

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.

Source: AIML.com
Quick cheat sheet
| Algorithm | Data used per update | Speed | Convergence Stability | Typical Use |
| Batch GD | All samples | Slow | High | Small/medium datasets |
| SGD | 1 sample | Fast | Low (noisy) | Huge datasets |
| Mini-Batch SGD | 32–512 samples | Fastest on GPUs | Medium/High | Deep 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:
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

Source: AIML.com

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
- Good initial scales matter (e.g., He or Xavier initialization) to avoid vanishing/exploding gradients
- Good initial scales matter (e.g., He or Xavier initialization) to avoid vanishing/exploding gradients
- 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:
with momentum coefficient $\mu \in [0,1) $.

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
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
then apply a momentum-like correction on the displacement:
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:
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:
Defaults $(\beta_1=0.9,\ \beta_2=0.999)$ work strikingly well across tasks. This is the most popular at time of writing.

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)
- 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)
References
Academic Papers
- Bottou, L. (2010). Large-Scale Machine Learning with Stochastic Gradient Descent. COMPSTAT. https://leon.bottou.org/publications/pdf/compstat-2010.pdf
- 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
- 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
- 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.
- 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
- Kingma, D. P., & Ba, J. (2015). Adam: A Method for Stochastic Optimization. ICLR. https://arxiv.org/pdf/1412.6980.pdf
Tutorials & Books
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press. Chapter 8 (Optimization).
Online: https://www.deeplearningbook.org/ - Stanford CS231n (Fei-Fei Li, Justin Johnson, Serena Yeung), Optimization notes/slides.
Slides (2017): http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture6.pdf - Andrew Ng’s Machine Learning (Coursera): optimization modules and GD demos.
Course: https://www.coursera.org/learn/machine-learning
Blog-Style (Intuition & Figures)
- Ruder, S. (2016). An overview of gradient descent optimization algorithms.
Blog: https://ruder.io/optimizing-gradient-descent/ - Distill.pub (2017). Visualizing Optimization Algorithms (Momentum, Nesterov, etc.).
Interactive: https://distill.pub/2017/momentum/
Source Video
- Regularization and Optimization
Stanford CS231N | Spring 2025 | Lecture 3: Regularization and Optimization

