Add momentum to gradient descent

Plain gradient descent zig-zags in narrow valleys. Momentum keeps a running velocity so steps in a consistent direction build up speed.

Write momentum_steps(grad_fn, w0, lr, beta, steps). Start with v = 0 and repeat:
v = beta * v + grad_fn(w)
w = w - lr * v
Return the final w as an array.

Signaturedef momentum_steps(grad_fn, w0, lr, beta, steps)

Understand the idea

Momentum makes gradient descent behave like a ball rolling downhill. Instead of stepping by the raw gradient, you keep a velocity that remembers past gradients, so steady directions speed up and back-and-forth zig-zags cancel out. beta controls how much of the old velocity survives each step. Worked example: f(w) = w^2 / 2, so grad_fn(w) = w. Start w = 1, v = 0, lr = 0.1, beta = 0.9. Step 1: v = 0.9 x 0 + 1 = 1, w = 1 - 0.1 x 1 = 0.9. Step 2: v = 0.9 x 1 + 0.9 = 1.8, w = 0.9 - 0.1 x 1.8 = 0.72. Plain gradient descent would give 0.81 after two steps, so momentum moved faster. Rule: v = beta v + grad(w); w = w - lr v; repeat for the given number of steps. The update must use v, not the raw gradient. Momentum SGD is still used to train vision models such as ResNets.

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

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

  • Sample 1: narrow bowl, 5 stepsmomentum_steps(_g, [5.0, 1.0], 0.02, 0.9, 5)
  • Sample 2: beta 0 is plain GDmomentum_steps(_g, [5.0, 1.0], 0.02, 0.0, 3)
  • Test 3: 50 stepsmomentum_steps(_g, [5.0, 1.0], 0.02, 0.9, 50)