Skip to content
E
Educatum

Adam Optimizer

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Adam (Adaptive Moment Estimation) is a first-order gradient optimization algorithm that maintains exponential moving averages of both the gradients (first moment, like Momentum) and squared gradients (second raw moment, like RMSProp). By applying bias correction to counter zero initialization in early steps, Adam adapts the effective step size per parameter, converging rapidly on noisy or sparse-gradient problems.

Study Card: Adam Optimizer

Direct Answer

Adam (Adaptive Moment Estimation) is a first-order optimization algorithm widely used to train deep neural networks. It combines Momentum (an exponential moving average of past gradients) with RMSProp (an exponential moving average of past squared gradients, refining AdaGrad’s monotonically decaying learning rate) and adds bias correction so early estimates are not biased toward zero.

At step tt with gradient gt=∇θL(θt−1)g_t = \nabla_\theta \mathcal{L}(\theta_{t-1}), Adam updates the first moment mtm_t, the second raw moment vtv_t, their bias-corrected forms m^t\hat{m}_t and v^t\hat{v}_t, and the parameters θt\theta_t:

mt=β1mt−1+(1−β1)gtvt=β2vt−1+(1−β2)gt2m^t=mt1−β1t,v^t=vt1−β2tθt=θt−1−ηv^t+ϵm^t\begin{aligned} 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}, \qquad \hat{v}_t = \frac{v_t}{1 - \beta_2^t} \\ \theta_t &= \theta_{t-1} - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t \end{aligned}

Typical defaults are η=0.001\eta = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, and ϵ=10−8\epsilon = 10^{-8} (or 10−710^{-7} in Keras). Because each parameter’s update is normalized by v^t\sqrt{\hat{v}_t}, Adam handles heterogeneous gradient scales and sparse features effectively with minimal learning-rate tuning.

Key Terms

  • Learning Rate (η\eta): A hyperparameter controlling the baseline step size during gradient updates.
  • Gradient Descent: An iterative first-order optimization method that updates parameters opposite the gradient of the loss function.
  • Momentum (First Moment mtm_t): An exponential moving average of gradients that smooths oscillations and accelerates progress along consistent directions.
  • Second Raw Moment (vtv_t): The uncentered second moment E[gt2]\mathbb{E}[g_t^2], estimated as an exponential moving average of squared gradients to scale each parameter’s step size inversely with its typical gradient magnitude.
  • Bias Correction: Rescaling mtm_t and vtv_t by (1−β1t)−1(1 - \beta_1^t)^{-1} and (1−β2t)−1(1 - \beta_2^t)^{-1} because both accumulators are initialized at 00 and would otherwise remain biased toward zero in early iterations.

Example

Imagine training a deep convolutional neural network on a multi-class dataset where some features trigger large, frequent gradients and others trigger rare, informative gradients. Using standard SGD with a single global learning rate can either cause oscillations along steep directions or crawl along flat, sparse directions.

With Adam, momentum (β1=0.9\beta_1 = 0.9) damps noisy high-frequency oscillations across mini-batches, while dividing by v^t+ϵ\sqrt{\hat{v}_t} + \epsilon normalizes step sizes per parameter: weights that consistently receive large gradients have larger v^t\hat{v}_t and get scaled down, whereas parameters updated infrequently retain smaller v^t\hat{v}_t and still make meaningful progress whenever signal arrives.

Code Implementation

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

# Load and normalize MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Define a simple neural network model
model = Sequential([
    keras.Input(shape=(28, 28)),
    Flatten(),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])

# Configure the Adam optimizer explicitly
optimizer = keras.optimizers.Adam(
    learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07
)
print("Adam parameters:", optimizer.get_config())

# Compile and train the model using Adam
model.compile(
    optimizer=optimizer,
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)
model.fit(x_train, y_train, epochs=5, batch_size=64)

# Evaluate the model
loss, accuracy = model.evaluate(x_test, y_test)
print(f"Test accuracy: {accuracy:.4f}")
  • Stochastic Gradient Descent (SGD) with Momentum: Often generalizes slightly better than Adam on vision tasks with well-tuned cosine or step decay schedules, though Adam typically converges faster with less tuning.
  • AdaGrad and RMSProp: AdaGrad accumulates the total sum of squared gradients (causing the learning rate to shrink toward zero over long training runs); RMSProp fixes this with an exponential moving average, which Adam pairs with momentum and bias correction.
  • AdamW (Decoupled Weight Decay): Classic L2 regularization interacts poorly with Adam because the penalty gradient gets scaled by 1/v^t1 / \sqrt{\hat{v}_t}; AdamW decouples weight decay directly from the adaptive gradient step and is standard for training Transformers.
  • Learning Rate Schedules: Warmup plus cosine decay is commonly paired with Adam/AdamW—warmup prevents unstable large updates when early second-moment estimates have high variance, and decay improves final convergence.
  • Hyperparameter Tuning: Tuning η\eta, β1\beta_1, β2\beta_2 (e.g., β2=0.95\beta_2 = 0.95 or 0.980.98 in LLM training), and ϵ\epsilon stabilizes optimization across architectures and batch sizes.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.