Choose a step size with Armijo backtracking line search
A fixed learning rate can overshoot. Backtracking starts with a big step and halves it until the loss drops enough.
Write backtracking_step(f, grad, x, t0=1.0, beta=0.5, c=1e-4, max_iter=50). g = grad(x). Starting from t = t0, while f(x - t g) > f(x) - c t ||g||^2 and fewer than max_iter shrinks have happened, set t = beta t. Return (t, x - t g).
def backtracking_step(f, grad, x, t0=1.0, beta=0.5, c=1e-4, max_iter=50)Example
f(x) = x squared at x = [1] with t0 = 1 returns t = 0.5 and x = [0].
Understand the idea
A fixed learning rate can jump past the minimum. Backtracking line search starts with a big step and keeps halving it until the loss goes down by enough. 'Enough' is the Armijo condition: the drop must be at least a small fraction c of what the gradient predicts, 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, which is above 1 - 0.0008, so shrink. t = 1: new x = -1, f = 1, still above 0.9996, shrink. t = 0.5: new x = 0, f = 0, below 0.9998, accept. Return t = 0.5 and x = [0]. Rule: compute g once; while f(x - t g) > f(x) - c * t * ||g||^2 and fewer than max_iter shrinks have happened, set t = beta * t; return (t, x - t g). Line searches like this are used inside L-BFGS and other classic optimizers.