Training models requires finding parameters that minimize a cost function by updating them iteratively.
Stochastic Gradient Descent (SGD)
SGD updates parameters using the gradient calculated from a single random instance (or a mini-batch) at each step:
While computationally efficient, SGD’s updates can oscillate, slowing convergence.
Momentum and Nesterov Accelerated Gradient
Momentum accelerates SGD by adding a fraction of the previous update vector , acting like a physical ball rolling down a hill:
NAG calculates the gradient ahead of the current position () to stabilize convergence.
Adaptive Learning Rates
Adaptive algorithms adjust the learning rate per parameter based on historical gradients:
RMSProp: Decays past squared gradients to focus on recent updates.
Adam (Adaptive Moment Estimation): Tracks first (mean) and second (variance) moments of the gradients:
Bias correction is applied: and .
AdamW (Weight Decay)
AdamW improves on Adam by applying weight decay directly to the parameters rather than incorporating it into the gradient update step.
Example: Optimizing Parameters
The following example demonstrates parameter optimization using Adam in PyTorch:
Interactive Lab
import torch
# Start parameter with gradient tracking
w = torch.tensor([5.0], requires_grad=True)
# Adam optimizer with learning rate of 0.1
optimizer = torch.optim.Adam([w], lr=0.1)
# Minimize w^2 over 5 iterations
for _ in range(5):
optimizer.zero_grad() # Reset gradients
loss = w ** 2 # Compute loss
loss.backward() # Backprop
optimizer.step() # Update w
print(f"w: {w.item():.4f}")
Expected output
w: 4.9000
w: 4.8001
w: 4.7003
w: 4.6009
w: 4.5019
python
Interactive Lab
Minimize a quadratic function using the Adam optimizer in PyTorch. Observe how w converges toward zero over 5 gradient update steps.
Step 1
Inspect the idea
Step 2
Edit the program
Step 3
Run and compare
Exercise
Test your understanding of adaptive optimization updates:
Knowledge Check
Why is bias correction necessary in the Adam optimizer?
Answer: Because first and second moments are initialized to zero, biasing estimates toward zero during the initial training steps.
Since m and s are initialized to zero vectors, they are biased toward zero, especially when decay rates beta_1 and beta_2 are close to 1. The division by 1 - beta^t corrects this initialization bias.
Why is bias correction necessary in the Adam optimizer?