Optional
Optimizers: noise and a finite budget
Compare batch noise and SGD, momentum and Adam training; separately compute the exact expectation of a noisy scalar recurrence.
- Version
- v2
- Minutes
- ~25
- 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.
Оптимизаторы: шум и конечный бюджет / Optimizers: noise and a finite budget
Activity version: 2. Optional desktop practice; no effect on mastery or certificates. / Необязательная практика за компьютером; не влияет на освоение и сертификаты.
Проверьте масштабирование шума батча, градиент конечными разностями и Adam; отдельно вычислите точное ожидание скалярной рекурсии. / Check batch-noise scaling, finite-difference gradients and Adam; separately compute the exact expectation of a scalar recurrence.
The sensor fixture has 240 synthetic rows and eight inputs. Seed 20261113 fixes its independent normal draws, redundant pair and irrelevant auxiliaries. It contains no patient, user, scraped or equipment observations. The other hand-sized and simulated constructions are explicitly specified in the reviewed note. / В примере 240 синтетических строк и восемь входов. Seed 20261113 фиксирует независимые нормальные величины, избыточную пару и бесполезные признаки. Наблюдений за пациентами, пользователями или оборудованием и собранных постов нет. Другие небольшие и симуляционные примеры явно заданы в проверенном конспекте.
Run cells from top to bottom in a Python environment with NumPy, SciPy and scikit-learn. The code downloads no dataset or model and makes no network requests. Tested versions: python 3.14.7, numpy 2.5.4, scipy 1.18.1, scikit-learn 1.9.1. Other numerical backends may differ in final digits. / Запускайте ячейки сверху вниз в Python с NumPy, SciPy и scikit-learn. Код не загружает данные или модели и не делает сетевых запросов. Последние цифры могут отличаться между численными backend.
Provenance / Происхождение
Prepared for the Fedor Pakhurov project with Codex assistance. The main code cell is the project's reviewed example code from the published source note, revision 67f4698fb061d93879984860f99d5181e426221b. New self-checks and bilingual framing adapt that first-party material. The complete upstream review records its scientific references and material boundaries. The note bibliography supplies primary algorithm attribution; no external dataset, model weights, source figure or third-party notebook is included. The primary references are citations, not blanket reuse permission. AI assistance does not imply guaranteed exclusive copyright. No new redistribution license is granted here.
Подготовлено для проекта Фёдора Пахурова с помощью Codex. Основная ячейка содержит проверенный код примеров проекта из опубликованного конспекта; новые самопроверки и двуязычное сопровождение адаптируют этот материал. Ссылки выше фиксируют точную ревизию, обзор происхождения и первичные источники алгоритмов. Внешних датасетов, весов моделей, чужих рисунков и ноутбуков в файле нет. Новая лицензия на распространение не устанавливается.
import numpy as np
rng = np.random.default_rng(0)
# the noise ball in one dimension: Q(w) = w^2 / 2, stochastic gradient w + noise with variance 1
for eta in (0.1, 0.01):
w = np.zeros(20_000) # 20,000 independent runs from w = 0
for k in range(int(20 / eta)):
w = w - eta * (w + rng.normal(size=w.size))
print(eta, round(w.var(), 4), round(eta / (2 - eta), 4)) # simulated and stationary variance of w
# 0.1 0.053 0.0526 | 0.01 0.005 0.005
# Original synthetic inputs; sample gradients independently with replacement.
def make_data():
# Independent dimensionless simulated inputs, with one deliberately redundant pair.
rng = np.random.default_rng(20261113)
base = rng.normal(size=(240, 8))
X = base.copy()
X[:, 1] = base[:, 0] + 0.08 * base[:, 1]
y = 20 + X @ np.array([4., 4., -3., 2., 0., 0., 0., 0.])
y += 4 * rng.normal(size=len(X))
return X, y
X, y = make_data()
X = (X - X.mean(0)) / X.std(0); y = y - y.mean(); n = len(y)
G = X * (-y)[:, None]; full_gradient = G.mean(0)
noise_rng = np.random.default_rng(20261114)
for B in (1, 8, 64):
idx = noise_rng.integers(0, n, size=(6000, B))
errors = G[idx].mean(1) - full_gradient
print(B, round(float(np.sqrt(np.mean(np.sum(errors ** 2, axis=1)))), 2),
round(float(np.sqrt(np.sum(np.var(G, axis=0)) / B)), 2))
# 1 28.99 28.47 | 8 10.05 10.07 | 64 3.54 3.56
# a quadratic with eigenvalues 0.045 and 4.5 (kappa = 100): steps to shrink the excess loss 1000-fold
mu, L = 0.045, 4.5
c, s = np.cos(np.pi / 6), np.sin(np.pi / 6); R = np.array([[c, -s], [s, c]])
H1 = np.diag([L, mu]); H2 = R @ H1 @ R.T # the same bowl, axis-aligned and rotated by 30 degrees
def steps(H, w0, method, eta, beta=0.0, K=2000):
w, v, m, s2 = w0.copy(), np.zeros(2), np.zeros(2), np.zeros(2)
q0 = w0 @ H @ w0
for k in range(1, K + 1):
g = H @ w
if method == 'gd': w = w - eta * g
if method == 'momentum': v = beta * v + g; w = w - eta * v
if method == 'nesterov':
g = H @ (w - eta * beta * v); v = beta * v + g; w = w - eta * v
if method == 'adam':
m = 0.9 * m + 0.1 * g; s2 = 0.999 * s2 + 0.001 * g * g
w = w - eta * (m / (1 - 0.9 ** k)) / (np.sqrt(s2 / (1 - 0.999 ** k)) + 1e-8)
if w @ H @ w < 1e-3 * q0: return k
w0 = np.array([-2.4, 1.6])
rk = np.sqrt(L / mu)
print(round((L - mu) / (L + mu), 3), round((rk - 1) / (rk + 1), 3),
steps(H1, w0, 'gd', 2 / (L + mu)), steps(H1, w0, 'momentum', 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2, ((rk - 1) / (rk + 1)) ** 2),
steps(H1, w0, 'nesterov', 1 / L, (rk - 1) / (rk + 1)))
# 0.98 0.818 173 39 17: asymptotic per-step factors of GD and momentum; steps of GD, optimal heavy ball, Nesterov
w, v, norms = w0.copy(), np.zeros(2), []
for _ in range(10):
v = ((rk - 1) / (rk + 1)) ** 2 * v + H1 @ w; w = w - 4 / (np.sqrt(L) + np.sqrt(mu)) ** 2 * v; norms.append(np.linalg.norm(w))
print(round(float(np.linalg.norm(w0)), 2), round(float(max(norms)), 2), int(np.argmax(norms)) + 1)
# 2.88 8.98 4: the optimal heavy ball first moves away, error norm 2.88 -> 8.98 after 4 steps
for name, H, start in (('aligned', H1, w0), ('rotated', H2, R @ w0)):
print(name, steps(H, start, 'gd', 2 / (L + mu)), steps(H, start, 'momentum', 0.05, 0.9), steps(H, start, 'adam', 0.2))
# aligned 173 48 13 | rotated 173 48 171
# Neglect epsilon for this demonstration: the first corrected step is eta * sign(g).
g1 = np.array([100.0, 0.01])
m1, v1 = 0.1 * g1, 0.001 * g1 ** 2
print((m1 / 0.1) / np.sqrt(v1 / 0.001), (m1 / np.sqrt(v1)).round(2)) # [1. 1.] [3.16 3.16]
# Independent numerical gradient and first-step checks.
loss = lambda w: np.mean((X @ w - y) ** 2) / 2
probe = np.linspace(-0.4, 0.7, X.shape[1]); h = 1e-5
finite = np.array([(loss(probe + h * e) - loss(probe - h * e)) / (2*h) for e in np.eye(len(probe))])
analytic = X.T @ (X @ probe - y) / n
assert np.max(abs(finite - analytic)) < 1e-7
first_gradient = np.array([100., 0.01])
first_m = 0.1 * first_gradient; first_v = 0.001 * first_gradient ** 2
assert np.allclose((first_m / 0.1) / (np.sqrt(first_v / 0.001) + 1e-8), first_gradient / (abs(first_gradient) + 1e-8))
def train(X, y, method, eta, cut=False):
# A shared NumPy permutation for every optimizer makes the finite comparison explicit.
out = []
optimum = np.linalg.lstsq(X, y, rcond=None)[0]
minimum = np.mean((X @ optimum - y) ** 2) / 2
for seed in range(5):
rng = np.random.default_rng(400 + seed)
w = np.zeros(X.shape[1]); velocity = w.copy(); m = w.copy(); v = w.copy()
step = 0
for epoch in range(40):
rate = eta / 10 if cut and epoch >= 20 else eta
indices = rng.permutation(len(y))
for start in range(0, len(y), 24):
idx = indices[start:start + 24]
g = X[idx].T @ (X[idx] @ w - y[idx]) / len(idx)
step += 1
if method == "sgd":
w -= rate * g
elif method == "momentum":
velocity = 0.9 * velocity + g
w -= rate * velocity
elif method == "adam":
m = 0.9 * m + 0.1 * g
v = 0.999 * v + 0.001 * g * g
w -= rate * (m / (1 - 0.9 ** step)) / (np.sqrt(v / (1 - 0.999 ** step)) + 1e-8)
else:
raise ValueError(method)
out.append(float(np.mean((X @ w - y) ** 2) / 2 - minimum))
return {"mean": float(np.mean(out)), "seed_results": out}
w_hat = np.linalg.lstsq(X, y, rcond=None)[0]
print(round(loss(w_hat), 3), round(float(np.linalg.cond(X.T @ X)), 1)) # 8.456 568.9
for method, rate in [('sgd', 0.03), ('sgd', 0.15), ('momentum', 0.015), ('adam', 0.003), ('adam', 0.1)]:
print(method, rate, round(train(X, y, method, rate)['mean'], 3), round(train(X, y, method, rate, True)['mean'], 3))
# sgd 0.03 0.035 0.035 | sgd 0.15 0.116 0.029 | momentum 0.015 0.054 0.030
# adam 0.003 21.155 28.620 | adam 0.1 0.045 0.036
Self-check / Самопроверка
The next cell verifies the lesson-specific claims. / Следующая ячейка проверяет утверждения урока.
# Exact expectation propagation, adapted from the reviewed first-party FP figure.
# This is not a Monte Carlo simulation of sample paths.
def expected_scalar_loss(step):
mean, variance = 2.0, 0.0
for k in range(240):
eta = step(k)
mean = (1 - eta) * mean
variance = (1 - eta)**2 * variance + eta**2
return (mean**2 + variance) / 2
expected = [expected_scalar_loss(lambda k: 0.12),
expected_scalar_loss(lambda k: 0.025),
expected_scalar_loss(lambda k: 0.12 / (1 + k / 30))]
assert np.allclose(expected, [0.031914893617, 0.006339630370, 0.003904405475], atol=1e-12)
print("Exact expected loss after 240 steps:", [round(x, 12) for x in expected])
print("Self-checks passed; expected loss is not a monotonicity guarantee for each path")
Try a change / Измените условие
Сначала предскажите, как изменится RMSE при удвоении батча, затем пересчитайте. Для сравнения оптимизаторов меняйте один параметр и сохраняйте общие перестановки. Не называйте обучающую потерю тестовым качеством. / Predict the RMSE change when batch size doubles, then recompute it. In optimizer comparisons change one parameter while preserving shared permutations. Do not call training loss test performance.