BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Optimizers1 of 18 in topic

240. 为梯度下降添加 momentum

EasyOptimizers

普通的梯度下降在狭窄的谷底会呈之字形(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)
Play with it

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.

051015-6-4-20246xlossStart
step
0
x
4
loss
8
slope
4
distance to minimum
4
loss = 1 x² / 2. Tap the curve to move the start.

示例 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 控制每一步中保留多少旧速度。

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. 普通梯度下降在两步后会得到 0.81,因此 momentum 移动得更快。

v = beta v + grad(w); w = w - lr v; repeat for the given number of steps. 更新必须使用 v,而不是原始梯度。Momentum SGD 仍被用于训练 ResNets 等视觉模型。
主题
Optimizers
相似题目
  • 按全局范数裁剪梯度列表Easy
  • 执行 Nesterov momentum 步进Easy
  • 计算 Noam warmup 学习率Easy
  • 计算带有偏差修正的指数加权平均Easy
所有 Optimizers 道题目
反馈
240 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def momentum_steps(grad_fn, w0, lr, beta, steps):
# your code here
pass
​
momentum_steps(_g, [5.0, 1.0], 0.02, 0.9, 5)

此用例使用生成数据,因此按原样运行。按 + 添加你自己的用例。

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS