ML Optimizers: Momentum, RMSProp, and Adam Guide

Standard Stochastic Gradient Descent (SGD) applies a fixed learning rate across every parameter. In practice, real-world loss landscapes are rarely neat, symmetric bowls. Instead, they often contain ravines—regions where the loss changes steeply in one direction but gradually in another—and broad, relatively flat regions containing saddle points.

In these situations, vanilla SGD can oscillate across steep directions while making slow progress along flatter directions toward a minimum.

To address these challenges, modern deep learning uses advanced optimization algorithms that improve how model parameters are updated. Three important optimizers are Momentum, RMSProp, and Adam.

These optimizers introduce two major ideas:

  • Momentum: Uses information from previous gradients to build a more consistent update direction.
  • Adaptive Learning Rates: Adjusts the effective step size for individual parameters based on historical gradient information.

The most widely recognized optimizer combining both ideas is Adam (Adaptive Moment Estimation).

Let's understand how these optimizers work, their mathematical foundations, differences, advantages, limitations, and practical Python implementations.


1. Understanding Why Vanilla SGD Is Not Always Enough

Before exploring advanced optimizers, let's understand the limitations of standard Stochastic Gradient Descent.

The basic SGD update rule is:

\[ \theta_{t+1}=\theta_t-\eta g_t \]

Where:

  • \(\theta_t\): Model parameters at the current step.
  • \(\eta\): Learning rate.
  • \(g_t\): Gradient of the loss function.
  • \(\theta_{t+1}\): Updated model parameters.

SGD calculates the current gradient and moves the parameters in the opposite direction to reduce the loss.

However, this approach can encounter several difficulties.

1.1 Oscillations in Steep Directions

Imagine a narrow valley where the loss changes dramatically from left to right but only slightly along the valley.

SGD may repeatedly move from one steep wall to the other instead of progressing efficiently toward the minimum.

1.2 Slow Progress in Flat Regions

When gradients are very small, parameter updates also become small.

Consequently, the model may take many iterations to make meaningful progress.

1.3 Sensitivity to Learning Rate

The learning rate determines the size of each parameter update.

  • Too small: Training becomes unnecessarily slow.
  • Too large: The optimizer may overshoot the minimum or diverge.
  • Appropriate: Training generally makes stable progress.

Advanced optimizers attempt to improve these behaviors by using information from previous gradients.

2. Momentum: Accelerating Down Ravines

Momentum improves SGD by incorporating information from previous gradients.

It borrows intuition from Newtonian physics: imagine a heavy ball rolling down a hillside. As it rolls, it builds up velocity in a consistent downhill direction and resists sudden changes in direction.

Instead of relying entirely on the current gradient, Momentum maintains a running estimate of the update direction.

2.1 Mathematical Formulation

A commonly used Momentum formulation is:

\[ v_t=\beta v_{t-1}+g_t \]

\[ \theta_{t+1}=\theta_t-\eta v_t \]

Where:

  • \(v_t\): Momentum or velocity vector.
  • \(v_{t-1}\): Previous velocity.
  • \(g_t\): Current gradient.
  • \(\beta\): Momentum coefficient, commonly around 0.9.
  • \(\eta\): Learning rate.

The parameter \(\beta\) controls how much previous gradient information influences the current update.

A larger momentum coefficient gives more influence to previous updates.

Another equivalent convention uses an exponentially weighted average:

\[ v_t=\beta v_{t-1}+(1-\beta)g_t \]

\[ \theta_{t+1}=\theta_t-\eta v_t \]

This second version normalizes the running average. The two conventions have different update scales, so the learning rate must be interpreted accordingly.

2.2 How Momentum Works

Suppose the gradients consistently point in approximately the same direction.

Momentum accumulates their influence, increasing the effective movement in that direction.

When gradients alternate directions, their contributions can partially cancel, reducing unnecessary oscillations.

Without Momentum vs. With Momentum

Without Momentum (SGD)          With Momentum

      \      /                       \
       \    /                         \
        \  /                           \
         \/                             \========>
         /\                              \
        /  \                              \
   Oscillating path                 Smoother progress

2.3 Advantages of Momentum

  • Accelerates convergence when gradients consistently point in a similar direction.
  • Reduces oscillations in steep directions.
  • Can help the optimizer move through small flat regions.
  • Often improves training efficiency compared with vanilla SGD.

2.4 Limitations of Momentum

  • Requires selecting a suitable momentum coefficient.
  • Does not independently adapt the learning rate for each parameter.
  • Excessive momentum can cause overshooting.
  • Still requires careful learning-rate selection.

2.5 When Should You Use Momentum?

Momentum is particularly useful when training deep neural networks with SGD, especially when the loss landscape contains narrow valleys or noisy gradients.

It is commonly used in image classification and computer vision models.

3. RMSProp: Adaptive Learning Rates for Every Parameter

Momentum improves the direction of parameter updates, but it does not independently adjust learning rates for different parameters.

Consider a model where one parameter receives consistently large gradients while another receives much smaller gradients.

Using the same learning rate for both parameters may result in inefficient updates.

RMSProp (Root Mean Square Propagation) addresses this issue by adapting the effective learning rate for each parameter.

It maintains an exponentially weighted average of squared gradients.

3.1 Mathematical Formulation

First, calculate the moving average of squared gradients:

\[ s_t=\beta s_{t-1}+(1-\beta)g_t^2 \]

Then update the model parameters:

\[ \theta_{t+1}= \theta_t-\frac{\eta}{\sqrt{s_t}+\epsilon}g_t \]

Where:

  • \(s_t\): Moving average of squared gradients.
  • \(\beta\): Decay coefficient, often around 0.9.
  • \(g_t\): Current gradient.
  • \(\eta\): Learning rate.
  • \(\epsilon\): Small constant used for numerical stability.

The squared gradient is calculated element-wise for each parameter.

3.2 How RMSProp Works

RMSProp changes the effective learning rate according to the historical magnitude of gradients.

  • Parameters with consistently large gradients receive smaller effective updates.
  • Parameters with smaller gradients can receive relatively larger effective updates.

This helps balance learning across parameters with different gradient scales.

For example:

Parameter A: Large historical gradients
Effective learning rate: Smaller

Parameter B: Small historical gradients
Effective learning rate: Relatively larger

The optimizer uses the following effective step-size relationship:

\[ \eta_{\text{effective}}= \frac{\eta}{\sqrt{s_t}+\epsilon} \]

This is why RMSProp is called an adaptive learning-rate optimizer.

3.3 Advantages of RMSProp

  • Automatically adapts learning rates for individual parameters.
  • Helps handle gradients with different magnitudes.
  • Can work well in non-stationary optimization problems.
  • Often performs well in recurrent neural network training.
  • Reduces the impact of consistently large gradients.

3.4 Limitations of RMSProp

  • Requires tuning the learning rate and decay coefficient.
  • Does not guarantee convergence to a global minimum.
  • Its adaptive updates can sometimes make optimization difficult to interpret.
  • Performance depends on the dataset, architecture, and hyperparameters.

3.5 When Should You Use RMSProp?

RMSProp is useful when gradients vary significantly in magnitude across parameters.

It has historically been popular for:

  • Recurrent Neural Networks (RNNs).
  • Sequence modeling.
  • Non-stationary learning problems.
  • Deep learning models with unstable gradient scales.

4. Adam: Adaptive Moment Estimation

Adam (Adaptive Moment Estimation) combines the key ideas of Momentum and RMSProp.

It tracks two moving averages:

  1. First moment: The moving average of gradients.
  2. Second moment: The moving average of squared gradients.

The first moment helps determine the direction of updates, while the second moment adjusts their effective scale.

Adam also uses bias correction to compensate for the initialization of these moving averages at zero.

4.1 Mathematical Formulation

Adam maintains two estimates.

Step 1: Calculate the first moment

\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t \]

This is the exponentially weighted average of gradients.

Step 2: Calculate the second moment

\[ v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2 \]

This is the exponentially weighted average of squared gradients.

Step 3: Apply bias correction

Because both moving averages begin at zero, they can initially underestimate their true values.

Adam corrects this bias using:

\[ \hat{m}_t=\frac{m_t}{1-\beta_1^t} \]

\[ \hat{v}_t=\frac{v_t}{1-\beta_2^t} \]

Step 4: Update the parameters

\[ \theta_{t+1}= \theta_t- \frac{\eta}{\sqrt{\hat{v}_t}+\epsilon} \hat{m}_t \]

Where:

  • \(m_t\): First-moment estimate.
  • \(v_t\): Second-moment estimate.
  • \(\hat{m}_t\): Bias-corrected first moment.
  • \(\hat{v}_t\): Bias-corrected second moment.
  • \(\beta_1\): First-moment decay coefficient.
  • \(\beta_2\): Second-moment decay coefficient.
  • \(\epsilon\): Numerical stability constant.
  • \(\eta\): Learning rate.

4.2 Common Adam Hyperparameters

Typical default values are:

HyperparameterCommon DefaultPurpose
Learning rate0.001Controls update size
\(\beta_1\)0.9Controls first-moment decay
\(\beta_2\)0.999Controls second-moment decay
\(\epsilon\)\(10^{-8}\)Numerical stability

These are common starting values, not universal optimal settings.

4.3 How Adam Works

Imagine training a neural network with millions of parameters.

Some parameters may receive large gradients, while others receive small or inconsistent gradients.

Adam handles this by combining:

  • Momentum-like behavior to maintain a smoother update direction.
  • RMSProp-like behavior to adjust the update magnitude for each parameter.
  • Bias correction to improve the early estimates.

As a result, Adam often provides effective optimization with relatively little initial hyperparameter tuning.

4.4 Advantages of Adam

  • Combines momentum and adaptive learning rates.
  • Often converges quickly during early training.
  • Handles noisy and sparse gradients effectively in many settings.
  • Requires relatively little initial tuning.
  • Works well across many neural network architectures.

4.5 Limitations of Adam

  • Requires additional memory to store moment estimates.
  • Does not guarantee better generalization than SGD with Momentum.
  • Can sometimes converge to solutions that generalize less effectively than carefully tuned SGD.
  • Still requires learning-rate tuning and validation.
  • Adaptive updates do not eliminate the need for proper data preprocessing or model design.

4.6 When Should You Use Adam?

Adam is a strong starting choice for many deep learning projects, including:

  • Image classification.
  • Natural Language Processing (NLP).
  • Transformer models.
  • Deep neural networks.
  • Recommendation systems.
  • Generative AI applications.

However, the best optimizer should always be selected through experimentation and validation.

5. Adam vs. AdamW: Understanding Weight Decay

A related optimizer worth understanding is AdamW.

AdamW modifies how weight decay is applied during optimization.

In standard Adam implementations, L2 regularization added to the loss can interact with the adaptive gradient scaling.

AdamW uses decoupled weight decay, applying the weight decay separately from the adaptive gradient update.

A simplified AdamW update is:

\[ \theta_{t+1} = \theta_t - \eta \frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon} - \eta\lambda\theta_t \]

Where:

  • \(\lambda\): Weight decay coefficient.
  • Other terms follow the Adam update rule.

Why does AdamW matter?

It provides more direct control over weight decay and is widely used when training modern neural networks, including transformer-based architectures.

AdamW is not simply Adam with an arbitrary L2 penalty added to the loss; its decoupled weight decay is the important distinction.

6. Comparison: SGD, Momentum, RMSProp, Adam, and AdamW

Let's compare the major optimization algorithms.

FeatureSGDMomentumRMSPropAdamAdamW
Uses current gradientYesYesYesYesYes
Uses gradient historyNoYesYesYesYes
Momentum behaviorNoYesNo by defaultYesYes
Adaptive learning ratesNoNoYesYesYes
Bias correctionNoNoUsually noYesYes
Decoupled weight decayNoNoNoNoYes
Memory requirementLowLowModerateHigherHigher

Which Optimizer Should You Choose?

  • SGD: Useful when simplicity and low memory usage are priorities.
  • SGD with Momentum: Useful when smoother updates and potentially strong generalization are desired.
  • RMSProp: Useful for problems where adaptive scaling of gradients is beneficial.
  • Adam: A practical starting point for many deep learning tasks.
  • AdamW: A strong option when using adaptive optimization with decoupled weight decay.

No optimizer is universally best. The right choice depends on the model, dataset, training setup, and evaluation objective.

7. Practical Python Implementation

Let's see how these optimizers are used in a real machine-learning workflow.

We'll use TensorFlow/Keras to demonstrate the optimizers.

7.1 Installing Required Libraries

pip install tensorflow numpy

7.2 Importing Libraries

import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import (
    SGD,
    RMSprop,
    Adam,
    AdamW
)

7.3 Creating a Sample Neural Network

model = Sequential([
    Dense(64, activation='relu', input_shape=(20,)),
    Dense(32, activation='relu'),
    Dense(1, activation='sigmoid')
])

This simple neural network contains:

  • An input layer accepting 20 features.
  • Two hidden layers.
  • An output layer for binary classification.

7.4 Using SGD with Momentum

optimizer = SGD(
    learning_rate=0.01,
    momentum=0.9
)

model.compile(
    optimizer=optimizer,
    loss='binary_crossentropy',
    metrics=['accuracy']
)

Here, the momentum coefficient is set to 0.9.

7.5 Using RMSProp

optimizer = RMSprop(
    learning_rate=0.001,
    rho=0.9
)

model.compile(
    optimizer=optimizer,
    loss='binary_crossentropy',
    metrics=['accuracy']
)

RMSProp uses rho to control the decay of the moving average of squared gradients.

7.6 Using Adam

optimizer = Adam(
    learning_rate=0.001,
    beta_1=0.9,
    beta_2=0.999
)

model.compile(
    optimizer=optimizer,
    loss='binary_crossentropy',
    metrics=['accuracy']
)

Adam combines first- and second-moment estimates to adapt parameter updates.

7.7 Using AdamW

optimizer = AdamW(
    learning_rate=0.001,
    weight_decay=0.0001
)

model.compile(
    optimizer=optimizer,
    loss='binary_crossentropy',
    metrics=['accuracy']
)

AdamW applies decoupled weight decay during optimization.

Note: These are separate optimizer configurations. In an actual experiment, create or reset the model for each optimizer so that every comparison begins from equivalent initial weights. Use the same data splits and comparable training conditions.

8. Learning Rate: The Most Important Hyperparameter

Even advanced optimizers depend heavily on the learning rate.

The learning rate determines how large a step the optimizer takes while updating model parameters.

Consider the following situations:

Learning rate too small

  • Training progresses slowly.
  • More iterations may be required.
  • The model may appear to stop improving within the available training budget.

Learning rate too large

  • The optimizer may overshoot useful regions.
  • Loss may oscillate.
  • Training may become unstable or diverge.

Appropriate learning rate

  • Loss generally decreases in a stable manner.
  • Training makes useful progress.
  • The model can approach a good solution within a reasonable number of iterations.

A useful practice is to experiment with learning rates on a logarithmic scale, such as:

\[ 0.1,\quad 0.01,\quad 0.001,\quad 0.0001 \]

These are example values, not recommendations for every architecture.

9. Learning Rate Scheduling

Instead of keeping the learning rate constant throughout training, many deep learning workflows gradually change it.

This technique is called Learning Rate Scheduling.

Common scheduling strategies include:

9.1 Step Decay

The learning rate decreases after a specified number of epochs.

For example:

Initial learning rate: 0.01
After 10 epochs:       0.001
After 20 epochs:       0.0001

9.2 Exponential Decay

The learning rate decreases exponentially over time.

\[ \eta_t=\eta_0e^{-kt} \]

Where:

  • \(\eta_0\): Initial learning rate.
  • \(k\): Decay coefficient.
  • \(t\): Training step or epoch, depending on implementation.

9.3 Cosine Annealing

The learning rate gradually follows a cosine-shaped curve.

\[ \eta_t= \eta_{\min} + \frac{1}{2}(\eta_{\max}-\eta_{\min}) \left(1+\cos\left(\frac{\pi t}{T}\right)\right) \]

Where:

  • \(\eta_{\max}\): Maximum learning rate.
  • \(\eta_{\min}\): Minimum learning rate.
  • \(T\): Total scheduled training duration.
  • \(t\): Current step within the schedule.

9.4 Reduce on Plateau

The learning rate decreases when the monitored validation metric stops improving for a specified number of epochs.

This is useful when training progress does not follow a predictable schedule.

9.5 Learning Rate Warmup

During warmup, the learning rate gradually increases from a small value to its target value.

Warmup is frequently used when training large neural networks and transformer models.

10. Common Optimization Problems and Their Solutions

Even advanced optimizers can encounter training difficulties.

ProblemPossible CausePotential Solution
Loss does not decreaseLearning rate too small or incorrect gradientsCheck implementation and tune learning rate
Loss becomes unstableLearning rate too highReduce learning rate
Training is slowPoor optimization settingsTry Momentum or an adaptive optimizer
Exploding gradientsVery large gradient valuesGradient clipping or architecture changes
OverfittingModel memorizes training dataRegularization, dropout, or early stopping
Validation performance is poorGeneralization problemImprove data quality and model selection
Training gets stuckFlat or difficult loss regionsExperiment with optimizer and learning-rate schedule

10.1 Gradient Clipping

Gradient clipping limits the magnitude of gradients before the optimizer updates parameters.

For example, global-norm clipping scales gradients when their combined norm exceeds a specified threshold.

It is commonly used to reduce the risk of exploding gradients, particularly in recurrent networks.

10.2 Early Stopping

Early stopping monitors validation performance and stops training when improvement stalls.

It helps prevent unnecessary training and can reduce overfitting.

10.3 Feature Scaling

For many models, scaling input features can improve optimization behavior.

Standardization is commonly expressed as:

\[ z=\frac{x-\mu}{\sigma} \]

Where:

  • \(x\): Original feature value.
  • \(\mu\): Feature mean.
  • \(\sigma\): Feature standard deviation.
  • \(z\): Standardized value.

Fit scaling parameters on the training data only, then apply the same transformation to validation and test data.

11. Real-World Applications of Modern Optimizers

Modern optimization algorithms are essential across machine learning and deep learning.

ApplicationCommon OptimizersPurpose
Image ClassificationSGD with Momentum, AdamTrain CNNs and vision models
Natural Language ProcessingAdam, AdamWTrain language and transformer models
Generative AIAdam, AdamWOptimize generative neural networks
Time-Series ForecastingAdam, RMSPropTrain sequence models
Recommendation SystemsAdam, SGDOptimize large prediction models
Computer VisionSGD with Momentum, AdamWTrain deep visual recognition models

These are common choices rather than strict rules. Optimizer selection should be based on validation results and the requirements of the training task.

12. Best Practices for Choosing an Optimizer

When training a machine-learning or deep-learning model, follow these practical guidelines:

  1. Start with a reasonable baseline: Try Adam for many neural network tasks or SGD with Momentum when it is appropriate for your architecture.
  2. Tune the learning rate: Test several values rather than assuming the default is optimal.
  3. Monitor training and validation loss: A decreasing training loss does not necessarily mean better generalization.
  4. Use learning-rate schedules: Consider warmup, cosine decay, or reduce-on-plateau when appropriate.
  5. Apply gradient clipping when necessary: Particularly useful for models vulnerable to exploding gradients.
  6. Use weight decay carefully: Consider AdamW for adaptive optimization with decoupled weight decay.
  7. Keep experiments comparable: Use consistent data splits, preprocessing, and evaluation metrics.
  8. Avoid relying only on training speed: The final validation or test performance matters more than how quickly training loss decreases.
  9. Reproducibility matters: Record optimizer settings, random seeds, and training configurations.

Conclusion

Optimization algorithms play a fundamental role in training machine-learning and deep-learning models.

Vanilla SGD provides a simple foundation, but its fixed learning rate and reliance on current gradients can make optimization difficult in complex loss landscapes.

Momentum improves update direction by incorporating historical gradients. RMSProp adapts learning rates using the moving average of squared gradients. Adam combines both approaches through first- and second-moment estimates with bias correction.

AdamW extends Adam by introducing decoupled weight decay, making it another important optimizer in modern deep learning.

Understanding these algorithms helps developers and machine-learning engineers select suitable optimization strategies, improve training stability, and build more effective models.

The key takeaway: An advanced optimizer does not automatically produce the best model. Good results depend on choosing an appropriate optimizer, tuning its hyperparameters, preparing data correctly, and evaluating performance carefully.


Further Learning

To build a stronger understanding of machine-learning optimization, explore these related topics:

  • Gradient Descent, SGD, Mini-Batches & Learning Rates
  • Backpropagation in Neural Networks
  • Neural Networks: Architecture, Activation Functions & Training
  • Vanishing and Exploding Gradients
  • Weight Initialization: Xavier and He Initialization
  • Learning Rate Scheduling and Warmup
  • Batch Normalization and Layer Normalization