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

46. 使用 Armijo 回溯线性搜索选择步长

MediumCalculus and gradients

固定的学习率可能会导致过冲。回溯法从一个大步长开始,并不断将其减半,直到 loss 有足够的下降。

编写 backtracking_step(f, grad, x, t0=1.0, beta=0.5, c=1e-4, max_iter=50)。g = grad(x)。从 t = t0 开始,当 f(x - t g) > f(x) - c t ||g||^2 且收缩次数少于 max_iter 时,设置 t = beta t。返回 (t, x - t g)。

函数def backtracking_step(f, grad, x, t0=1.0, beta=0.5, c=1e-4, max_iter=50)

示例 1

输入: f(x) = x squared at x = [1] with t0 = 1

输出: t = 0.5 and x = [0]

示例 2

输入: f = lambda v: float(v @ v), grad = lambda v: 2 * v, x = [1.0]

输出: (0.5, [0.0])

示例 3

输入: f = lambda v: (1 - v[0]) ** 2 + 100 * (v[1] - v[0] ** 2) ** 2, grad = lambda v: [-2 * (1 - v[0]) - 400 * v[0] * (v[1] - v[0] ** 2), 200 * (v[1] - v[0] ** 2)], x = [-1.0, 1.0]

输出: (0.5, [1.0, 1.0])

约束条件

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

Keep shrinking the step until the new loss is lower than the old loss by at least a small amount that grows with the step size.

提示 2

Compute g = grad(x), f(x) and g @ g once, start at t = t0, and while the Armijo test fails and you still have shrinks left, multiply t by beta.

提示 3

The loop condition is f(x - t*g) > fx - c*t*gg and it < max_iter, where it counts the shrinks, and you return the pair (t, x - t*g).

理解思路

固定的学习率可能会跳过最小值。回溯线性搜索从一个大步长开始,并不断将其减半,直到 loss 下降足够多。“足够多”是指满足 Armijo 条件:下降量必须至少达到梯度预测值的 $c$ 倍,即 $t * ||g||^2$。

Worked example

f(x) = x^2 at x = [1], t0 = 2, beta = 0.5, c = 1e-4. g = 2, ||g||^2 = 4, f(x) = 1. t = 2: new x = 1 - 4 = -3, f = 9, 高于 1 - 0.0008, 所以收缩。t = 1: new x = -1, f = 1, 仍高于 0.9996, 收缩。t = 0.5: new x = 0, f = 0, 低于 0.9998, 接受。返回 t = 0.5 和 x = [0]。

计算一次 g;当 f(x - t g) > f(x) - c * t * ||g||^2 且收缩次数少于 max_iter 时,设置 t = beta * t;返回 (t, x - t g)。此类线性搜索被用于 L-BFGS 和其他经典优化器中。
主题
Calculus and gradients
相似题目
  • 推导 softmax 加上 cross-entropy 的梯度Medium
  • 推导余弦相似度对单个向量的梯度Medium
  • 计算逻辑回归损失的 Hessian 矩阵Medium
  • 对均值和 log sigma 求高斯负对数似然的导数Medium
所有 Calculus and gradients 道题目
反馈
46 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def backtracking_step(f, grad, x, t0=1.0, beta=0.5, c=1e-4, max_iter=50):
# your code here
pass
​

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

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