Stochastic gradient descent
From the exact gradient to SGD, momentum, Nesterov, RMSProp and Adam: why each step exists, with animations and exercises.
Learning goals: explain why a stochastic gradient is used and what its noise costs; state the step-size conditions; explain momentum, Nesterov, RMSProp and Adam; implement them and compare them with Keras.
Part 1 · Why a stochastic gradient?
Why not simply compute the exact gradient?
Training a model means minimizing an average over the $N$ examples of a data set:
\[ J(\theta)=\frac1N\sum_{i=1}^{N}\ell_i(\theta),\qquad \nabla J(\theta)=\frac1N\sum_{i=1}^{N}\nabla\ell_i(\theta). \]Gradient descent $\theta\leftarrow\theta-\alpha\nabla J(\theta)$ needs all the $N$ gradients for a single step. For $N=10^4$ this is cheap; for $N=10^7$ images (or $10^{12}$ tokens) one exact step costs a full pass over the data, and a model needs thousands of steps. Three observations explain why we do not do that.
- Data are redundant. If you duplicate every example, the exact gradient does not change but costs twice as much. A small random subset already points in nearly the same direction as the full set.
- An early step does not need to be precise. Far from the minimum, any direction that decreases the loss is good: an accurate direction brings little more than a rough one, but costs $N$ times more.
- A sample is an unbiased estimate. If $i$ is drawn uniformly, then $\mathbb E[\nabla\ell_i(\theta)]=\nabla J(\theta)$. The estimate has noise, but no systematic error (Part 3).
The idea of the stochastic gradient: replace $\nabla J$ by the gradient on a random mini-batch of $b$ examples, and update after each batch. For the price of one exact step, we make $N/b$ updates.
What the noise costs, and what it brings
The price of a mini-batch gradient is its variance: $\sigma^2/b$ if one example has variance $\sigma^2$. Averaging $b$ examples divides the variance by $b$ but multiplies the cost by $b$, so the standard deviation of the noise decreases only like $1/\sqrt b$: going from $b=1$ to $b=100$ divides it by 10 and costs 100 times more. Most of the benefit comes from the first examples. This is why mini-batches of 32 to 512 are the usual compromise on a GPU.
The noise also has a benefit: it helps to leave saddle points and sharp narrow minima, and it makes the training time almost independent of $N$. Its drawback is that, with a constant step, the iterate never settles: it fluctuates around the minimizer (Part 2). That is why the step must decrease, or why we add the tools of Parts 5 and 6.
Exercise 1.1 · the noise of a mini-batch
- The data set has $N=10{,}000$ points. At $\theta=0$, compute the exact gradient and, for $b\in\{1,4,16,64,256\}$, 3,000 mini-batch gradients.
- Check that their mean is close to the exact gradient (no bias), and compute their total variance.
- Check that the variance times $b$ is almost constant, and plot the variance against $b$ in log–log scale.
theta0 = np.array([0.0, 0.0])g_full = ... # TO DO: the exact gradient: all the 10,000 examplessizes = [1, 4, 16, 64, 256]variances = []for b in sizes: G = ... # TO DO: 3,000 mini-batch gradients of size b bias = ... # TO DO: distance between their average and the exact gradient variances.append(float(np.sum(G.var(axis=0)))) # total variance of the estimate print(f"b = {b:4d}: |mean - exact| = {bias:.4f}, variance = {variances[-1]:.4f}, b * variance = {b * variances[-1]:.3f}")plt.loglog(sizes, variances, "o-", label="measured variance")plt.loglog(sizes, variances[0] / np.array(sizes), "--", label="variance of b = 1, divided by b")plt.xlabel("mini-batch size b"); plt.ylabel("variance of the gradient estimate"); plt.legend(); plt.show()

Show the correction
theta0 = np.array([0.0, 0.0])g_full = batch_gradient(theta0, np.arange(N)) # the exact gradient: all the 10,000 examplessizes = [1, 4, 16, 64, 256]variances = []for b in sizes: G = np.array([batch_gradient(theta0, rng.integers(0, N, b)) for _ in range(3000)]) # 3,000 mini-batch gradients of size b bias = np.linalg.norm(G.mean(axis=0) - g_full) # distance between their average and the exact gradient variances.append(float(np.sum(G.var(axis=0)))) # total variance of the estimate print(f"b = {b:4d}: |mean - exact| = {bias:.4f}, variance = {variances[-1]:.4f}, b * variance = {b * variances[-1]:.3f}")plt.loglog(sizes, variances, "o-", label="measured variance")plt.loglog(sizes, variances[0] / np.array(sizes), "--", label="variance of b = 1, divided by b")plt.xlabel("mini-batch size b"); plt.ylabel("variance of the gradient estimate"); plt.legend(); plt.show()
The distance between the mean of the estimates and the exact gradient is small for every $b$ (at most 0.11, and it shrinks as $b$ grows: it is only the error of the mean over 3,000 samples). The variance goes from 30.5 for $b=1$ to 0.124 for $b=256$; the product $b\times$variance stays between 30.5 and 33.1, as the theory predicts.
Exercise 1.2 · same budget, more updates
- Implement full-batch gradient descent (one update per epoch) and mini-batch SGD with $b=32$ (shuffle once per epoch, $N/b$ updates per epoch).
- Run both for 10 epochs and print $J-J(\theta^*)$ after 1, 3 and 10 epochs.
- Plot $J-J^*$ against the epoch in log scale and explain the difference.
def run_gd(alpha, n_epochs): theta, losses = np.zeros(2), [loss(np.zeros(2))] for _ in range(n_epochs): theta = ... # TO DO: one update per epoch, using all the examples losses.append(loss(theta)) return np.array(losses)def run_minibatch_sgd(alpha, n_epochs, b, seed=1): r = np.random.default_rng(seed) theta, losses = np.zeros(2), [loss(np.zeros(2))] for _ in range(n_epochs): order = ... # TO DO: shuffle the examples once per epoch for k in range(N // b): theta = ... # TO DO: N/b updates per epoch, each one on b examples losses.append(loss(theta)) return np.array(losses)epochs = 10gd = run_gd(0.1, epochs)sgd = run_minibatch_sgd(0.05, epochs, b=32)print(f"updates made in {epochs} epochs: GD {epochs}, mini-batch SGD {epochs * (N // 32)}")print("loss J - J(theta*) after 1, 3 and 10 epochs:")print(" GD :", gd[[1, 3, 10]] - loss(theta_star))print(" SGD :", sgd[[1, 3, 10]] - loss(theta_star))plt.semilogy(gd - loss(theta_star) + 1e-12, "o-", label="GD, step 0.1"); plt.semilogy(sgd - loss(theta_star) + 1e-12, "s-", label="mini-batch SGD, b = 32, step 0.05")plt.xlabel("epoch (one pass over the 10,000 examples)"); plt.ylabel("J - J*"); plt.legend(); plt.show()

Show the correction
def run_gd(alpha, n_epochs): theta, losses = np.zeros(2), [loss(np.zeros(2))] for _ in range(n_epochs): theta = theta - alpha * batch_gradient(theta, np.arange(N)) # one update per epoch, using all the examples losses.append(loss(theta)) return np.array(losses)def run_minibatch_sgd(alpha, n_epochs, b, seed=1): r = np.random.default_rng(seed) theta, losses = np.zeros(2), [loss(np.zeros(2))] for _ in range(n_epochs): order = r.permutation(N) # shuffle the examples once per epoch for k in range(N // b): theta = theta - alpha * batch_gradient(theta, order[k * b:(k + 1) * b]) # N/b updates per epoch, each one on b examples losses.append(loss(theta)) return np.array(losses)epochs = 10gd = run_gd(0.1, epochs)sgd = run_minibatch_sgd(0.05, epochs, b=32)print(f"updates made in {epochs} epochs: GD {epochs}, mini-batch SGD {epochs * (N // 32)}")print("loss J - J(theta*) after 1, 3 and 10 epochs:")print(" GD :", gd[[1, 3, 10]] - loss(theta_star))print(" SGD :", sgd[[1, 3, 10]] - loss(theta_star))plt.semilogy(gd - loss(theta_star) + 1e-12, "o-", label="GD, step 0.1"); plt.semilogy(sgd - loss(theta_star) + 1e-12, "s-", label="mini-batch SGD, b = 32, step 0.05")plt.xlabel("epoch (one pass over the 10,000 examples)"); plt.ylabel("J - J*"); plt.legend(); plt.show()
After one epoch the gap is $5.2$ for GD against $0.0005$ for SGD: SGD has made 312 updates, GD only one. After 10 epochs GD has made 10 updates and is still at $0.78$; SGD has made 3,120 and sits at $0.0023$. SGD does not go lower than that because of its noise: it is limited by the size of the step. This is the interest of the method on large data sets.
Part 2 · Example: full gradient or stochastic gradient?
Both methods start from the same point and spend the same number of gradients $\nabla\ell_i$. The blue path is GD, the red path is SGD, the star is $\theta^*$. Change the step sizes and the mini-batch size, and click in the data plot to add a point. The notation is defined in the frame below.
Interactive demonstration: JavaScript required.
The least-squares problem and its two gradients
We fit the model $f_\theta(x)=\theta_0+\theta_1x$ to $N$ examples $(x_i,y_i)$. With residuals $r_i=\theta_0+\theta_1x_i-y_i$, the loss is
\[J(\theta)=\frac1N\sum_{i=1}^N\ell_i(\theta),\qquad \ell_i(\theta)=\tfrac12 r_i^2,\qquad \nabla\ell_i(\theta)=r_i\begin{pmatrix}1\\x_i\end{pmatrix}.\]With $X$ the $N\times2$ matrix of rows $(1,x_i)$, $J(\theta)=\frac1{2N}\|X\theta-y\|^2$ is a convex quadratic with Hessian $\frac1NX^TX$; its minimizer solves the normal equations $X^TX\,\theta^*=X^Ty$.
- Full-batch gradient descent (GD): $\theta_{k+1}=\theta_k-\alpha\,\nabla J(\theta_k)$, which uses all $N$ examples at every step.
- Stochastic gradient descent (SGD): draw $i_k$ at random (or a mini-batch $B_k$) and set $\theta_{k+1}=\theta_k-\alpha_k\,\nabla\ell_{i_k}(\theta_k)$. For the cost of one GD step, SGD takes $N$ small steps.
The exercises of Parts 1 to 3 use the same problem in Python: $y=2+3x+\text{noise}$ on $N=10{,}000$ points, whose exact minimizer is $\theta^*\approx(2.003,\,2.986)$.
Part 3 · Why does SGD converge?
The stochastic gradient is unbiased
If the index $i$ is drawn uniformly in $\{1,\dots,N\}$, then for every $\theta$, $\mathbb E_i\big[\nabla\ell_i(\theta)\big]=\nabla J(\theta)$. For a mini-batch of size $b$ drawn uniformly, the same holds and the variance of the estimate is divided by about $b$.
Proof
By definition of the expectation, $\mathbb E_i[\nabla\ell_i(\theta)]=\sum_{i=1}^N\frac1N\nabla\ell_i(\theta)=\nabla\Big(\frac1N\sum_{i=1}^N\ell_i\Big)(\theta)=\nabla J(\theta)$. For a batch $B$ of $b$ indices drawn independently, the average of $b$ unbiased and independent estimates is unbiased, and its variance is $\sigma^2/b$ where $\sigma^2$ is the variance of a single one. $\square$
Robbins–Monro conditions
Write $\nabla\ell_{i_k}(\theta_k)=\nabla J(\theta_k)+\xi_k$ with a noise $\xi_k$ of zero mean. With a constant step the noise does not vanish: the iterate keeps fluctuating around $\theta^*$ at a distance of the order of $\sqrt\alpha$. To converge, the steps must satisfy the Robbins–Monro conditions:
\[\sum_k\alpha_k=\infty\quad(\text{we can reach any distance}),\qquad \sum_k\alpha_k^2<\infty\quad(\text{the noise is averaged out}).\]For example $\alpha_k=\alpha_0/(1+k/\tau)$. In practice, a constant step during a long time followed by a reduction (a schedule) is often used.
Exercise 3.1 · constant step against decreasing step
- Implement SGD with one example per step and a step size given by a function
schedule(k). - Compare a constant step $0.05$ with $\alpha_k=0.05/(1+k/500)$ over 20,000 steps, and print the distance to $\theta^*$ (averaged over the last 100 steps) at 100, 1,000, 5,000 and 20,000 steps.
- Plot the two distances in log–log scale (with a moving average) and explain the plateau.
def sgd_distance(schedule, n_steps=20000, seed=3): r = np.random.default_rng(seed) theta, dist = np.zeros(2), [] for k in range(n_steps): i = r.integers(0, N, 1) theta = ... # TO DO: one example per step, with the step size given by the schedule dist.append(np.linalg.norm(theta - theta_star)) return np.array(dist)constant = lambda k: 0.05 # a constant step sizedecreasing = ... # TO DO: alpha_k = alpha_0 / (1 + k / tau): the sum diverges, the sum of squares convergesd_const, d_dec = sgd_distance(constant), sgd_distance(decreasing)for k in [100, 1000, 5000, 20000]: print(f"after {k:5d} steps: constant {np.mean(d_const[k - 100:k]):.4f} | decreasing {np.mean(d_dec[k - 100:k]):.4f}")def smooth(d, w=200): return np.convolve(d, np.ones(w) / w, mode="valid") # a moving average makes the plateau visibleplt.loglog(smooth(d_const), label="constant step 0.05"); plt.loglog(smooth(d_dec), label="decreasing step 0.05 / (1 + k/500)")plt.xlabel("step k"); plt.ylabel("distance to the minimizer (moving average)"); plt.legend(); plt.show()

Show the correction
def sgd_distance(schedule, n_steps=20000, seed=3): r = np.random.default_rng(seed) theta, dist = np.zeros(2), [] for k in range(n_steps): i = r.integers(0, N, 1) theta = theta - schedule(k) * batch_gradient(theta, i) # one example per step, with the step size given by the schedule dist.append(np.linalg.norm(theta - theta_star)) return np.array(dist)constant = lambda k: 0.05 # a constant step sizedecreasing = lambda k: 0.05 / (1 + k / 500) # alpha_k = alpha_0 / (1 + k / tau): the sum diverges, the sum of squares convergesd_const, d_dec = sgd_distance(constant), sgd_distance(decreasing)for k in [100, 1000, 5000, 20000]: print(f"after {k:5d} steps: constant {np.mean(d_const[k - 100:k]):.4f} | decreasing {np.mean(d_dec[k - 100:k]):.4f}")def smooth(d, w=200): return np.convolve(d, np.ones(w) / w, mode="valid") # a moving average makes the plateau visibleplt.loglog(smooth(d_const), label="constant step 0.05"); plt.loglog(smooth(d_dec), label="decreasing step 0.05 / (1 + k/500)")plt.xlabel("step k"); plt.ylabel("distance to the minimizer (moving average)"); plt.legend(); plt.show()
The two runs are identical at the beginning (0.85 after 100 steps). With the constant step the distance stops decreasing near $0.18$–$0.20$: this is the plateau of the noise. With the decreasing step it continues: $0.090$ at 1,000 steps and $0.046$ at 20,000. The decrease is slow ($\alpha_k\sim1/k$ gives an error in $1/\sqrt k$), which is the second reason to look for faster methods in Parts 5 and 6.
Part 4 · Conditioning: normalize your data
Conditioning of the regression problem
On these data ($x\in[0,5]$) the Hessian $\frac1NX^TX$ has a condition number $\kappa$ of about 65: the level sets of $J$ are very elongated ellipses and GD crawls along the valley. Tick Standardize x in the demonstration of Part 2: the level sets become circles and GD converges in a few steps.
Why standardizing gives $\kappa=1$
Replace $x_i$ by $z_i=(x_i-\bar x)/s$, with $\bar x$ the mean and $s$ the standard deviation. Then $\frac1N\sum z_i=0$ and $\frac1N\sum z_i^2=1$, so $\frac1NX^TX=\begin{pmatrix}1&0\\0&1\end{pmatrix}$: all eigenvalues are equal and $\kappa=1$. Gradient descent with $\alpha=1$ then reaches $\theta^*$ in one step.
Preconditioning and the speed of gradient descent
Standardizing the inputs is the simplest preconditioning: a change of variables that makes the problem better conditioned. For a quadratic whose Hessian has eigenvalues between $\mu$ and $L$, $\kappa=L/\mu$.
For $f(z)=\tfrac12 z^THz$ with eigenvalues of $H$ in $[\mu,L]$, gradient descent with step $\alpha\in(0,2/L)$ converges, and with $\alpha=1/L$ the distance to the minimizer is multiplied at each step by at most $1-1/\kappa$. To divide it by $10^6$ one needs about $\kappa\ln(10^6)\approx13.8\,\kappa$ iterations.
Proof
$z_{k+1}=(I-\alpha H)z_k$. In the eigenbasis of $H$ each coordinate is multiplied by $1-\alpha\lambda$ with $\lambda\in[\mu,L]$. For $\alpha=1/L$, $0\le1-\lambda/L\le1-\mu/L=1-1/\kappa$. For $\alpha<2/L$ we have $|1-\alpha\lambda|<1$ for all $\lambda\le L$, hence convergence. $\square$
Exercise 4.1 · the number of iterations grows like $\kappa$
- Write the function and the gradient of $f(z)=\frac12(z_1^2+\kappa z_2^2)$ and a gradient descent with step $1/L=1/\kappa$.
- For $\kappa=1,10,100$, count the iterations needed to reach $\|z\|<10^{-6}$ from $(1,1)$ and compare with $\ln(10^{-6})/\ln(1-1/\kappa)$.
def quadratic(kappa): """f(z) = 1/2 (z1^2 + kappa z2^2): its Hessian has eigenvalues 1 and kappa, so its condition number is kappa.""" f = lambda z: 0.5 * (z[0] ** 2 + kappa * z[1] ** 2) g = ... # TO DO: gradient of the quadratic return f, gdef gradient_descent(g, z0, alpha, n_iter): z, path = np.array(z0, float), [np.array(z0, float)] for _ in range(n_iter): z = ... # TO DO: z <- z - alpha grad f(z) path.append(z.copy()) return np.array(path)def iterations_to(path, tol=1e-6): norms = np.linalg.norm(path, axis=1) hit = np.flatnonzero(norms < tol) return int(hit[0]) if len(hit) else Nonefor kappa in [1, 10, 100]: f, g = quadratic(kappa) path = ... # TO DO: the best constant step 1 / L, L = kappa the largest eigenvalue theory = np.log(1e-6) / np.log(1 - 1.0 / kappa) if kappa > 1 else 1 print(f"kappa = {kappa:3d}: iterations to reach 1e-6: {iterations_to(path)} | theory ln(1e-6)/ln(1 - 1/kappa) = {theory:.0f}")
Show the correction
def quadratic(kappa): """f(z) = 1/2 (z1^2 + kappa z2^2): its Hessian has eigenvalues 1 and kappa, so its condition number is kappa.""" f = lambda z: 0.5 * (z[0] ** 2 + kappa * z[1] ** 2) g = lambda z: np.array([z[0], kappa * z[1]]) # gradient of the quadratic return f, gdef gradient_descent(g, z0, alpha, n_iter): z, path = np.array(z0, float), [np.array(z0, float)] for _ in range(n_iter): z = z - alpha * g(z) # z <- z - alpha grad f(z) path.append(z.copy()) return np.array(path)def iterations_to(path, tol=1e-6): norms = np.linalg.norm(path, axis=1) hit = np.flatnonzero(norms < tol) return int(hit[0]) if len(hit) else Nonefor kappa in [1, 10, 100]: f, g = quadratic(kappa) path = gradient_descent(g, [1.0, 1.0], alpha=1.0 / kappa, n_iter=5000) # the best constant step 1 / L, L = kappa the largest eigenvalue theory = np.log(1e-6) / np.log(1 - 1.0 / kappa) if kappa > 1 else 1 print(f"kappa = {kappa:3d}: iterations to reach 1e-6: {iterations_to(path)} | theory ln(1e-6)/ln(1 - 1/kappa) = {theory:.0f}")
The counts are 1, 132 and 1,375 iterations for $\kappa=1,10,100$, against 1, 131 and 1,375 from the formula: the cost is proportional to $\kappa$. A bad conditioning is the enemy; momentum (next part) turns $\kappa$ into $\sqrt\kappa$.
Part 5 · Momentum, anticipation and Nesterov
Animation: gradient descent, heavy ball and Nesterov on a rotated quadratic of condition number 50. Change $\beta$ and the step size; see the zigzag of gradient descent disappear and the overshoot of the momentum.
Anticipation: keep a velocity
In a narrow valley, the gradient is large across the valley and small along it. Gradient descent oscillates from one side to the other and advances slowly along the valley. Momentum (the heavy ball of Polyak, 1964) gives the point inertia: it remembers the previous displacement,
\[ v_{k+1}=\beta\,v_k-\alpha\,\nabla f(z_k),\qquad z_{k+1}=z_k+v_{k+1},\qquad \beta\in[0,1). \]The oscillating components of the gradient (which change sign at each step) cancel in the velocity, while the components that keep the same sign (along the valley) add up: in a constant gradient $g$ the velocity tends to $-\alpha g/(1-\beta)$, a step $1/(1-\beta)$ times larger (10 times for $\beta=0.9$).
For $f(z)=\tfrac12z^THz$ with eigenvalues in $[\mu,L]$, the choice $\alpha=\dfrac{4}{(\sqrt L+\sqrt\mu)^2}$, $\beta=\Big(\dfrac{\sqrt\kappa-1}{\sqrt\kappa+1}\Big)^2$ gives a convergence at rate $\dfrac{\sqrt\kappa-1}{\sqrt\kappa+1}\approx1-\dfrac2{\sqrt\kappa}$ per iteration, instead of $1-\dfrac1\kappa$ for gradient descent.
Proof
In the eigenbasis of $H$ the recursion decouples into $x_{k+1}=(1+\beta-\alpha\lambda)x_k-\beta x_{k-1}$ for each eigenvalue $\lambda$, whose characteristic polynomial is $r^2-(1+\beta-\alpha\lambda)r+\beta$. When the roots are complex their modulus is $\sqrt\beta$, whatever $\lambda$. This holds for every $\lambda\in[\mu,L]$ if $(1-\sqrt\beta)^2\le\alpha\lambda\le(1+\sqrt\beta)^2$, which is true for the two extreme eigenvalues with the above $\alpha,\beta$. The rate is then $\sqrt\beta=\frac{\sqrt\kappa-1}{\sqrt\kappa+1}$. $\square$
Exercise 5.1 · the heavy ball
- Implement the heavy ball: the velocity
v = beta*v - alpha*grad, thenz = z + v. - On $f=\frac12(z_1^2+100z_2^2)$, take the optimal $\alpha,\beta$ of the theorem and compare the iterations to reach $10^{-6}$ with gradient descent of step $1/L$.
- Plot the distance to the minimizer of both methods and check the contraction factors per iteration.
def heavy_ball(g, z0, alpha, beta, n_iter): z, v, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): v = ... # TO DO: the velocity remembers the previous displacement z = ... # TO DO: move with the velocity path.append(z.copy()) return np.array(path)kappa = 100.0f, g = quadratic(kappa)beta_opt = ... # TO DO: optimal momentum for a quadratic of condition number kappaalpha_opt = 4.0 / (1.0 + np.sqrt(kappa)) ** 2 # and the matching step size (smallest eigenvalue is 1)gd = gradient_descent(g, [1.0, 1.0], 1.0 / kappa, 1600)hb = heavy_ball(g, [1.0, 1.0], alpha_opt, beta_opt, 1600)print(f"beta* = {beta_opt:.4f}, alpha* = {alpha_opt:.4f}")print("iterations to reach 1e-6: gradient descent", iterations_to(gd), "| heavy ball", iterations_to(hb))print("contraction factors per iteration: GD", 1 - 1 / kappa, "| heavy ball", (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1))plt.semilogy(np.linalg.norm(gd, axis=1), label="gradient descent"); plt.semilogy(np.linalg.norm(hb, axis=1), label="heavy ball")plt.xlabel("iteration"); plt.ylabel("distance to the minimizer"); plt.legend(); plt.show()

Show the correction
def heavy_ball(g, z0, alpha, beta, n_iter): z, v, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): v = beta * v - alpha * g(z) # the velocity remembers the previous displacement z = z + v # move with the velocity path.append(z.copy()) return np.array(path)kappa = 100.0f, g = quadratic(kappa)beta_opt = ((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)) ** 2 # optimal momentum for a quadratic of condition number kappaalpha_opt = 4.0 / (1.0 + np.sqrt(kappa)) ** 2 # and the matching step size (smallest eigenvalue is 1)gd = gradient_descent(g, [1.0, 1.0], 1.0 / kappa, 1600)hb = heavy_ball(g, [1.0, 1.0], alpha_opt, beta_opt, 1600)print(f"beta* = {beta_opt:.4f}, alpha* = {alpha_opt:.4f}")print("iterations to reach 1e-6: gradient descent", iterations_to(gd), "| heavy ball", iterations_to(hb))print("contraction factors per iteration: GD", 1 - 1 / kappa, "| heavy ball", (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1))plt.semilogy(np.linalg.norm(gd, axis=1), label="gradient descent"); plt.semilogy(np.linalg.norm(hb, axis=1), label="heavy ball")plt.xlabel("iteration"); plt.ylabel("distance to the minimizer"); plt.legend(); plt.show()
With $\beta^*=0.669$ and $\alpha^*=0.0331$ the heavy ball reaches $10^{-6}$ in 95 iterations, against 1,375 for gradient descent: the gain is of the order of $\sqrt\kappa$, i.e. a contraction of 0.818 per iteration instead of 0.99. The curve of the heavy ball oscillates slightly (the complex roots), that of gradient descent is a straight line in log scale.
Nesterov: look before you leap
The heavy ball computes the gradient at the current point $z_k$, then adds the velocity. Nesterov (1983) evaluates the gradient where the velocity is about to carry us:
\[ \tilde z_k=z_k+\beta v_k,\qquad v_{k+1}=\beta v_k-\alpha\nabla f(\tilde z_k),\qquad z_{k+1}=z_k+v_{k+1}. \]It is an anticipation: if the ball is about to overshoot the valley floor, the gradient at the look-ahead point already points back and brakes earlier. For a convex $L$-smooth function this gives the optimal rate $f(z_k)-f^*=O(1/k^2)$ for first-order methods, against $O(1/k)$ for gradient descent. In Keras it is SGD(momentum=0.9, nesterov=True).
Exercise 5.2 · Nesterov against classical momentum
- Implement Nesterov: compute the look-ahead point, the gradient there, the velocity, the update.
- With the same step $1/L$ and the same $\beta=0.818$ on the quadratic $\kappa=100$, compare the iterations of classical momentum and of Nesterov to reach $10^{-6}$.
- Do the same experiment on a non-quadratic valley and compare $f$ after 300 iterations. What do you conclude?
def nesterov(g, z0, alpha, beta, n_iter): z, v, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): lookahead = ... # TO DO: where the momentum is about to carry us v = ... # TO DO: the gradient is evaluated at the look-ahead point z = z + v path.append(z.copy()) return np.array(path)kappa = 100.0f, g = quadratic(kappa)beta_n = (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1) # Nesterov's momentum for a strongly convex functionnest = nesterov(g, [1.0, 1.0], 1.0 / kappa, beta_n, 800)plain_momentum = heavy_ball(g, [1.0, 1.0], 1.0 / kappa, beta_n, 800) # classical momentum with the same step and the same betaprint("same step 1/L and same beta =", round(beta_n, 3))print("iterations to reach 1e-6: classical momentum", iterations_to(plain_momentum), "| Nesterov", iterations_to(nest))# a non-quadratic valley: f(z) = log(1 + exp(z1)) + 0.5 * 20 * z2^2 (logistic term and a stiff direction)fn = lambda z: np.log1p(np.exp(z[0])) + 10.0 * z[1] ** 2gn = lambda z: np.array([1 / (1 + np.exp(-z[0])), 20.0 * z[1]])a, b = 0.02, 0.9p_hb = heavy_ball(gn, [-4.0, 1.0], a, b, 300); p_nv = nesterov(gn, [-4.0, 1.0], a, b, 300)print("value of f after 300 iterations: classical momentum", fn(p_hb[-1]), "| Nesterov", fn(p_nv[-1]))plt.semilogy(np.linalg.norm(plain_momentum, axis=1), label="classical momentum"); plt.semilogy(np.linalg.norm(nest, axis=1), label="Nesterov")plt.xlabel("iteration"); plt.ylabel("distance to the minimizer"); plt.legend(); plt.show()

Show the correction
def nesterov(g, z0, alpha, beta, n_iter): z, v, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): lookahead = z + beta * v # where the momentum is about to carry us v = beta * v - alpha * g(lookahead) # the gradient is evaluated at the look-ahead point z = z + v path.append(z.copy()) return np.array(path)kappa = 100.0f, g = quadratic(kappa)beta_n = (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1) # Nesterov's momentum for a strongly convex functionnest = nesterov(g, [1.0, 1.0], 1.0 / kappa, beta_n, 800)plain_momentum = heavy_ball(g, [1.0, 1.0], 1.0 / kappa, beta_n, 800) # classical momentum with the same step and the same betaprint("same step 1/L and same beta =", round(beta_n, 3))print("iterations to reach 1e-6: classical momentum", iterations_to(plain_momentum), "| Nesterov", iterations_to(nest))# a non-quadratic valley: f(z) = log(1 + exp(z1)) + 0.5 * 20 * z2^2 (logistic term and a stiff direction)fn = lambda z: np.log1p(np.exp(z[0])) + 10.0 * z[1] ** 2gn = lambda z: np.array([1 / (1 + np.exp(-z[0])), 20.0 * z[1]])a, b = 0.02, 0.9p_hb = heavy_ball(gn, [-4.0, 1.0], a, b, 300); p_nv = nesterov(gn, [-4.0, 1.0], a, b, 300)print("value of f after 300 iterations: classical momentum", fn(p_hb[-1]), "| Nesterov", fn(p_nv[-1]))plt.semilogy(np.linalg.norm(plain_momentum, axis=1), label="classical momentum"); plt.semilogy(np.linalg.norm(nest, axis=1), label="Nesterov")plt.xlabel("iteration"); plt.ylabel("distance to the minimizer"); plt.legend(); plt.show()
On these examples the two methods are practically equal: 149 and 158 iterations on the quadratic, and $f=0.00878$ and $0.00879$ on the valley after 300 iterations. We do not observe a gain for Nesterov here: its advantage is a guarantee (the $1/k^2$ rate for convex functions, with $\beta_k$ increasing to 1) that classical momentum does not have, and on a quadratic with well chosen parameters both are close to optimal. Compare on your problem rather than assume.
Part 6 · RMSProp and Adam: one step size per coordinate
Two animations first: the five methods of Parts 5 and 6 on a rotated quadratic of condition number 50 and on the Rosenbrock valley. Choose the methods, the step sizes and the coefficients, and press play.
Why a different step for each coordinate?
Even with momentum, all the coordinates share the same step $\alpha$. But in a neural network some weights have gradients of size $10^{-4}$ and others of size $10^{2}$ (input scale, depth, rare features). A step good for the second ones is too small for the first ones, and a step good for the first ones makes the second ones diverge. This is the same problem of conditioning as in Part 4, but without the possibility of rescaling by hand: the scale changes with the weight and with the time.
RMSProp (Hinton, 2012) keeps a moving average of the squared gradient, coordinate by coordinate, and divides the step by its square root:
\[ s_{k+1}=\rho\,s_k+(1-\rho)\,g_k^{\,2},\qquad z_{k+1}=z_k-\alpha\,\frac{g_k}{\sqrt{s_{k+1}}+\varepsilon}\qquad(g_k=\nabla f(z_k)\text{ or its stochastic estimate}). \]The division is coordinate-wise: a coordinate with large gradients gets a smaller effective step, one with small gradients gets a larger one. Each step is of size about $\alpha$ in every coordinate whatever the scale of the gradient ($g/\sqrt{\mathbb E g^2}\approx\pm1$): the method is almost invariant to a rescaling of each coordinate. With a stochastic gradient, $\sqrt s$ also estimates the size of the noise, and the step becomes small where the signal is weak compared with the noise.
Adam: momentum for the direction, RMSProp for the scale
Adam (Kingma and Ba, 2015) combines the two moving averages: the first moment $m$ of the gradient (the direction, like momentum, but averaged instead of accumulated) and the second moment $s$ of its square (the scale, as in RMSProp):
\[ m_t=\beta_1m_{t-1}+(1-\beta_1)g_t,\quad s_t=\beta_2s_{t-1}+(1-\beta_2)g_t^{\,2},\quad \hat m_t=\frac{m_t}{1-\beta_1^t},\quad \hat s_t=\frac{s_t}{1-\beta_2^t},\quad z_{t+1}=z_t-\alpha\frac{\hat m_t}{\sqrt{\hat s_t}+\varepsilon}, \]with the usual values $\beta_1=0.9$, $\beta_2=0.999$, $\varepsilon=10^{-8}$. The two divisions by $1-\beta^t$ are the bias correction.
If the gradient is constant, $g_t=g$ for all $t$, then $m_t=(1-\beta_1^t)\,g$ and $s_t=(1-\beta_2^t)\,g^2$. Hence $\hat m_t=g$ and $\hat s_t=g^2$ exactly, and the first step is $\alpha\,\mathrm{sign}(g)$. Without the correction, $m_1=0.1\,g$ and $s_1=0.001\,g^2$, so that the first step would be $0.1\,g/(0.0316\,|g|)\approx3.16\,\alpha\,\mathrm{sign}(g)$: too large.
Proof
By induction: $m_1=(1-\beta_1)g$ and $m_t=\beta_1(1-\beta_1^{t-1})g+(1-\beta_1)g=(1-\beta_1^t)g$. The same holds for $s_t$ with $g^2$ and $\beta_2$. $\square$
Exercise 6.1 · RMSProp, Adam and the bias correction
- Implement
rmsprop(moving average of $g^2$) andadamwith a switch for the bias correction. - Check the proposition with a constant gradient equal to 1: print $m_t$, $\hat m_t$, $s_t$, $\hat s_t$ for $t=1,\dots,5$.
- On $f=\frac12(z_1^2+100z_2^2)$ with $\alpha=0.1$, print the first coordinate of the first four iterates of Adam with and without the correction.
def rmsprop(g, z0, alpha=0.01, rho=0.9, eps=1e-8, n_iter=500): z, s, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): grad = g(z) s = ... # TO DO: moving average of the squared gradient, coordinate by coordinate z = ... # TO DO: divide each coordinate by its recent typical size path.append(z.copy()) return np.array(path)def adam(g, z0, alpha=0.1, b1=0.9, b2=0.999, eps=1e-8, n_iter=500, correct=True): z, m, s, path = np.array(z0, float), np.zeros(2), np.zeros(2), [np.array(z0, float)] for t in range(1, n_iter + 1): grad = g(z) m = ... # TO DO: first moment: a moving average of the gradient (momentum) s = ... # TO DO: second moment: a moving average of the squared gradient (RMSProp) m_hat = ... # TO DO: bias correction: m starts at 0 and is too small at the beginning s_hat = s / (1 - b2 ** t) if correct else s z = z - alpha * m_hat / (np.sqrt(s_hat) + eps) path.append(z.copy()) return np.array(path)# why the bias correction? with a constant gradient g, m_t = (1 - b1^t) g and s_t = (1 - b2^t) g^2grad_const = 1.0m, s = 0.0, 0.0for t in range(1, 6): m = 0.9 * m + 0.1 * grad_const; s = 0.999 * s + 0.001 * grad_const ** 2 print(f"t = {t}: m = {m:.4f}, m/(1-b1^t) = {m / (1 - 0.9 ** t):.4f} | s = {s:.5f}, s/(1-b2^t) = {s / (1 - 0.999 ** t):.4f}")f, g = quadratic(100.0)print("first steps of Adam with and without the correction (alpha = 0.1):")print(" corrected :", adam(g, [1.0, 1.0], n_iter=3)[:4, 0])print(" uncorrected:", adam(g, [1.0, 1.0], n_iter=3, correct=False)[:4, 0])
Show the correction
def rmsprop(g, z0, alpha=0.01, rho=0.9, eps=1e-8, n_iter=500): z, s, path = np.array(z0, float), np.zeros(2), [np.array(z0, float)] for _ in range(n_iter): grad = g(z) s = rho * s + (1 - rho) * grad ** 2 # moving average of the squared gradient, coordinate by coordinate z = z - alpha * grad / (np.sqrt(s) + eps) # divide each coordinate by its recent typical size path.append(z.copy()) return np.array(path)def adam(g, z0, alpha=0.1, b1=0.9, b2=0.999, eps=1e-8, n_iter=500, correct=True): z, m, s, path = np.array(z0, float), np.zeros(2), np.zeros(2), [np.array(z0, float)] for t in range(1, n_iter + 1): grad = g(z) m = b1 * m + (1 - b1) * grad # first moment: a moving average of the gradient (momentum) s = b2 * s + (1 - b2) * grad ** 2 # second moment: a moving average of the squared gradient (RMSProp) m_hat = m / (1 - b1 ** t) if correct else m # bias correction: m starts at 0 and is too small at the beginning s_hat = s / (1 - b2 ** t) if correct else s z = z - alpha * m_hat / (np.sqrt(s_hat) + eps) path.append(z.copy()) return np.array(path)# why the bias correction? with a constant gradient g, m_t = (1 - b1^t) g and s_t = (1 - b2^t) g^2grad_const = 1.0m, s = 0.0, 0.0for t in range(1, 6): m = 0.9 * m + 0.1 * grad_const; s = 0.999 * s + 0.001 * grad_const ** 2 print(f"t = {t}: m = {m:.4f}, m/(1-b1^t) = {m / (1 - 0.9 ** t):.4f} | s = {s:.5f}, s/(1-b2^t) = {s / (1 - 0.999 ** t):.4f}")f, g = quadratic(100.0)print("first steps of Adam with and without the correction (alpha = 0.1):")print(" corrected :", adam(g, [1.0, 1.0], n_iter=3)[:4, 0])print(" uncorrected:", adam(g, [1.0, 1.0], n_iter=3, correct=False)[:4, 0])
With the correction the corrected moments are exactly 1 at each step, while $m_t$ is only 0.1 at the first step and 0.41 at the fifth. On the quadratic, Adam with the correction moves regularly: $1,\ 0.900,\ 0.800,\ 0.702$ (about $\alpha$ per step); without it the first step is 3.2 times larger and the iterate crosses the minimum: $1,\ 0.684,\ 0.270,\ -0.162$.
Compare the five methods: do not trust a single picture
The animation below uses the demonstration library of the site. Choose a function (the rotated quadratic of condition number 50, the Rosenbrock valley…), tick the methods, and press play. Each method has its step size and its coefficients: we cannot say that one is better from one run. Look at how they move: gradient descent zigzags, momentum and Nesterov overshoot then come back, RMSProp and Adam move in almost the same step in each coordinate.
The step sizes are not the same for each method: the stability limit of gradient descent is $2/L$, but Adam has a step of about $\alpha$ per coordinate, so its natural step is of the order of the distance to be travelled and it must be decreased near the minimum.
Exercise 6.2 · the same experiment in Python
- On the quadratic $\kappa=100$ and on the Rosenbrock valley $f=(1-x)^2+100(y-x^2)^2$, run the five methods with the proposed step sizes.
- Print the remaining gap $f-f^*$ after 400 (quadratic) and 4,000 (Rosenbrock) iterations and plot the five curves.
- Which method is best on each problem? Change the step sizes by a factor 3 and see whether the ranking changes.
def rosenbrock(z): return (1 - z[0]) ** 2 + 100 * (z[1] - z[0] ** 2) ** 2def rosenbrock_grad(z): return np.array([-2 * (1 - z[0]) - 400 * z[0] * (z[1] - z[0] ** 2), 200 * (z[1] - z[0] ** 2)])problems = { "quadratic, kappa = 100": (quadratic(100.0)[0], quadratic(100.0)[1], [1.0, 1.0], np.array([0.0, 0.0]), 400), "Rosenbrock valley": (rosenbrock, rosenbrock_grad, [-1.2, 1.0], np.array([1.0, 1.0]), 4000),}settings = { # one reasonable step size per method and problem "quadratic, kappa = 100": {"GD": ("gd", 0.01), "momentum": ("hb", 0.0331, 0.6694), "Nesterov": ("nv", 0.01, 0.9), "RMSProp": ("rms", 0.02), "Adam": ("adam", 0.1)}, "Rosenbrock valley": {"GD": ("gd", 0.0005), "momentum": ("hb", 0.0003, 0.9), "Nesterov": ("nv", 0.0003, 0.9), "RMSProp": ("rms", 0.005), "Adam": ("adam", 0.05)},}def run_method(spec, g, z0, n): kind = spec[0] if kind == "gd": return gradient_descent(g, z0, spec[1], n) if kind == "hb": return heavy_ball(g, z0, spec[1], spec[2], n) if kind == "nv": return nesterov(g, z0, spec[1], spec[2], n) if kind == "rms": return rmsprop(g, z0, alpha=spec[1], n_iter=n) return ... # TO DO: one call for each of the five methodsfig, axes = plt.subplots(1, 2, figsize=(13, 4.8))for ax, (name, (f, g, z0, zs, n)) in zip(axes, problems.items()): print(name) for method, spec in settings[name].items(): path = run_method(spec, g, z0, n) gap = ... # TO DO: remaining gap to the optimal value after n iterations print(f" {method:9s} f - f* after {n} iterations: {gap:.2e}") ax.semilogy([f(p) - f(zs) + 1e-16 for p in path], label=method) ax.set_title(name); ax.set_xlabel("iteration"); ax.set_ylabel("f - f*"); ax.legend()plt.show()

Show the correction
def rosenbrock(z): return (1 - z[0]) ** 2 + 100 * (z[1] - z[0] ** 2) ** 2def rosenbrock_grad(z): return np.array([-2 * (1 - z[0]) - 400 * z[0] * (z[1] - z[0] ** 2), 200 * (z[1] - z[0] ** 2)])problems = { "quadratic, kappa = 100": (quadratic(100.0)[0], quadratic(100.0)[1], [1.0, 1.0], np.array([0.0, 0.0]), 400), "Rosenbrock valley": (rosenbrock, rosenbrock_grad, [-1.2, 1.0], np.array([1.0, 1.0]), 4000),}settings = { # one reasonable step size per method and problem "quadratic, kappa = 100": {"GD": ("gd", 0.01), "momentum": ("hb", 0.0331, 0.6694), "Nesterov": ("nv", 0.01, 0.9), "RMSProp": ("rms", 0.02), "Adam": ("adam", 0.1)}, "Rosenbrock valley": {"GD": ("gd", 0.0005), "momentum": ("hb", 0.0003, 0.9), "Nesterov": ("nv", 0.0003, 0.9), "RMSProp": ("rms", 0.005), "Adam": ("adam", 0.05)},}def run_method(spec, g, z0, n): kind = spec[0] if kind == "gd": return gradient_descent(g, z0, spec[1], n) if kind == "hb": return heavy_ball(g, z0, spec[1], spec[2], n) if kind == "nv": return nesterov(g, z0, spec[1], spec[2], n) if kind == "rms": return rmsprop(g, z0, alpha=spec[1], n_iter=n) return adam(g, z0, alpha=spec[1], n_iter=n) # one call for each of the five methodsfig, axes = plt.subplots(1, 2, figsize=(13, 4.8))for ax, (name, (f, g, z0, zs, n)) in zip(axes, problems.items()): print(name) for method, spec in settings[name].items(): path = run_method(spec, g, z0, n) gap = f(path[-1]) - f(zs) # remaining gap to the optimal value after n iterations print(f" {method:9s} f - f* after {n} iterations: {gap:.2e}") ax.semilogy([f(p) - f(zs) + 1e-16 for p in path], label=method) ax.set_title(name); ax.set_xlabel("iteration"); ax.set_ylabel("f - f*"); ax.legend()plt.show()
| $f-f^*$ after $n$ iterations | GD | momentum | Nesterov | RMSProp | Adam |
|---|---|---|---|---|---|
| quadratic $\kappa=100$ (400) | 1.6e-4 | 1.9e-41 | 1.8e-21 | 5.1e-3 | 1.7e-17 |
| Rosenbrock (4,000) | 7.9e-2 | 9.4e-6 | 1.0e-5 | 5.6e-3 | 4.4e-29 |
With these tuned steps momentum is the best on the quadratic (the optimal parameters of the theorem are known there) and Adam is the best on the Rosenbrock valley; RMSProp with a constant step plateaus around $10^{-3}$ because its step stays of the order of $\alpha$ near the minimum. This is a table for these steps, not a ranking: with a bad step each of them can diverge.
Part 7 · All the optimizers in Keras
The optimizers of Keras
Keras provides all the methods of this page: SGD(lr), SGD(lr, momentum=0.9), SGD(lr, momentum=0.9, nesterov=True), RMSprop(lr, rho=0.9), Adam(lr, beta_1=0.9, beta_2=0.999). An optimizer takes a list of pairs (gradient, variable) with apply_gradients; model.fit does it for you after the computation of the gradient of the loss on a mini-batch.
Exercise 7.1 · check your code against Keras
- Write a function that minimizes a function of a
tf.Variablewith a Keras optimizer, withtf.GradientTapeandapply_gradients. - On the quadratic $\kappa=100$, compare 100 iterations of Keras with your implementations of SGD, momentum, RMSProp and Adam, and print the largest difference.
- Print the final point of Keras Nesterov. Why do we not compare it term by term?
def keras_path(optimizer, g_fun, z0, n_iter): z = tf.Variable(np.array(z0, dtype="float64")) path = [z.numpy().copy()] for _ in range(n_iter): with tf.GradientTape() as tape: value = ... # TO DO: the function to minimize, written with TensorFlow operations ... # TO DO: the Keras optimizer updates the variable path.append(z.numpy().copy()) return np.array(path)f_tf = lambda z: 0.5 * (z[0] ** 2 + 100.0 * z[1] ** 2)f_np, g_np = quadratic(100.0)checks = [ ("SGD", keras.optimizers.SGD(0.01), gradient_descent(g_np, [1.0, 1.0], 0.01, 100)), ("SGD + momentum", keras.optimizers.SGD(0.0331, momentum=0.6694), heavy_ball(g_np, [1.0, 1.0], 0.0331, 0.6694, 100)), ("SGD + Nesterov", keras.optimizers.SGD(0.01, momentum=0.9, nesterov=True), None), ("RMSprop", keras.optimizers.RMSprop(0.02, rho=0.9), rmsprop(g_np, [1.0, 1.0], alpha=0.02, n_iter=100)), ("Adam", keras.optimizers.Adam(0.1), adam(g_np, [1.0, 1.0], alpha=0.1, n_iter=100)),]for name, opt, mine in checks: kp = keras_path(opt, f_tf, [1.0, 1.0], 100) if mine is None: print(f"{name:16s}: final point {kp[-1]} (Nesterov in Keras uses the reformulated update; compare with your own implementation)") else: print(f"{name:16s}: largest difference with our implementation over 100 steps = {np.abs(kp - mine).max():.2e}")
Show the correction
def keras_path(optimizer, g_fun, z0, n_iter): z = tf.Variable(np.array(z0, dtype="float64")) path = [z.numpy().copy()] for _ in range(n_iter): with tf.GradientTape() as tape: value = g_fun(z) # the function to minimize, written with TensorFlow operations optimizer.apply_gradients([(tape.gradient(value, z), z)]) # the Keras optimizer updates the variable path.append(z.numpy().copy()) return np.array(path)f_tf = lambda z: 0.5 * (z[0] ** 2 + 100.0 * z[1] ** 2)f_np, g_np = quadratic(100.0)checks = [ ("SGD", keras.optimizers.SGD(0.01), gradient_descent(g_np, [1.0, 1.0], 0.01, 100)), ("SGD + momentum", keras.optimizers.SGD(0.0331, momentum=0.6694), heavy_ball(g_np, [1.0, 1.0], 0.0331, 0.6694, 100)), ("SGD + Nesterov", keras.optimizers.SGD(0.01, momentum=0.9, nesterov=True), None), ("RMSprop", keras.optimizers.RMSprop(0.02, rho=0.9), rmsprop(g_np, [1.0, 1.0], alpha=0.02, n_iter=100)), ("Adam", keras.optimizers.Adam(0.1), adam(g_np, [1.0, 1.0], alpha=0.1, n_iter=100)),]for name, opt, mine in checks: kp = keras_path(opt, f_tf, [1.0, 1.0], 100) if mine is None: print(f"{name:16s}: final point {kp[-1]} (Nesterov in Keras uses the reformulated update; compare with your own implementation)") else: print(f"{name:16s}: largest difference with our implementation over 100 steps = {np.abs(kp - mine).max():.2e}")
The largest differences are $2\times10^{-8}$ (SGD), $1.5\times10^{-5}$ (momentum), $1.3\times10^{-7}$ (RMSProp) and $6.7\times10^{-6}$ (Adam): the same algorithms, up to the details of $\varepsilon$ and of float precision. Keras writes Nesterov with a reformulated update (the gradient is evaluated at the current point and the correction is applied to the velocity), which gives the same sequence in another variable, so the iterates are not term by term those of the look-ahead form.
Exercise 7.2 · five optimizers on MNIST
- Load MNIST, keep 20,000 training images, and build a network with a hidden layer of 64 units.
- Train the same network (same initial weights, batch 64, 8 epochs) with the five optimizers of the page.
- Plot the training loss against the epoch and print the test accuracy. Which optimizer is best? Is it the one you expected?
(x_tr_all, y_tr_all), (x_te_all, y_te_all) = keras.datasets.mnist.load_data()x_tr = x_tr_all[:20000].reshape(-1, 784).astype("float32") / 255.0y_tr = y_tr_all[:20000]x_te = x_te_all.reshape(-1, 784).astype("float32") / 255.0def make_model(): keras.utils.set_random_seed(SEED) # the same initial weights for every optimizer return keras.Sequential([keras.Input(shape=(784,)), layers.Dense(64, activation="relu"), layers.Dense(10)])optimizers = { "SGD": lambda: keras.optimizers.SGD(0.05), "SGD + momentum": lambda: keras.optimizers.SGD(0.05, momentum=0.9), "SGD + Nesterov": lambda: keras.optimizers.SGD(0.05, momentum=0.9, nesterov=True), "RMSprop": lambda: keras.optimizers.RMSprop(0.001), "Adam": ..., # TO DO: the five optimizers of the course, as Keras objects}histories = {}for name, make_opt in optimizers.items(): model = make_model() model.compile(optimizer=make_opt(), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"]) hist = ... # TO DO: the same data, the same batch size, 8 epochs histories[name] = hist.history["loss"] print(f"{name:16s}: training loss after 1 and 8 epochs {hist.history['loss'][0]:.3f}, {hist.history['loss'][-1]:.3f} | test accuracy {model.evaluate(x_te, y_te_all, verbose=0)[1]:.3f}")for name, losses in histories.items(): plt.plot(range(1, 9), losses, "o-", label=name)plt.xlabel("epoch"); plt.ylabel("training loss"); plt.yscale("log"); plt.legend(); plt.show()

Show the correction
(x_tr_all, y_tr_all), (x_te_all, y_te_all) = keras.datasets.mnist.load_data()x_tr = x_tr_all[:20000].reshape(-1, 784).astype("float32") / 255.0y_tr = y_tr_all[:20000]x_te = x_te_all.reshape(-1, 784).astype("float32") / 255.0def make_model(): keras.utils.set_random_seed(SEED) # the same initial weights for every optimizer return keras.Sequential([keras.Input(shape=(784,)), layers.Dense(64, activation="relu"), layers.Dense(10)])optimizers = { "SGD": lambda: keras.optimizers.SGD(0.05), "SGD + momentum": lambda: keras.optimizers.SGD(0.05, momentum=0.9), "SGD + Nesterov": lambda: keras.optimizers.SGD(0.05, momentum=0.9, nesterov=True), "RMSprop": lambda: keras.optimizers.RMSprop(0.001), "Adam": lambda: keras.optimizers.Adam(0.001), # the five optimizers of the course, as Keras objects}histories = {}for name, make_opt in optimizers.items(): model = make_model() model.compile(optimizer=make_opt(), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"]) hist = model.fit(x_tr, y_tr, epochs=8, batch_size=64, verbose=0) # the same data, the same batch size, 8 epochs histories[name] = hist.history["loss"] print(f"{name:16s}: training loss after 1 and 8 epochs {hist.history['loss'][0]:.3f}, {hist.history['loss'][-1]:.3f} | test accuracy {model.evaluate(x_te, y_te_all, verbose=0)[1]:.3f}")for name, losses in histories.items(): plt.plot(range(1, 9), losses, "o-", label=name)plt.xlabel("epoch"); plt.ylabel("training loss"); plt.yscale("log"); plt.legend(); plt.show()
| loss epoch 1 | loss epoch 8 | test accuracy | |
|---|---|---|---|
| SGD (0.05) | 0.729 | 0.209 | 0.936 |
| SGD + momentum (0.9) | 0.415 | 0.042 | 0.963 |
| SGD + Nesterov | 0.396 | 0.039 | 0.961 |
| RMSprop (0.001) | 0.502 | 0.101 | 0.954 |
| Adam (0.001) | 0.539 | 0.090 | 0.954 |
The three methods with momentum are clearly faster than plain SGD (0.936). In this small experiment, SGD with momentum and with Nesterov is even better than Adam and RMSProp, which are expected to be the most robust: they have a different step size ($10^{-3}$ against $5\times10^{-2}$) and we did not tune either of them. The right conclusion is that Adam is a good default that needs little tuning, not that it always wins; one seed and one network do not settle the question.
References
Papers and documentation
- H. Robbins and S. Monro, A stochastic approximation method, Annals of Mathematical Statistics, 1951.
- B. T. Polyak, Some methods of speeding up the convergence of iteration methods, 1964 (heavy ball).
- Y. Nesterov, A method for solving the convex programming problem with convergence rate $O(1/k^2)$, 1983.
- T. Tieleman and G. Hinton, Lecture 6.5 — RMSProp, Coursera: Neural Networks for Machine Learning, 2012.
- D. Kingma and J. Ba, Adam: a method for stochastic optimization, ICLR 2015.
- L. Bottou, F. Curtis and J. Nocedal, Optimization methods for large-scale machine learning, SIAM Review, 2018.
- S. Ruder, An overview of gradient descent optimization algorithms, 2016.
- See also Neural networks with Keras where these optimizers train a network.