Skip to content
BIASED
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 .ipynb

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 · Данные: L(w)=12(w12+104w22)L(w)=\tfrac12(w_1^2 + 10^4 w_2^2).

Узкое направление ограничивает шаг SGD (η≲2⋅10−4\eta\lesssim 2\cdot10^{-4}), поэтому w1w_1 почти не двигается; Adam масштабирует координаты отдельно.

Ожидаемые числа (w0=(1,1)w_0=(1,1), 500 шагов)
Optimizer final LL Tolerance
SGD η=10−4\eta=10^{-4} ≥0.4\ge 0.4
Adam η=0.05\eta=0.05 <10−3< 10^{-3}
Самопроверка в ноутбуке

Не влияет на сертификат.

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