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

242. 执行 Nesterov momentum 步进

EasyOptimizers

重要性 Nesterov momentum 是视觉训练中使用的每种 SGD optimizer 的可选方案。

Nesterov momentum 在 look-ahead point 处计算梯度。

编写 nesterov_step(w, v, grad_fn, lr, mu)。计算 g = grad_fn(w + mu * v),然后 v_new = mu * v - lr * g 且 w_new = w + v_new。返回 (w_new, v_new)。

函数def nesterov_step(w, v, grad_fn, lr, mu)
Play with it

Momentum against Nesterov on a stretched bowl

Nesterov takes the gradient at the look-ahead point w + μv, which damps the zig-zag across the steep direction.

-202-4-2024w1w2
step
0
w1
-4
w2
1.5
loss
30.5
00.250.50.7510246810steploss, share of start
loss = (1 w1² + 20 w2²) / 2, so one direction is 20 times steeper. Tap the map to pick a start.

示例 1

输入: w = [1], v = [0], grad_fn = lambda x: 2 * x, lr = 0.1, mu = 0.9

输出: w [0.8], v [-0.2]

示例 2

输入: w = [1.0, -2.0], v = [0.5, 0.5], grad_fn = lambda x: 2 * x, lr = 0.1, mu = 0.9

输出: ([1.16, -1.24], [0.16, 0.76])

示例 3

输入: w = [2.0], v = [-1.0], grad_fn = lambda x: 4 * x ** 3, lr = 0.01, mu = 0.5

输出: ([1.365], [-0.635])

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 3 tests to be accepted.
提示 1

与经典 momentum 唯一的区别在于计算梯度所在的位置。

提示 2

Look-ahead point: w + mu * v。

提示 3

先更新 v,再更新 w。

常见错误
  • 在 w 处计算梯度。
理解思路

普通 momentum 维护一个速度 v,并在每一步将其加到权重上。Nesterov momentum 更聪明:既然权重无论如何都要移动大约 mu * v 的距离,它就在那个 look-ahead point 处测量梯度,而不是在当前权重处。这使得它在趋向最小值时能更早地减速。

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.

g = grad_fn(w + mu * v); v_new = mu * v - lr * g; w_new = w + v_new; return both. 如果你在 w 处计算梯度,得到的就是普通 momentum。应用场景:用于训练 CNN 的 SGD with Nesterov momentum,以及 NAdam optimizer 背后的思想。
主题
Optimizers
相似题目
  • 为梯度下降添加 momentumEasy
  • 按全局范数裁剪梯度列表Easy
  • 计算 Noam warmup 学习率Easy
  • 计算带有偏差修正的指数加权平均Easy
所有 Optimizers 道题目
反馈
242 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def nesterov_step(w, v, grad_fn, lr, mu):
# your code here
pass
​

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

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