240. 为梯度下降添加 momentum
普通的梯度下降在狭窄的谷底会呈之字形(zig-zags)移动。Momentum 通过维护一个运行速度,使得一致方向上的步进能够累积速度。
编写 momentum_steps(grad_fn, w0, lr, beta, steps)。从 v = 0 开始并重复以下步骤:
v = beta * v + grad_fn(w)
w = w - lr * v
返回作为数组的最终 w。
def momentum_steps(grad_fn, w0, lr, beta, steps)Gradient descent with and without momentum
Loss = a x² / 2. Step through it. With momentum the ball keeps speed from earlier steps, so it gets there faster but can overshoot.
- step
- 0
- x
- 4
- loss
- 8
- slope
- 4
- distance to minimum
- 4
示例 1
输入: momentum_steps(lambda w: 2 * w, [1.0], 0.1, 0.9, 2)
输出: [0.46]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
The velocity is a running sum of past gradients that decays by beta each step, and the weights move along the velocity instead of the raw gradient.
提示 2
Start w as a float array copy of w0 and v as zeros, then repeat steps times: update v with the new gradient, then update w.
提示 3
Order matters: compute v = beta * v + grad_fn(w) first and then w = w - lr * v using the new v.
常见错误
- 错误的版本计算了 v 但从未在更新中使用它。
理解思路
Momentum 让梯度下降的行为就像一个从山上滚下的球。你不再仅仅根据原始梯度进行步进,而是维护一个记录了过去梯度的速度,从而使稳定的方向加速,并抵消来回的之字形运动。beta 控制每一步中保留多少旧速度。
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. 普通梯度下降在两步后会得到 0.81,因此 momentum 移动得更快。
v = beta v + grad(w); w = w - lr v; repeat for the given number of steps. 更新必须使用 v,而不是原始梯度。Momentum SGD 仍被用于训练 ResNets 等视觉模型。