Adam Optimizer
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 with gradient , Adam updates the first moment , the second raw moment , their bias-corrected forms and , and the parameters :
Typical defaults are , , , and (or in Keras). Because each parameter’s update is normalized by , Adam handles heterogeneous gradient scales and sparse features effectively with minimal learning-rate tuning.
Key Terms
- Learning Rate (): 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 ): An exponential moving average of gradients that smooths oscillations and accelerates progress along consistent directions.
- Second Raw Moment (): The uncentered second moment , 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 and by and because both accumulators are initialized at 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 () damps noisy high-frequency oscillations across mini-batches, while dividing by normalizes step sizes per parameter: weights that consistently receive large gradients have larger and get scaled down, whereas parameters updated infrequently retain smaller 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}")
Related Concepts
- 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 ; 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 , , (e.g., or in LLM training), and stabilizes optimization across architectures and batch sizes.