Gradient descent and line search
Derive gradient descent as minimization of a local quadratic model and study step selection precisely: fixed steps, exact search, Armijo backtracking and Wolfe conditions. Spectral analysis on quadratics explains zigzagging, the stability limit η < 2/L and the role of conditioning.
After this lesson you can
- Derive gradient descent as the minimizer of the quadratic upper bound for an L-smooth function.
- Analyze GD on a quadratic by decomposing error into eigendirections with contraction factor |1 − ηλᵢ|.
- Prove fixed-step GD diverges for η > 2/L on a quadratic and obtain the optimal step 2/(μ + L).
- Implement Armijo backtracking and a line search satisfying the strong Wolfe conditions.
- Diagnose zigzagging, slowness and divergence from loss and gradient-norm curves.
Before you start
Motivation: the simplest algorithm training almost everything
Almost everything you will train in this course, from logistic regression to a transformer, is optimized using a variant of the same recipe: calculate the gradient, step in the opposite direction, repeat. Gradient descent (GD) fits in one line,
yet that line hides three questions separating an algorithm that works from one that does not:
- Why that direction? The gradient is a descent direction, but not the only one, or always the best.
- How far to move? Number is everything. Too small and the algorithm crawls; too large and loss explodes. The right value depends on curvature, invisible in the gradient.
- When to stop and what to do when things go wrong? A loss curve is a diagnostic instrument: it distinguishes an excessive step from a narrow valley or gradient error.
This lesson answers all three with specialist precision. First derive GD as minimizer of a local model, explaining as inverse curvature. Then solve the quadratic dynamics exactly, decomposing error into eigendirections shrinking at their own rates; this yields stability limit , optimal step and rate , numbers to remember. Finally study automatic step selection with line search: exact, Armijo backtracking and Wolfe conditions, needed for damped Newton and quasi-Newton methods in lessons 13 and 14.
This lesson uses what you already have: the first-order condition (at a minimum, ), -smoothness as an upper curvature bound, strong convexity as a lower bound, and the condition number summarizing both. The next lesson, convergence analysis of first-order methods, turns what quadratics show here into theorems for general convex functions.
Descent directions
Before choosing how far to move, choose where. Given point and direction , everything that happens along that direction fits into a one-variable function, the slice with . Its derivative at zero is the directional derivative , and everything depends on its sign.
Proof
With , the derivative definition says . A quotient with negative limit is negative for sufficiently small , i.e. . Conversely, if near , the quotient is negative and its limit cannot be positive.
∎The theorem guarantees descent only near zero: how far extends is precisely the line-search question. The boundary case is ambiguous (it may rise or fall), so the definition’s strict inequality supplies guarantees.
Which directions satisfy the condition? An entire half-space: all forming an acute angle with . Two families recur:
- Any with symmetric positive definite . Indeed if . With we get the gradient; with (when the Hessian is positive definite), Newton’s method; with diagonal , adaptive methods of lessons 20 and 21; with BFGS’s approximation, quasi-Newton methods of lesson 14. Almost all unconstrained optimization algorithms have this form, changing .
- Appropriately signed coordinate directions, , used by coordinate descent (lesson 15).
Which direction decreases fastest? Among unit vectors, directional derivative is smallest when opposes the gradient, by Cauchy-Schwarz: , with equality iff is a positive multiple of . This is the steepest direction (here descent) in Euclidean norm. Under another norm the steepest direction differs (the gradient sign under , for example): this is steepest descent in a general norm in lesson 26. “Steepest” describes the derivative at one point; it says nothing about two steps later, the subject of the following sections.
GD as minimization of a local model
The method’s fixed points, , are exactly stationary points . This connects to the lesson-1 first-order condition: GD seeks points satisfying necessary optimality, and in the convex case that is the global optimum.
A more fruitful interpretation than “going downhill”: GD minimizes a model. Around , resembles its linear approximation, but a linear function has no minimum, so add a term penalizing distance:
This is strictly convex quadratic in , with gradient . It vanishes at : the GD step minimizes . The quadratic term is assumed curvature: the model says “I believe curves like in every direction”. Larger assumes less curvature and takes a bolder step. Newton does the same with true curvature ; GD replaces it by a multiple of the identity. This explains why GD ignores problem geometry and struggles when curvature differs greatly by direction.
When is the model reliable? If is -smooth, lesson 3’s quadratic upper bound says . When , the model’s penalty term exceeds the bound’s, so for every : the model is a global upper bound of touching at . Minimizing a touching upper bound guarantees descent, the idea of majorization-minimization:
Check the equality by substituting into : we get . This is a form of the descent lemma proved generally in lesson 8, explaining why is the “safe” step when is known. A third interpretation, used at the end of the next section: GD is explicit Euler with step for differential equation of gradient flow.
Three aspects of the figure deserve names. Zigzagging (the iterate crosses from one side of the valley to the other) occurs when the step is large relative to transverse curvature. Slowness in the valley is the reverse: the step that does not explode in the steep direction is tiny for the flat direction, so progress along the valley floor is slow. Divergence is the limit of that tradeoff. With a fixed step there is no way to have all three at once; the next section explains exactly why.
Exact dynamics on a quadratic
The quadratic is the laboratory where GD has a closed-form solution, and approximates any smooth function near a minimum. Let
with unique minimum and gradient . Subtracting from both sides of , the error follows a linear recurrence,
Now the spectral theorem enters: with orthogonal and . Write the error in the eigenvector basis, . Since is diagonal, coordinates do not mix:
This is gradient descent dynamics on a quadratic: independent scalar problems, one per eigendirection, where each error coordinate is multiplied every step by its contraction factor . The values of and error are
Notice the factor’s sign. If , it is positive and less than 1: the coordinate decreases without oscillation. If , it is negative with magnitude below 1: the coordinate decreases changing sign each step (zigzagging). If , magnitude exceeds 1 and the coordinate grows with alternating sign (divergence). Small eigenvalues have factors close to 1: slow modes.
The figure contains the lesson’s most important idea: largest curvature limits the step; smallest curvature limits speed. To keep the mode from exploding we need ; but that step contracts the mode only by factor , close to 1 if the ratio is small. The next result makes this precise: , and are exactly strong convexity, smoothness and condition number of .
Proof
(1) Factor is affine decreasing in , so its absolute value is maximized at a spectral endpoint: . The bound follows from , with equality if all error lies in an extreme eigenvector.
(2) is equivalent to for every , meaning ; since the tightest condition is . For , factor . If , the factor for eigenvalue is and .
(3) On , decreases and increases with ; their maximum is minimized where they cross, , i.e. , with value .
∎At the optimal step, extreme modes contract by the same factor with opposite signs: low curvature decreases without oscillating; high curvature changes sign each time. It balances the slow mode and the exploding mode.
Intermediate eigenvalues change nothing: the envelope depends only on extremes. To determine the cost of poor conditioning, calculate steps reducing error by factor . Since , , so
Cost is linear in . With , the prudent choice when only is known, the factor is and nearly steps are needed: twice as many.
Two qualifications to avoid over-extrapolation. First, if is only semidefinite (, as in least squares with dependent columns) and lies in the image of (always true in least squares; otherwise is unbounded below), modes with never move: with , GD converges, but only to the point in the minimizer set sharing ‘s component in the nullspace of . Second, for a nonquadratic function varies with position: limit is local and may be far smaller away from the minimum than near it: for Beale, at versus at the minimum; for Rosenbrock, at versus at the minimum (and there). The trajectory figure reads at the start and last iterate. An chosen only at the start may diverge ten iterations later, and one working far away may fail near the minimum: for Rosenbrock, , barely above at the minimum, does not explode, but after 60,000 iterations still jumps between two points near , a period-2 cycle with , never reaching the minimum.
Limit also has a classical interpretation: the stability edge of explicit Euler for . Gradient flow decays as for any , but Euler with step mimics it only if ; GD is flow with a time step too large for the fastest modes.
Line search: choosing on the fly
Choosing a fixed step requires knowing (or and for the optimum) and assumes curvature is the same everywhere. The alternative is a line search: each iteration, with direction fixed, choose by examining slice . Each trial costs an evaluation of (perhaps ), so search should be cheap: seek a good, guaranteed , not the best.
Exact search and orthogonal zigzagging
The natural idea is to minimize the slice.
Proof
At an interior minimum of , , and by the chain rule . With this gives orthogonality. On the quadratic, with and , is a parabola minimized at .
∎A trajectory with orthogonal consecutive gradients turns exactly 90° at each step. This causes the trajectory figure’s zigzag with “Exact”. It is not an implementation defect: it means reaching the bottom of the slice. Curiously that zigzag is the calculable worst case:
That factor cannot be improved in the worst case, as the next theorem states, worth remembering as GD’s exact-search benchmark bound.
Proof
Let be the gradient at (with ). Then , and substituting in the slice parabola,
Let , a probability distribution on eigenvalues. The denominator divided by is , and we must show (Kantorovich inequality). For , is equivalent to ; taking expectations, . By arithmetic-geometric mean, , and squaring yields the inequality. Therefore the ratio is at most .
∎Compare fixed-step theorem: exact search achieves the same contraction per step as optimal step (with it each error coordinate is multiplied by a factor of magnitude , and , quadratic in error, by ), without knowing and . This is line search’s great virtue: it adapts step to problem. Its drawback: for a quadratic the formula is free, but for a general function finding the minimum of requires many evaluations for small benefit (zigzag remains). It is used on quadratics (conjugate gradient in numerical analysis, which corrects zigzag by choosing conjugate directions) and almost never otherwise.
Armijo backtracking: decrease enough
For a general function a step decreasing sufficiently suffices. “Sufficiently” cannot mean “a little”: a sequence of steps decreasing by ever-smaller amounts can converge to a nonstationary point. The correct condition compares actual decrease with the tangent’s prediction.
The condition requires to lie below the line starting at with slope : a fraction of the tangent-predicted decrease. In practice is tiny () and . Backtracking only shrinks the step, so must be large enough not to fall short (1 is usual for well-scaled directions).
Proof
By the quadratic upper bound, . It suffices that , i.e. (divide by and recall ), , which is . Backtracking tries . If it accepts . Otherwise it stops at the first with , which exists as ; the previous step was rejected, so and . Trial count is the smallest with . The last inequality is Armijo with and .
∎Three interpretations. It always terminates, without knowing . The accepted step is never below , which with and small is : backtracking guarantees at least what safe step guarantees, while exploiting low-curvature areas where it accepts larger steps. It is an automatic local curvature estimator, the complement requested in lesson 3 for sampled estimates, useful only to start. And a decrease is guaranteed of at least , which, if is bounded below, suffices to prove (lesson 8).
Cost is the number of trials, each one evaluation without gradient. With a good (e.g. twice the last accepted step, allowing it to grow), usually 1 or 2 per iteration.
Wolfe conditions: do not fall short
Armijo has a gap: any sufficiently small satisfies it (as the theorem shows), so alone it does not prevent tiny steps. Backtracking avoids this by starting large, but other search algorithms or too small an do not. A second condition must force progress: the slope of must have flattened.
Since , weak Wolfe says the slope at has risen from at least to , less negative: the function no longer decreases as strongly, so moving further is less rewarding. Strong Wolfe also requires the slope not be very positive, meaning the valley has not been overshot: lies near a stationary point of . As exact search is recovered.
The curvature condition raises a question: are there always steps satisfying both conditions? Yes, under minimal assumptions.
Proof
Line tends to and is bounded below, so they intersect. Since (because and ), lies below immediately right of ; let be the first point with . Then on . By the mean value theorem there is with , and since , . At Armijo holds strictly (since ), and gives weak curvature. Also strictly, so strong curvature holds too. By continuity of and , all three inequalities hold in a neighborhood of .
∎The proof says where to look: is where ‘s slope equals the Armijo line’s slope. Why does an algorithm want curvature? For GD it is not essential, so Armijo backtracking suffices. For quasi-Newton methods it is: BFGS updates a Hessian approximation with pair , , and the update preserves positive definiteness only if (the secant equation requires it with ). With and weak curvature,
Wolfe conditions guarantee by construction the curvature condition needed by BFGS (lesson 14), so quasi-Newton line searches use Wolfe with and (conjugate gradient uses , closer to exact search).
How is a strong Wolfe step found? With Nocedal and Wright’s bracketing and zoom algorithm (algorithms 3.5 and 3.6). Bracketing tries until an interval containing an acceptable step is found: either Armijo is violated (or has stopped decreasing), or the slope is positive. Zoom reduces this interval, maintaining the invariant “ satisfies Armijo and has the smallest value so far; slope at points toward ”, testing an interior point (cubic interpolation safeguarded by bisection) until curvature holds. Each trial costs an evaluation of and ; in machine learning the backpropagated gradient costs a small multiple of (the cheap gradient principle), so it is not prohibitive but costs more than Armijo.
Stopping criteria and diagnostics
When does the loop stop? A decent stopping criterion combines several signals, since each can mislead alone:
- Gradient norm: . This is the optimality condition, but depends on units of and : multiplying by multiplies its gradient by . Scale it (by the initial gradient or ).
- Stalled : . Misleading in flat valleys, where decreases slowly without being close to the minimum.
- Small step: . A tiny always satisfies it.
- Budget: maximum iterations or evaluations so the program terminates.
In the strongly convex case, gradient norm is a quantitative certificate of proximity: if is -strongly convex, and . The second follows by minimizing lower bound over , whose minimum cannot exceed . The first follows from . With small the certificate is weak: gradient guarantees only .
Loss and gradient-norm curves (as in the trajectory figure) help diagnose the algorithm. With moderate and a reasonable step, on a log scale the curve of is a line of slope (as quadratic theory predicts, asymptotically valid near any nondegenerate minimum).
| What you see | Usual cause | What to do |
|---|---|---|
| Descending line on log scale | linear convergence with rate ; flatter means greater | estimate from slope; precondition or use momentum |
| Fast initial fall then nearly horizontal, with barely decreasing | narrow valley: low-curvature mode dominates | raise if safe; change method |
| grows geometrically and parameters alternate signs | in highest-curvature direction | lower below ; use line search |
| rises and falls with growing amplitude | near or above local , or growing curvature | lower ; clip the gradient |
| nearly constant from the start | tiny , or incorrectly calculated gradient | try larger ; check the gradient with finite differences |
| stalls and goes to zero at a bad point | local minimum or saddle (nonconvex) | change starting point; analyze the Hessian |
This is first contact with a discipline developed in the deep-learning module (learning curve patterns) and learning-rate schedules replacing line search when is stochastic.
Implementation from scratch
Build four step rules and compare actual cost: evaluations of and , not iterations. A test bench with counters and rules as functions receiving problem, point, value and gradient, returning .
import numpy as np
class Problema:
"""Envuelve f y su gradiente y cuenta cuántas veces se evalúa cada uno."""
def __init__(self, f, grad):
self._f, self._grad = f, grad
self.nf = self.ng = 0
def f(self, x):
self.nf += 1
return self._f(x)
def grad(self, x):
self.ng += 1
return self._grad(x)
def reiniciar(self):
self.nf = self.ng = 0
def descenso(prob, x0, busqueda, tol=1e-6, max_iter=50000):
"""GD con una regla de paso: busqueda(prob, x, fx, g) -> alfa. Devuelve (x, k, convergió, historial)."""
x = np.array(x0, dtype=float)
fx, g = prob.f(x), prob.grad(x)
historial = [(prob.nf + prob.ng, np.linalg.norm(g))]
for k in range(max_iter):
if np.linalg.norm(g) <= tol:
return x, k, True, historial
x = x - busqueda(prob, x, fx, g) * g
fx, g = prob.f(x), prob.grad(x)
historial.append((prob.nf + prob.ng, np.linalg.norm(g)))
return x, max_iter, False, historial
def paso_fijo(eta):
return lambda prob, x, fx, g: eta
def exacta_cuadratica(A):
"""Búsqueda exacta en f = x'Ax/2 - b'x: alfa = g'g / g'Ag."""
return lambda prob, x, fx, g: (g @ g) / (g @ (A @ g))
def armijo(alfa0=1.0, c1=1e-4, beta=0.5, calido=False):
"""Retroceso de Armijo. Con calido=True se empieza en el doble del último paso, con tope alfa0."""
estado = {"alfa": alfa0}
def busqueda(prob, x, fx, g):
alfa = min(2 * estado["alfa"], alfa0) if calido else alfa0
pendiente = -(g @ g) # phi'(0) para d = -g
while prob.f(x - alfa * g) > fx + c1 * alfa * pendiente:
alfa *= beta
estado["alfa"] = alfa
return alfa
return busqueda
def interp_cubica(a0, f0, d0, a1, f1, d1):
"""Mínimo del interpolante cúbico de Hermite por (a0, f0, d0) y (a1, f1, d1); None si no existe."""
d1c = d0 + d1 - 3 * (f0 - f1) / (a0 - a1)
rad = d1c * d1c - d0 * d1
if rad < 0:
return None
d2 = np.sign(a1 - a0) * np.sqrt(rad)
return a1 - (a1 - a0) * (d1 + d2 - d1c) / (d1 - d0 + 2 * d2)
def wolfe_ls(phi, dphi, f0, d0, a1, c1, c2, max_eval=30):
"""Búsqueda de Wolfe fuerte: acotación y zoom (Nocedal y Wright, algoritmos 3.5 y 3.6)."""
def zoom(lo, flo, dlo, hi, fhi, dhi):
for _ in range(max_eval):
a = interp_cubica(lo, flo, dlo, hi, fhi, dhi)
ancho = abs(hi - lo)
if a is None or not (min(lo, hi) + 0.1 * ancho <= a <= max(lo, hi) - 0.1 * ancho):
a = 0.5 * (lo + hi) # protección: bisección
fa, da = phi(a), dphi(a)
if fa > f0 + c1 * a * d0 or fa >= flo: # Armijo violada: el intervalo se acorta por la derecha
hi, fhi, dhi = a, fa, da
else:
if abs(da) <= -c2 * d0: # curvatura fuerte: hecho
return a
if da * (hi - lo) >= 0:
hi, fhi, dhi = lo, flo, dlo
lo, flo, dlo = a, fa, da
return lo
previo, fprevio, dprevio = 0.0, f0, d0
a = a1
for i in range(max_eval):
fa, da = phi(a), dphi(a)
if fa > f0 + c1 * a * d0 or (i > 0 and fa >= fprevio):
return zoom(previo, fprevio, dprevio, a, fa, da)
if abs(da) <= -c2 * d0:
return a
if da >= 0:
return zoom(a, fa, da, previo, fprevio, dprevio)
previo, fprevio, dprevio = a, fa, da
a *= 2 # acotación: duplicar
return previo
def wolfe_fuerte(alfa0=1.0, c1=1e-4, c2=0.9, calido=False):
estado = {"alfa": alfa0}
def busqueda(prob, x, fx, g):
phi = lambda a: prob.f(x - a * g)
dphi = lambda a: -(g @ prob.grad(x - a * g))
inicial = min(2 * estado["alfa"], alfa0) if calido else alfa0
estado["alfa"] = wolfe_ls(phi, dphi, fx, -(g @ g), inicial, c1, c2)
return estado["alfa"]
return busqueda
# comprobación: el paso devuelto cumple de verdad las condiciones, en una parábola cuyo mínimo está en alfa = 125
phi = lambda a: (1 - 0.008 * a) ** 2
dphi = lambda a: -0.016 * (1 - 0.008 * a)
a = wolfe_ls(phi, dphi, 1.0, -0.016, 1.0, 1e-4, 0.1)
print(f"alfa = {a:.2f}; Armijo: {phi(a) <= 1 - 1e-4 * a * 0.016}; |phi'(a)| = {abs(dphi(a)):.2e} <= {0.1 * 0.016:.2e}: {abs(dphi(a)) <= 0.1 * 0.016}")Two implementation details. In armijo the while loop always terminates by the preceding theorem provided is the gradient of and is a descent direction: with a miscalculated gradient the condition might never hold and the loop would be infinite (a while iteration limit is good practice). In wolfe_ls bracketing doubles the step; if is bounded below it terminates soon, and both phases have an evaluation budget to prevent loops.
First test bench: a quadratic with (known exact answers) and Rosenbrock’s curved-valley landscape.
import matplotlib.pyplot as plt
A = np.diag([1.0, 100.0])
cuadratica = Problema(lambda x: 0.5 * x @ A @ x, lambda x: A @ x)
rosenbrock = Problema(
lambda p: (1 - p[0]) ** 2 + 100 * (p[1] - p[0] ** 2) ** 2,
lambda p: np.array([-2 * (1 - p[0]) - 400 * p[0] * (p[1] - p[0] ** 2), 200 * (p[1] - p[0] ** 2)]),
)
def comparar(nombre, prob, x0, reglas, tol, max_iter=30000):
print(nombre)
print(f" {'regla':20s} {'iter':>6s} {'eval f':>7s} {'eval grad':>10s} {'total':>7s}")
historiales = {}
for etiqueta, regla in reglas.items():
prob.reiniciar()
x, k, ok, hist = descenso(prob, x0, regla, tol, max_iter)
historiales[etiqueta] = hist
marca = "" if ok else " (sin converger)"
print(f" {etiqueta:20s} {k:6d} {prob.nf:7d} {prob.ng:10d} {prob.nf + prob.ng:7d}{marca}")
return historiales
comparar("Cuadrática diag(1, 100), x0 = (100, 1), |g| <= 1e-6", cuadratica, [100, 1], {
"paso 1/L": paso_fijo(0.01),
"paso óptimo 2/(mu+L)": paso_fijo(2 / 101),
"búsqueda exacta": exacta_cuadratica(A),
"Armijo, alfa0 = 1": armijo(1.0),
"Armijo cálido": armijo(1.0, calido=True),
"Wolfe cálido": wolfe_fuerte(1.0, calido=True),
}, 1e-6)
print()
hist = comparar("Rosenbrock, x0 = (-1.2, 1), |g| <= 1e-3", rosenbrock, [-1.2, 1.0], {
"paso fijo 0.001": paso_fijo(1e-3),
"Armijo, alfa0 = 1": armijo(1.0),
"Armijo cálido": armijo(1.0, calido=True),
"Wolfe cálido": wolfe_fuerte(1.0, calido=True),
}, 1e-3)
for etiqueta, h in hist.items():
h = np.array(h)
plt.semilogy(h[:, 0], h[:, 1], label=etiqueta, lw=1.4)
plt.xlabel("evaluaciones acumuladas de f y de ∇f"); plt.ylabel("‖∇f‖"); plt.legend(); plt.show()The quadratic table confirms the theory line by line. Optimal step and exact search need the same number of iterations (939 for , with the same per-step contraction), step nearly twice as many (1833), and Armijo slightly fewer than both (839). The last deserves explanation: starting point is precisely Akaike’s zigzag, exact search’s worst case. Backtracking from 1 can accept only powers of , accepting or ; the latter is above , accepted (in 349 of 839 iterations) when error’s fast-mode component is so small that still decreases. That step amplifies the fast mode by but moves twice as far in the slow one, and subsequent steps recontract the fast mode by . No fixed step can do this: an adaptive rule can temporarily enter the unstable zone because it monitors . But consider cost: with , Armijo needs about 7.6 evaluations of per iteration (six or seven backtracks from 1), and warm starting lowers it to about 3. A search that looks more efficient in iterations can cost nearly four times as many evaluations (7204 versus 1880). On Rosenbrock iteration count misleads the other way. Fixed step (which must be known in advance: already fails to converge) is cheapest per iteration, with one evaluation each of and , needing 14,789; Armijo with needs under half as many iterations (5231), yet over twice as many total evaluations (62,352 versus 29,580), because each iteration evaluates about 11 times backtracking from 1 to a step on the order of . Warm starting lowers the total to 26,354, slightly better than fixed step, and Wolfe takes 38,510. The plot of against cumulative evaluations is the honest comparison, and no rule is drastically better: in this valley the limiting factor is , not step rule.
Second bench: regularized logistic regression with 200 examples and 10 features on very different scales, the problem from lesson 3.
rng = np.random.default_rng(0)
n, d = 200, 10
X = rng.normal(size=(n, d)) * np.linspace(0.3, 3, d) # características con escalas distintas
w_verdadero = rng.normal(size=d)
y = np.where(X @ w_verdadero + 0.5 * rng.normal(size=n) > 0, 1.0, -1.0)
lam = 1e-3
def f_log(w):
return np.mean(np.logaddexp(0, -y * (X @ w))) + 0.5 * lam * w @ w
def g_log(w):
s = 0.5 * (1 - np.tanh(0.5 * y * (X @ w))) # sigmoide(-y x'w), estable
return -(X.T @ (y * s)) / n + lam * w
logistica = Problema(f_log, g_log)
L = np.linalg.eigvalsh(X.T @ X)[-1] / (4 * n) + lam # L = lambda_max(X'X)/(4n) + lam
print(f"L = {L:.3f}, mu >= lambda = {lam}, kappa <= {L / lam:.0f}")
comparar("Regresión logística, |g| <= 1e-6", logistica, np.zeros(d), {
"paso 1/L": paso_fijo(1 / L),
"Armijo, alfa0 = 1": armijo(1.0),
"Wolfe fuerte, alfa0 = 1": wolfe_fuerte(1.0),
}, 1e-6)This bench teaches something different. Step is safe but conservative: is the global worst case and actual curvature near the minimum is much smaller. Armijo cannot exploit it because it never exceeds (backtracking only shrinks): with it accepts steps no greater than 1, slightly more than twice , and needs 2933 iterations versus 6830 for . Wolfe does exploit it: when curvature fails because slope remains very negative, bracketing doubles the step until it holds, converging in 353 iterations. Each iteration costs more (calculating on each trial), but the total is much smaller: 3364 evaluations versus Armijo’s 8801 and ‘s 13,662. This is what Wolfe “does not fall short” means.
The library version
scipy.optimize.line_search implements strong Wolfe search (following Nocedal and Wright with interpolation). Use it as reference: on a battery of test functions and random points, check that our implementation and SciPy’s return steps satisfying the same conditions, and compare their evaluation counts.
from scipy.optimize import line_search, rosen, rosen_der
def himmelblau(p): return (p[0]**2 + p[1] - 11)**2 + (p[0] + p[1]**2 - 7)**2
def himmelblau_der(p):
a, b = p[0]**2 + p[1] - 11, p[0] + p[1]**2 - 7
return np.array([4 * p[0] * a + 2 * b, 2 * a + 4 * p[1] * b])
def beale(p):
x, y = p
return (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2
def beale_der(p):
x, y = p
a, b, c = 1.5 - x + x*y, 2.25 - x + x*y**2, 2.625 - x + x*y**3
return np.array([2*a*(y-1) + 2*b*(y**2-1) + 2*c*(y**3-1), 2*a*x + 4*b*x*y + 6*c*x*y**2])
Q = np.array([[3.0, 1.0], [1.0, 10.0]])
bateria = {
"Rosenbrock": (rosen, rosen_der, 2.0),
"Himmelblau": (himmelblau, himmelblau_der, 4.0),
"Beale": (beale, beale_der, 2.0),
"cuadrática": (lambda p: 0.5 * p @ Q @ p, lambda p: Q @ p, 3.0),
}
c1, c2 = 1e-4, 0.9
def wolfe_fuerte_cumplida(f, df, x, d, a):
phi0, dphi0 = f(x), df(x) @ d
return f(x + a * d) <= phi0 + c1 * a * dphi0 and abs(df(x + a * d) @ d) <= c2 * abs(dphi0)
rng = np.random.default_rng(1)
print(f"{'función':12s} {'propia: cumple, eval f':>26s} {'SciPy: cumple, eval f':>26s}")
for nombre, (f, df, escala) in bateria.items():
ok_p = ok_s = nf_p = nf_s = 0
for _ in range(30):
x = rng.uniform(-escala, escala, size=2)
d = -df(x)
prob = Problema(f, df)
a = wolfe_ls(lambda t: prob.f(x + t * d), lambda t: prob.grad(x + t * d) @ d, f(x), df(x) @ d, 1.0, c1, c2)
ok_p += wolfe_fuerte_cumplida(f, df, x, d, a)
nf_p += prob.nf
cuenta = [0]
def f_contada(z):
cuenta[0] += 1
return f(z)
res = line_search(f_contada, df, x, d, gfk=df(x), old_fval=f(x), c1=c1, c2=c2, amax=1e6)
ok_s += res[0] is not None and wolfe_fuerte_cumplida(f, df, x, d, res[0])
nf_s += cuenta[0]
print(f"{nombre:12s} {ok_p:>16d}/30, {nf_p / 30:5.1f} {ok_s:>16d}/30, {nf_s / 30:5.1f}")Both implementations satisfy conditions in all 120 cases with the same order of evaluations (on average 2.2–6.7 per search for ours and 2.2–8.5 for SciPy). Do not read that difference as our superiority: these are 30 random points per function, and SciPy has other safeguards (different interpolation, a maximum step, the ability to fail and return None). Remember that line search is interchangeable: a serious optimizer treats it as a black box.
To contrast with what follows, solve the same Rosenbrock problem with SciPy methods using Wolfe search on directions better than :
from scipy.optimize import minimize
for metodo in ("CG", "BFGS", "L-BFGS-B"):
r = minimize(rosen, [-1.2, 1.0], jac=rosen_der, method=metodo, options={"gtol": 1e-3})
print(f"{metodo:9s} iteraciones = {r.nit:3d} eval f = {r.nfev:3d} eval grad = {r.njev:3d} f = {r.fun:.2e}")Between 31 and 35 iterations and 38–76 evaluations of , versus 14,789 fixed-step iterations: over two orders of magnitude improvement from changing direction (conjugate gradient, quasi-Newton) and using Wolfe search. This is the rest of the module: even with the best possible step, GD is tied to the condition number, and later methods exist to escape it.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What condition does satisfy as an interior minimizer of ?
Step 1 of 4. What bound does -smoothness give for ?
wolfe_line_search(phi, dphi, c1=1e-4, c2=0.9, alpha0=1.0, max_evals=40), returning a step alpha > 0 satisfying the strong Wolfe conditions for slice phi (derivative dphi), assuming dphi(0) < 0. Use Nocedal and Wright's bracketing-and-zoom strategy: double the step until bracketing an interval containing an acceptable step and reduce the interval (bisection or interpolation), keeping the best Armijo-satisfying step in lo. Each call to phi or dphi counts as an evaluation; do not exceed max_evals.import numpy as np
def wolfe_line_search(phi, dphi, c1=1e-4, c2=0.9, alpha0=1.0, max_evals=40):
"""Devuelve alpha que cumple Armijo y |phi'(alpha)| <= c2 |phi'(0)|."""
phi0, dphi0 = phi(0.0), dphi(0.0)
# tu código: fase de acotación (duplicar alpha) y fase de zoom
return alpha0Summary
- A descent direction satisfies and decreases for small . is steepest in Euclidean norm; with covers Newton, quasi-Newton and adaptive methods.
- GD minimizes . With this model majorizes and guarantees .
- On a quadratic, . Convergence from every starting point iff ; optimal step is with rate , and steps suffice.
- Exact search gives orthogonal gradients (90° zigzag) and contraction in , without knowing or ; for general functions its cost is not worthwhile.
- Armijo, , with backtracking always terminates and accepts without knowing , but only shrinks the step. Wolfe adds curvature (, or its absolute value) to avoid falling short; such a step always exists and guarantees in BFGS.
- Always compare evaluations, scale stopping criteria and read loss curves: a line on a log scale means linear convergence; growing oscillation means .