Take a Nesterov momentum step

Why it matters Nesterov momentum is an option in every SGD optimizer used for vision training.

Nesterov momentum evaluates the gradient at the look-ahead point.

Write nesterov_step(w, v, grad_fn, lr, mu). Compute g = grad_fn(w + mu * v), then v_new = mu * v - lr * g and w_new = w + v_new. Return (w_new, v_new).

Signaturedef nesterov_step(w, v, grad_fn, lr, mu)

Example

w = [1], v = [0], grad_fn = lambda x: 2 * x, lr = 0.1, mu = 0.9 gives w [0.8], v [-0.2].

Understand the idea

Plain momentum keeps a velocity v and adds it to the weights each step. Nesterov momentum is smarter: since the weights are about to move by roughly mu * v anyway, it measures the gradient at that look-ahead point instead of at the current weights. This lets it slow down earlier when heading toward a minimum. Worked example: w = [2], v = [-0.5], gradient 2x, lr 0.1, mu 0.9. Look-ahead point = 2 + 0.9 * (-0.5) = 1.55. Gradient there = 3.1. v_new = 0.9 * (-0.5) - 0.1 * 3.1 = -0.45 - 0.31 = -0.76. w_new = 2 - 0.76 = 1.24. Rule: g = grad_fn(w + mu * v); v_new = mu * v - lr * g; w_new = w + v_new; return both. If you evaluate the gradient at w instead, you get ordinary momentum. Used in: SGD with Nesterov momentum for training CNNs, and the idea behind the NAdam optimizer.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplenesterov_step([1.0], [0.0], lambda x: 2 * x, 0.1, 0.9)
  • Sample 2: with velocitynesterov_step([1.0, -2.0], [0.5, 0.5], lambda x: 2 * x, 0.1, 0.9)
  • Test 3: quarticnesterov_step([2.0], [-1.0], lambda x: 4 * x ** 3, 0.01, 0.5)