Implement SGD with classical (heavy-ball) momentum in NumPy

Quick Overview

Implement stochastic gradient descent with classical heavy-ball momentum as a small NumPy optimizer class that keeps one velocity per parameter array across calls. It tests the velocity update, state handling between steps, input validation, and returning new arrays without mutating the caller's data.

Implement SGD with classical (heavy-ball) momentum in NumPy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `SGDMomentum.step(params, grads)`, which takes equal-length lists of NumPy arrays and returns a new list of updated parameter arrays. For each array `i`: `v_i = momentum * v_i + g_i`, then `p_i = p_i - lr * v_i`. Velocities start at zero and persist across calls. The constructor is `SGDMomentum(lr=0.01, momentum=0.9)`. The class must also meet these requirements: - Store velocities as a list of float arrays in `self.velocities` (one per parameter, same shape). - Increment `self.t` by 1 on every `step`. - Do not mutate the input `params` or `grads` arrays. Output arrays keep their input shapes. - Different list lengths or a param/grad shape mismatch raises `ValueError`. Example: ```python opt = SGDMomentum(lr=0.1, momentum=0.9) x = opt.step([np.array([1.0])], [np.array([2.0])]) # v=[2.0], x=[0.8] x = opt.step(x, [np.array([1.6])]) # v=[3.4], x=[0.46] opt.t # 2 ``` ```hint Where the velocity comes from On the first call there is no velocity yet. Decide when to create it and what it must look like, then trace the two example calls by hand before writing the loop. ``` ### Constraints & Assumptions - `params` and `grads` are lists of NumPy arrays of any shape, one gradient per parameter array. - The same optimizer instance is called repeatedly on the same list of parameter shapes. ### What a Strong Answer Covers - The heavy-ball update in the given order: the velocity first, then the parameter step scaled by the learning rate. - Velocity state created at zero on the first call, one float array per parameter, and kept between calls. - New output arrays every step, with the caller's `params` and `grads` left unchanged and shapes preserved. - `ValueError` for mismatched list lengths or shapes, and `self.t` incremented once per call. ### Follow-up Questions - If the gradient stays constant, what step size does the update approach, and what does that mean for choosing `lr` when you raise `momentum`? - How would you change `step` to implement Nesterov momentum? - Why can a momentum close to 1 make training oscillate even when plain SGD at the same learning rate converges?

Overview: Implement stochastic gradient descent with classical heavy-ball momentum as a small NumPy optimizer class that keeps one velocity per parameter array across calls. It tests the velocity update, state handling between steps, input validation, and returning new arrays without mutating the caller's data.

General logo
General
Nov 25, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement SGDMomentum.step(params, grads), which takes equal-length lists of NumPy arrays and returns a new list of updated parameter arrays. For each array i: v_i = momentum * v_i + g_i, then p_i = p_i - lr * v_i. Velocities start at zero and persist across calls. The constructor is SGDMomentum(lr=0.01, momentum=0.9).

The class must also meet these requirements:

  • Store velocities as a list of float arrays in self.velocities (one per parameter, same shape).
  • Increment self.t by 1 on every step .
  • Do not mutate the input params or grads arrays. Output arrays keep their input shapes.
  • Different list lengths or a param/grad shape mismatch raises ValueError .

Example:

opt = SGDMomentum(lr=0.1, momentum=0.9)
x = opt.step([np.array([1.0])], [np.array([2.0])])  # v=[2.0], x=[0.8]
x = opt.step(x, [np.array([1.6])])                 # v=[3.4], x=[0.46]
opt.t  # 2

Constraints & Assumptions

  • params and grads are lists of NumPy arrays of any shape, one gradient per parameter array.
  • The same optimizer instance is called repeatedly on the same list of parameter shapes.

What a Strong Answer Covers Guidance

  • The heavy-ball update in the given order: the velocity first, then the parameter step scaled by the learning rate.
  • Velocity state created at zero on the first call, one float array per parameter, and kept between calls.
  • New output arrays every step, with the caller's params and grads left unchanged and shapes preserved.
  • ValueError for mismatched list lengths or shapes, and self.t incremented once per call.

Follow-up Questions Guidance

  • If the gradient stays constant, what step size does the update approach, and what does that mean for choosing lr when you raise momentum ?
  • How would you change step to implement Nesterov momentum?
  • Why can a momentum close to 1 make training oscillate even when plain SGD at the same learning rate converges?