Comparison of SGD vs Momentum vs Adam optimizers
Comparison of SGD vs Momentum vs Adam optimizers
Run the three optimizers on the same "narrow valley" loss function and visualize the convergence path and speed differences.
After learning this case study, you will understand: the mathematical principles and intuitive effects of SGD oscillation, Momentum smoothing by inertia, and Adam's adaptive step size adjustment—the three strategies.
Real-life introduction
**Downhill curve—three strategies
SGD strategy: only looks at the ground beneath its feet, moving in the steepest direction each time. It bounces back and forth when encountering a narrow ditch.
Momentum Strategy: Like a snowball rolling—remember the previous direction of speed, inertia allows it to roll over small bumps.
Adam Strategy: Not only inertia, but also adjusting step size based on the condition of each section of the road—small steps on steep parts, large strides on flat parts.
Intuitive Understanding
SGD
theta -= lr * g
Pure gradient direction, no historical information, oscillates in steep directions
Momentum
v = beta*v + (1-beta)*g
theta -= lr * v
Accumulate historical gradients, inertia suppresses oscillations
Adam
m = beta1*m + (1-beta1)*g
v = beta2*v + (1-beta2)*g^2
theta -= lr * m_hat/(sqrt(v_hat)+eps)
Momentum + adaptive learning rate, independently adjusts step size for each parameter
Test function: (f(x, y) = 0.5x^2 + 5y^2) — a narrow valley with a gentle slope in the x direction and a steep slope in the y direction.
Python Hands-on Practice
Example
import
numpy
as
np
def
f
(
pos
)
:
x
,
y
=
pos
return
0.5
- x**
2
5
- y**
2
def
grad
(
pos
)
:
x
,
y
=
pos
return
np.
array
(
[
x
,
10
- y
]
)
def
sgd
(
start
,
lr
=
0.1
,
steps
=
60
)
:
pos
=
np.
array
(
start
,
dtype
=
float
)
history
=
[
pos.
copy
(
)
]
for
_
in
range
(
steps
)
:
pos
=
pos - lr * grad
(
pos
)
history.
append
(
pos.
copy
(
)
)
return
np.
array
(
history
)
def
momentum
(
start
,
lr
=
0.1
,
beta
=
0.9
,
steps
=
60
)
:
pos
=
np.
array
(
start
,
dtype
=
float
)
v
=
np.
zeros_like
(
pos
)
history
=
[
pos.
copy
(
)
]
for
_
in
range
(
steps
)
:
g
=
grad
(
pos
)
v
=
beta * v +
(
1
- beta
)
- g
pos
=
pos - lr * v
history.
append
(
pos.
copy
(
)
)
return
np.
array
(
history
)
def
adam
(
start
,
lr
=
0.3
,
beta1
=
0.9
,
beta2
=
0.999
,
eps
=
1e-8
,
steps
=
60
)
:
pos
=
np.
array
(
start
,
dtype
=
float
)
m
=
np.
zeros_like
(
pos
)
v
=
np.
zeros_like
(
pos
)
history
=
[
pos.
copy
(
)
]
for
t
in
range
(
1
,
steps +
1
)
:
g
=
grad
(
pos
)
m
=
beta1 * m +
(
1
- beta1
)
- g
v
=
beta2 * v +
(
1
- beta2
)
(
g **
2
)
m_hat
=
m /
(
1
- beta1 ** t
)
v_hat
=
v /
(
1
- beta2 ** t
)
pos
=
pos - lr * m_hat /
(
np.
sqrt
(
v_hat
)
- eps
)
history.
append
(
pos.
copy
(
)
)
return
np.
array
(
history
)
start
=
[
4.0
,
4.0
]
results
=
{
"SGD"
: sgd
(
start
,
lr
=
0.1
)
,
"Momentum"
: momentum
(
start
,
lr
=
0.1
)
,
"Adam"
: adam
(
start
,
lr
=
0.3
)
,
}
(
"RUNOOB Three Optimizers Comparison (Starting Point [4,4]):\n"
)
for
name
,
hist
in
results.
items
(
)
:
dists
=
np.
linalg
.
norm
(
hist
,
axis
=
1
)
mask
=
dists
<
0.05
conv
=
(np.
argmax
(
mask
)
if
mask.
any
(
)
else
"Not converged"
)
n_osc
=
np.
sum
(
np.
diff
(
np.
sign
(
hist
[
:
,
1
]
)
)
!=
0
)
(
f
" {name:10s}: {str(conv):>6s} convergence steps, y oscillated {n_osc} times, loss={f(hist[-1]):.6f}"
)
Original prompt (Chinese, left untranslated)
RUNOOB 三种优化器对比 (起点 [4,4]):
SGD : 未收敛 步收敛, y震荡36次, 损失=0.000035
Momentum : 21 步收敛, y震荡6次, 损失=0.000000
Adam : 16 步收敛, y震荡0次, 损失=0.000000
Application scenarios in AI
| Scenario | Recommended optimizer | Reason |
|---|---|---|
| Most tasks | Adam/AdamW | Adaptive, fast convergence, few hyperparameters to tune |
| Transformer training | AdamW | Used by both GPT/BERT |
| Requires extreme precision | SGD+Momentum | Generalization ability is sometimes better |