12 / 16 · Optimization
Unconstrained optimization
Finding the minimum of a smooth function, and how fast: optimality conditions, gradient descent rates and the condition number, Armijo line search, Newton's method and its quadratic convergence, and BFGS.
Convex sets and functions · Gradients, Jacobians and Hessians
On this page 8
Fit a logistic regression with an L2 penalty to 40 points with two features, the second ten times larger than the first (the Code section builds the data). The loss is
where are the points and their labels. In the language of the previous note, the penalty makes strongly convex with , and the bound makes it -smooth with .
Gradient descent with the safe step , started at , lowers the excess loss from to in 10 steps, to in 100 and to in 1,000. It needs 2,727 steps to reach . Every step decreases the loss, and nothing is wrong with the code. Newton’s method solves the same problem in 5 steps.
Why does gradient descent need thousands of steps for two unknowns, and what does it guarantee on a loss that is not a quadratic? The answers come from the constants and , and the cure from the curvature, which the gradient ignores.
Optimality conditions#
Before an algorithm, a test: what must hold at a minimizer, and what is enough to be sure of one? Write for a candidate and, for with continuous second derivatives, expand it to second order, as in the gradients note:
Each condition reads one term of the expansion:
| Condition | Statement | Reason |
|---|---|---|
| first-order, necessary | local minimum | otherwise lowers by |
| second-order, necessary | local minimum | otherwise some with lowers along |
| second-order, sufficient | and strict local minimum | the quadratic term is at least (Rayleigh quotient), and for small the term is below half of that |
| convex | global minimum | the tangent bound |
The gap between necessary and sufficient is real. and both have zero gradient and the Hessian at the origin, positive semidefinite but singular. The first has a minimum there and the second a saddle: along the quadratic term vanishes and the quartic decides. An algorithm that only drives the gradient to zero can stop at any critical point unless the function is convex.
Gradient descent on a smooth function#
Gradient descent moves against the gradient, , where and is the step. How much does one step gain? An -smooth function lies below the parabola of curvature that touches it at the current point, the upper bound of the previous note. Put into it, with :
This is the descent lemma, the many-variable form of the one-variable bound in the derivatives note. Every decreases while the gradient is nonzero, because then . The guaranteed decrease has derivative in , so it is largest at , where it equals :
Summed over steps, the decreases telescope, and the smallest of numbers is at most their average:
Without convexity this is all that holds: the smallest gradient among the first steps satisfies
The iterates approach a critical point at the rate in the gradient norm, with no promise about which kind. The gradient descent note of the machine learning course quotes the same three regimes this section proves.
Convex and smooth: the excess loss falls like 1/k#
Convexity bounds how far the loss is above its minimum in terms of the gradient and the distance to . Each step then trades that excess for a decrease of the squared distance. Assume a minimizer exists, write for the error of an iterate and take :
- The descent lemma.
- The tangent bound at towards , .
- Expanding the square, , gives back the previous line.
- The step itself, .
Summing over telescopes the right side to at most . The left side is a sum of excesses , each at least the last one, because the loss never increases. Hence
On the way, the chain shows , because its left side minus is non-negative: the iterates never move away from the minimizer. Merkulov (2024), lecture 9, proves the bound the same way.
For the opening problem, , so the bound is , at most after 1,000 steps. The run reaches . The bound is valid and pessimistic, because it uses neither the penalty nor the curvature near the minimum.
Strongly convex: a linear rate set by κ#
Strong convexity keeps the gradient large while the loss is far from its minimum, through the Polyak–Łojasiewicz inequality of the previous note. Put it into the descent lemma, after subtracting from both sides:
The second line replaces by the smaller .
Applying this times, with the condition number :
Since , the tangent bound of the convex at 0, the right side is at most . To shrink the excess loss by a factor it is enough that , that is, steps: the number of steps is linear in the condition number. For and that is 1,375 steps by the first bound, , and 1,382 by the second, . Each step costs one gradient, so on badly conditioned problems gradient descent is slow however cheap its steps are. The proof used only the Polyak–Łojasiewicz inequality, not convexity, so the linear rate holds for every smooth function that satisfies it (Merkulov, 2024, lecture 9; Karimi, Nutini and Schmidt, 2016, Theorem 1).
Why the condition number? Near the minimum is close to a quadratic with Hessian . In its eigenvector coordinates the level set has half-axes , in the ratio . The gradient is perpendicular to the level set, so it points at the minimum only when the level sets are round. On a quadratic, a step multiplies the error along an eigenvector with eigenvalue by . The safe step is limited by the steep direction, , and along the flat direction it then removes only a fraction of the error. Strang (2018) draws this as a zigzag down a narrow valley.
The exact analysis on a quadratic gives the best constant step , with the error factor per step: the same linear dependence on with a better constant. Momentum reduces it to , and no better dependence is possible for methods that move within the span of past gradients. Bubeck (2015), Theorem 3.15, builds an -smooth, -strongly convex function on the infinite-dimensional space on which every such method has .
For the opening problem, , and the bound promises after steps. The run needed 2,727. The global and are worst cases over the whole space. Near the minimum the Hessian has eigenvalues and , a local condition number of 110. With the step , the error along the flat eigenvector shrinks by per step, and the excess loss, quadratic in the error, by the square of that, . That predicts steps from to ; the run needs 2,727 because its early steps are faster, and its late steps shrink the excess by , as predicted.
Line search: the Armijo condition#
is rarely known, and is often far shorter than the steps the function allows. A line search chooses the step length at every iteration, along a search direction that points downhill, . The slope at the start promises a decrease of for a step ; the Armijo condition accepts the step if it achieves at least a fixed fraction of that:
Backtracking tries until the condition holds. Armijo (1966), Corollary 2, proposed exactly this halving with ; a much smaller , about , is typical in practice (Merkulov, 2024, lecture 2). The search always ends: by Taylor, , and since and , the actual decrease beats the required one for all small enough .
How long is the accepted step? For gradient descent, . The descent lemma gives the first inequality below, and the second is the Armijo test:
The second inequality holds whenever , that is, . Halving therefore stops at some : the first trial step below is more than half of it. Every accepted step lowers by at least , and the Polyak–Łojasiewicz argument above, with replaced by , gives , without knowing . On the opening problem, gradient descent with backtracking () needs 526 steps instead of 2,727, because it takes steps longer than wherever the local curvature allows.
A step can satisfy Armijo and still be too short to make progress. The Wolfe conditions add a curvature condition that rules out steps after which the slope has hardly changed:
with , typically (Merkulov, 2024, lecture 2). Quasi-Newton methods need it, as shown below.
Newton’s method#
Gradient descent uses a linear model of , and a linear model has no minimum, so it needs a step size. Newton’s method uses the quadratic model instead:
When , is a strictly convex quadratic, and its minimum is where its gradient vanishes. That gives a complete step, length and direction included:
The same step solves the linearized optimality condition : Newton’s method for minimization is Newton’s root-finding method applied to . A third reading explains why the condition number disappears. Gradient descent takes the steepest direction in the Euclidean norm. Measured in the norm of the local Hessian , the steepest direction becomes , the Newton direction, and in that norm the level sets near the minimum are round (Boyd and Vandenberghe, EE364a, lecture 9, the interpretation of the Newton step). To see it, substitute : the slope over is most negative for opposite to , by Cauchy–Schwarz, that is, for along . The quadratic model’s level sets are spheres in that norm.
The Newton direction is computed by solving a linear system, by a Cholesky factorization when the Hessian is positive definite, never by forming the inverse. On a quadratic the model is the function itself, and one step from any point lands on , whatever is. When is too large to factor , the iterative methods note minimizes the same quadratic by conjugate gradients, which need only products with .
Newton’s method is affine invariant. In coordinates with an invertible , the chain rule turns the Hessian into and the gradient into , and the Newton step in is exactly the Newton step in mapped back:
Rescaling or rotating the features, which changes and the speed of gradient descent, changes nothing for Newton. Logistic regression is fitted this way, as iteratively reweighted least squares.
Quadratic convergence#
The Newton step solves a linearized equation, so its error comes only from the change of the Hessian between and , which is proportional to the distance. Assume that on a ball around the Hessian satisfies and is -Lipschitz, , and that lies in that ball. Write and use . The difference is the integral of the Hessian along the segment from to , and is the integral of a constant:
Now take norms: , since the eigenvalues of are the reciprocals of those of , and the two Hessians in the integral are evaluated at points apart:
Once , the factor is below , so : the next iterate stays in the ball, the assumptions hold again, and the factor shrinks at every step. Taking logarithms, : the number of correct digits roughly doubles per step. This is quadratic convergence, against the linear convergence of gradient descent, which adds a fixed number of digits per step. Merkulov (2024), lecture 15, assumes the bound only at and finds that the error shrinks from any start with .
The function on has , and its minimum at . The Newton step is , so exactly: the error is squared at every step. This matches the bound in the limit: on a shrinking interval around 1, and , so , the exact constant. From :
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
Damping#
Far from the minimum the quadratic model can be a poor guide. In the example, from the full step lands at , outside the domain. Damped Newton keeps the Newton direction and chooses its length by backtracking with the Armijo condition, starting from . The Newton direction is a descent direction whenever the Hessian is positive definite, since .
From the direction is . The steps and leave the domain, and gives with , below by more than the Armijo threshold. From the full step is accepted at every iteration, , , , and the quadratic phase begins. The two phases are general. For a strongly convex with Lipschitz Hessian, Boyd and Vandenberghe (2004), Section 9.5.3, prove that while is above a threshold every damped step lowers by at least a fixed amount, and below it every step is a full step with quadratic convergence. Why the full step passes near the minimum is visible on a quadratic, where the model is exact: with , . Since , this meets the Armijo threshold exactly when , so damping costs nothing there.
Each step still forms the Hessian and solves a linear system: operations and memory, out of reach for in the millions.
Quasi-Newton methods: BFGS#
Can we keep Newton’s step without the Hessian? A quasi-Newton method uses , where approximates the inverse Hessian. It is built from gradients only and corrected after every step. The information available after a step is the pair
Along the step the true Hessian maps approximately to , as the slope of a secant does in one variable. The secant equation asks the new approximation to reproduce this exactly, . A symmetric rank-one correction can satisfy it but may lose positive definiteness, since it can subtract a rank-one term; the rank-two BFGS update (Broyden, Fletcher, Goldfarb and Shanno, 1970) keeps it (Merkulov, 2024, lecture 15). With :
The secant equation is a one-line check: , so the first term vanishes on , and . The update keeps positive definite exactly when . If and , put ; then . Both terms vanish only if and , but makes , so the sum is positive. If , no positive definite matrix can satisfy the secant equation, because would have to be non-positive. For a -strongly convex function, adding its lower parabolas at towards and at towards gives . In general the Wolfe curvature condition guarantees it: with , , because and .
Each BFGS step costs , a few matrix–vector products and outer products. For a strongly convex with Lipschitz Hessian, BFGS with backtracking converges from any start and, near the minimum, superlinearly: the ratio tends to 0, though not as fast as Newton’s square (Vandenberghe, 2022, the convergence result, stated there without proof). L-BFGS stores only the last few pairs , typically 5 to 20, and applies the update implicitly, at per step for pairs. It is the default solver of scikit-learn’s LogisticRegression (solver='lbfgs' in version 1.9.1) and a standard choice for smooth deterministic problems of moderate size.
Gradient descent against Newton#
Gradient descent against Newton’s method
The left panel is the setting of the gradient descent note without its luck: an elongated quadratic with and whose axes are not the coordinate axes. Even with the best step along the gradient, found by an exact line search, gradient descent zigzags, because each step ends where the new gradient is perpendicular to the old one: the step minimizes , and there. The start is the worst case for which Boyd and Vandenberghe give the iterates in closed form (lecture 9, the quadratic example: from , here with and the axes turned), and falls by the factor per step. A millionfold reduction takes 35 steps, 66 with the fixed step ; the guarantee promises 132. Newton’s method takes one step.
The right panel is the opening logistic problem, where no method is exact in one step. Newton needs 5 steps to bring to about , BFGS with Armijo backtracking 11 steps to reach , gradient descent with backtracking 526 and with the fixed step 2,727. Per step, Newton pays an solve, BFGS and gradient descent beyond the gradient itself; at the solve is free, and at it is impossible.
Where it breaks#
Newton’s method looks for a zero of the gradient and does not care which kind. Take the non-convex function of the previous note and start at , where and . The function decreases to the right, but with negative curvature the Newton step points left, uphill:
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
Pure Newton converges, quadratically, to the local maximum at : as a root finder for , the convergence proof above needs only bounded away from 0 near the root, not its sign. Gradient descent with step from the same point goes downhill to the local minimum at . Practical codes guard against this by adding a multiple of the identity to the Hessian until it is positive definite, or by trusting the quadratic model only within a region around the current point. BFGS avoids it by construction: its stays positive definite, so is always a descent direction, and the line search makes decrease at every step, which rules out climbing to a maximum.
The analysis has other limits. Every rate here assumes exact gradients; with minibatch gradients the noise changes the picture, as the stochastic optimizers note shows, and BFGS pairs built from noisy gradients become unreliable. Losses with kinks, such as the hinge or the L1 penalty, break the descent lemma and need subgradient or proximal methods.
What you should remember#
- At a local minimum and ; for convex , suffices.
- Descent lemma: with , each step lowers by at least .
- Convex: . Strongly convex: about steps.
- Armijo backtracking finds a step with guaranteed decrease without knowing .
- Newton solves : affine invariant, quadratic near a minimum, damped far from it.
- BFGS builds the inverse Hessian from gradient differences through .
Code#
Newton’s method on with and without damping, gradient descent and Newton on the elongated quadratic, four methods on the logistic loss of the opening with the guarantees checked, and Newton on a non-convex function. Exact digits can differ slightly across platforms and library versions.
import numpy as np
from scipy.optimize import minimize
# Newton's method on f(x) = x - log x, minimum at 1: x <- 2x - x^2, and the error is squared at every step
x = 0.5
for k in range(6):
print(k, f'{x - 1:.3e}', end=' | ')
x = 2 * x - x * x
print()
# 0 -5.000e-01 | 1 -2.500e-01 | 2 -6.250e-02 | 3 -3.906e-03 | 4 -1.526e-05 | 5 -2.328e-10
# from x = 3 the full step lands at -3, outside the domain; backtracking (Armijo, c = 1e-4) halves it twice
f = lambda x: x - np.log(x) if x > 0 else np.inf
x = 3.0
for k in range(7):
g, h = 1 - 1 / x, 1 / x**2
d, t = -g / h, 1.0
while f(x + t * d) > f(x) + 1e-4 * t * g * d:
t /= 2
print(k, round(x, 6), t, end=' | ')
x += t * d
print()
# 0 3.0 0.25 | 1 1.5 1.0 | 2 0.75 1.0 | 3 0.9375 1.0 | 4 0.996094 1.0 | 5 0.999985 1.0 | 6 1.0 1.0
# an elongated quadratic: eigenvalues mu = 1 and L = 10, axes turned by 30 degrees, minimum at 0
th = np.deg2rad(30); Rot = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
mu, L = 1.0, 10.0
A = Rot @ np.diag([mu, L]) @ Rot.T
q = lambda x: 0.5 * x @ A @ x
x0 = Rot @ np.array([2.0, 0.2])
def count(step):
x, k = x0.copy(), 0
while q(x) > 1e-6 * q(x0):
g = A @ x
x, k = x - step(g) * g, k + 1
return k
print(count(lambda g: 1 / L), count(lambda g: 2 / (L + mu)), count(lambda g: g @ g / (g @ A @ g)),
((L - mu) / (L + mu)) ** 2, np.abs(x0 - np.linalg.solve(A, A @ x0)).max(), np.ceil(np.log(1e6) / -np.log(1 - mu / L)))
# 66 35 35 0.6694214876033059 2.220446049250313e-16 132.0
# steps with 1/L, with 2/(L + mu) and with exact line search; the factor per step of exact line search;
# Newton lands on the minimum in one step; the steps the strongly convex guarantee asks for
# a logistic loss with an L2 penalty on 40 deterministic points; the second feature is ten times larger
n, lam = 40, 0.01
k_ = np.arange(1, n + 1)
X = np.column_stack([2 * ((k_ * 0.6180339887498949) % 1) - 1, 10 * (2 * ((k_ * 0.7548776662466927) % 1) - 1)])
noise = (k_ * 0.4142135623730951) % 1 - 0.5
y = np.where(X[:, 0] + 0.1 * X[:, 1] + noise > 0, 1.0, -1.0)
F = lambda w: np.mean(np.maximum(-y * (X @ w), 0) + np.log1p(np.exp(-np.abs(y * (X @ w))))) + lam / 2 * w @ w
G = lambda w: -X.T @ (y / (1 + np.exp(y * (X @ w)))) / n + lam * w
def Hess(w):
p = 1 / (1 + np.exp(-(X @ w)))
return (X.T * (p * (1 - p))) @ X / n + lam * np.eye(2)
Lb = np.linalg.eigvalsh(X.T @ X)[-1] / (4 * n) + lam # a global bound on the Hessian
w = np.zeros(2)
for _ in range(30):
w = w - np.linalg.solve(Hess(w), G(w))
ws, Fs = w, F(w)
print(ws.round(4), round(Fs, 5), round(Lb, 3), round(Lb / lam), np.linalg.eigvalsh(Hess(ws)).round(4), round(np.linalg.cond(Hess(ws))))
# [3.4682 0.3803] 0.30901 7.898 790 [0.0293 3.2176] 110
def run(step, tol=1e-10):
w, k, gaps = np.zeros(2), 0, [F(np.zeros(2)) - Fs]
while gaps[-1] > tol:
w, k = step(w), k + 1
gaps.append(F(w) - Fs)
return k, gaps
def armijo(w):
g, t = G(w), 1.0
while F(w - t * g) > F(w) - 1e-4 * t * g @ g:
t /= 2
return w - t * g
k_gd, gaps = run(lambda w: w - G(w) / Lb)
k_ar, _ = run(armijo)
k_nt, gn = run(lambda w: w - np.linalg.solve(Hess(w), G(w)))
print(k_gd, k_ar, k_nt, [f'{g:.1e}' for g in gn], [f'{gaps[i]:.1e}' for i in (10, 100, 1000)])
# 2727 526 5 ['3.8e-01', '5.3e-02', '5.2e-03', '7.7e-05', '2.0e-08', '1.3e-15'] ['2.3e-01', '6.9e-02', '3.8e-05']
# the guarantees: f_k - f* <= (1 - mu/L)^k (f_0 - f*) and f_k - f* <= L |w_0 - w*|^2 / (2k), both hold
print(all(gaps[k] <= (1 - lam / Lb) ** k * gaps[0] + 1e-15 for k in range(len(gaps))),
all(gaps[k] <= Lb * ws @ ws / (2 * k) for k in range(1, len(gaps))),
round(np.log(gaps[0] / 1e-10) * Lb / lam))
# True True 17431: the steps the strongly convex bound asks for, against 2727 taken
# BFGS: the inverse-Hessian approximation Hinv is updated from s = w+ - w and y = g+ - g, and satisfies Hinv y = s
def bfgs(w, tol=1e-10):
Hinv, k = np.eye(2), 0
while F(w) - Fs > tol:
g = G(w); d = -Hinv @ g; t = 1.0
while F(w + t * d) > F(w) + 1e-4 * t * g @ d:
t /= 2
s = t * d; yv = G(w + s) - g; rho = 1 / (yv @ s)
V = np.eye(2) - rho * np.outer(s, yv)
Hinv = V @ Hinv @ V.T + rho * np.outer(s, s)
w, k = w + s, k + 1
return k, Hinv @ yv - s
k_bf, secant = bfgs(np.zeros(2))
r = minimize(F, np.zeros(2), jac=G, method='BFGS', options={'gtol': 1e-9})
print(k_bf, np.abs(secant).max() < 1e-12, r.nit, f'{r.fun - Fs:.0e}')
# 11 True 14 0e+00: our BFGS, the secant equation after the last update, SciPy's BFGS (Wolfe line search)
# where it breaks: pure Newton on x^4 - 2x^2 + x/2 from 0.3 climbs to the local maximum; gradient descent does not
fn = lambda x: x**4 - 2 * x**2 + 0.5 * x
d1, d2 = lambda x: 4 * x**3 - 4 * x + 0.5, lambda x: 12 * x**2 - 4
x = 0.3
for k in range(4):
print(k, round(x, 5), round(fn(x), 3), end=' | ')
x -= d1(x) / d2(x)
x_gd = 0.3
for _ in range(200):
x_gd -= 0.05 * d1(x_gd)
print(round(x_gd, 3), round(fn(x_gd), 3))
# 0 0.3 -0.022 | 1 0.09726 0.03 | 2 0.12676 0.032 | 3 0.12705 0.032 | 0.93 -0.517
Next#
Every problem so far was free: any was allowed. Many problems in machine learning are not. Probabilities must stay on the simplex, the SVM requires every point to be on the correct side of its margin, and PCA looks for the best direction among unit vectors. The next note handles constraints: at a constrained minimum the gradient need not vanish, only be balanced by the constraints, and the Lagrange multipliers and KKT conditions say exactly how.
References#
- D. Merkulov. Optimization for ML, HSE University, 2024. Lecture 2: line search (Armijo, Wolfe and backtracking); lecture 9: gradient descent (rates for quadratics, the smooth convex and the Polyak–Łojasiewicz cases, lower bounds); lecture 15: Newton and quasi-Newton methods (the convergence theorem, affine invariance, SR1, DFP and BFGS).
- S. Boyd, L. Vandenberghe. Convex Optimization. Cambridge University Press, 2004. Lecture slides of Stanford EE364a, lecture 9 (unconstrained minimization: descent methods, backtracking, the zigzag on a quadratic, three readings of the Newton step, the damped and quadratic phases); book Section 9.5.3 (the convergence analysis of Newton’s method).
- G. Strang. Matrix Methods in Data Analysis, Signal Processing, and Machine Learning (MIT 18.065), 2018. Lecture 22: gradient descent, downhill to a minimum.
- L. Vandenberghe. ECE236C, lecture 15: quasi-Newton methods, UCLA, Spring 2022. The convergence of BFGS: global with backtracking, superlinear near the minimum.
- S. Bubeck. Convex optimization: algorithms and complexity. Foundations and Trends in Machine Learning, 8(3–4), 2015. Section 3.5, Theorem 3.15 (the lower bound for smooth strongly convex functions).
- L. Armijo. Minimization of functions having Lipschitz continuous first partial derivatives. Pacific Journal of Mathematics, 16(1), 1966. Corollary 2 (step halving with ).