46. 使用 Armijo 回溯线性搜索选择步长
固定的学习率可能会导致过冲。回溯法从一个大步长开始,并不断将其减半,直到 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$。
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 和其他经典优化器中。