Back to topic
Optional
Adam vs SGD on a quadratic valley
Convergence comparison on L=½(w₁²+100 w₂²). Self-check in the notebook.
- Version
- v1
- Minutes
- ~15
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
DL · Adam vs SGD на овраге / Adam vs SGD on a valley
Activity version: 1 · Seed: n/a · Данные: .
Узкое направление ограничивает шаг SGD (), поэтому почти не двигается; Adam масштабирует координаты отдельно.
Ожидаемые числа (, 500 шагов)
| Optimizer | final | Tolerance |
|---|---|---|
| SGD | ||
| Adam |
Самопроверка в ноутбуке
Не влияет на сертификат.
import numpy as np
def loss(w):
return 0.5 * (w[0] ** 2 + 1e4 * w[1] ** 2)
def grad(w):
return np.array([w[0], 1e4 * w[1]])
def run_sgd(steps=500, lr=1e-4, w0=(1.0, 1.0)):
w = np.array(w0, dtype=float)
for _ in range(steps):
w = w - lr * grad(w)
return w, loss(w)
def run_adam(steps=500, lr=0.05, w0=(1.0, 1.0), beta1=0.9, beta2=0.999, eps=1e-8):
w = np.array(w0, dtype=float)
m = np.zeros_like(w)
v = np.zeros_like(w)
for t in range(1, steps + 1):
g = grad(w)
m = beta1 * m + (1 - beta1) * g
v = beta2 * v + (1 - beta2) * (g * g)
mhat = m / (1 - beta1 ** t)
vhat = v / (1 - beta2 ** t)
w = w - lr * mhat / (np.sqrt(vhat) + eps)
return w, loss(w)
w_s, L_s = run_sgd()
w_a, L_a = run_adam()
print("SGD", w_s, L_s)
print("Adam", w_a, L_a)
assert L_s >= 0.4
assert L_a < 1e-3
print("OK: Adam vs SGD")
Самопроверка в ноутбуке
- SGD loss ≥ 0.4
- Adam loss < 1e-3