Monday , November 30 2026
Gradient descent variants, momentum, RMSProp and Adam implemented and compared in NumPy, with learning-rate tips for deep learning.

Optimization Techniques in ML: Gradient Descent, Momentum and Adam

Updated: 29 November 2026Level: IntermediateReading time: about 10 minutesNumPy · tested

Training a model means finding weights that minimise a loss function. Optimizers are the algorithms that do this. Gradient descent is the basis; momentum, RMSProp and Adam are improvements used in almost every deep-learning project.

What You Will Learn

  • Batch, stochastic and mini-batch gradient descent
  • Momentum
  • RMSProp and Adam
  • Compare optimizers on the same problem in NumPy
  • Learning-rate schedules and practical tips

Prerequisites

Calculus for ML.

The Test Problem

We minimise f(w) = (w₁ − 3)² + 10(w₂ + 1)², a “stretched bowl” whose minimum is at (3, −1). It is steep in one direction and flat in the other – exactly the shape that makes plain gradient descent slow.

Example
import numpy as np

def grad(w): return np.array([2 * (w[0] - 3), 20 * (w[1] + 1)])
def loss(w): return (w[0] - 3) ** 2 + 10 * (w[1] + 1) ** 2

def run(update, steps=30):
    w, s = np.array([0.0, 0.0]), {}
    for t in range(1, steps + 1):
        w = update(w, grad(w), s, t)
    return loss(w)

def gd(w, g, s, t, lr=0.04):
    return w - lr * g

def momentum(w, g, s, t, lr=0.04, beta=0.8):
    s["v"] = beta * s.get("v", 0) + g          # running direction
    return w - lr * s["v"]

def adam(w, g, s, t, lr=0.3, b1=0.9, b2=0.999, eps=1e-8):
    s["m"] = b1 * s.get("m", 0) + (1 - b1) * g          # average gradient
    s["v"] = b2 * s.get("v", 0) + (1 - b2) * g * g      # average squared gradient
    m_hat, v_hat = s["m"] / (1 - b1 ** t), s["v"] / (1 - b2 ** t)
    return w - lr * m_hat / (np.sqrt(v_hat) + eps)

for name, f in [("Gradient descent", gd), ("Momentum", momentum), ("Adam", adam)]:
    print(f"{name:17s} loss after 30 steps = {run(f):.5f}")
Output
Gradient descent  loss after 30 steps = 0.06047
Momentum          loss after 30 steps = 0.00102
Adam              loss after 30 steps = 0.21468

Explanation: Momentum builds up speed in the consistent direction and gets ~60× closer than plain gradient descent in 30 steps. Adam scales each parameter’s step by its own gradient history, so it is robust to badly scaled problems and needs little tuning – but on this tiny, smooth problem it is not the fastest. There is no single best optimizer; Adam is the popular default because it works well across many deep networks with little tuning.

Variants of Gradient Descent

Variant Data per update Trade-off
Batch GD All rows Smooth but slow and memory-heavy
Stochastic GD (SGD) 1 row Fast, noisy; noise can escape poor minima
Mini-batch GD 32–512 rows The standard choice; uses GPUs efficiently

Common Optimizers

Optimizer Idea Keras
SGD Step = −lr × gradient SGD(learning_rate=0.01)
SGD + momentum Add a fraction of the previous step SGD(momentum=0.9)
RMSProp Divide by a running average of squared gradients RMSprop()
Adam Momentum + RMSProp with bias correction Adam(learning_rate=1e-3)
AdamW Adam with correct weight decay; standard for transformers AdamW()

Practical Tips

  • Start with Adam (lr = 1e-3) for neural networks; SGD + momentum often generalises well for CNNs when tuned.
  • Use a learning-rate schedule: warm-up, step decay or cosine decay.
  • If the loss explodes or becomes NaN, lower the learning rate.
  • Scale your input features – every optimizer works better.

Series

Maths & Statistics series: Introduction to Statistics · Descriptive Statistics · Probability · Bayes’ Theorem · Distributions · Inferential Statistics · Hypothesis Testing · P-Values · Correlation & Covariance · Linear Algebra · Eigenvalues · Calculus · Optimization · Interview Questions

Interview Questions

Q: Why does momentum help?
It accumulates past gradients, speeding up in consistent directions and damping oscillation.

Q: What does Adam adapt?
The step size per parameter, using running averages of the gradient and squared gradient.

Q: Batch vs mini-batch gradient descent?
Batch uses all data per update; mini-batch uses small subsets – faster and suited to GPUs.

Practice Exercises

  1. Change the learning rate of gradient descent to 0.09 and 0.11 – what happens?
  2. Implement RMSProp in the same framework and compare.

Summary

Optimizers minimise the loss. Gradient descent is the base; momentum accelerates it, and adaptive methods like RMSProp and Adam scale steps per parameter. Choose and tune by experiment.

Next: ANN – Plan of Attack · Statistics Interview Questions

About Machine Learning

Check Also

LSTM and GRU Explained (NumPy LSTM Cell + Keras Example)

LSTM and GRU explained: vanishing gradients, cell state and gates, an LSTM step in NumPy, GRU comparison, parameter counts and a Keras sentiment model.