Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Optimization Algorithms

Open in Colab

This section looks at the algorithms behind the method= argument. We minimize a smooth function

f:Rn→Rf : \mathbb R^n \to \mathbb R

(first without constraints). Almost every method has the form of iterations

xk+1=xk+αkpk,x_{k+1} = x_k + \alpha_k p_k,

a search direction pk p_k and a step length αk\alpha_k. The methods differ in how they choose the two.

Optimality conditions

If x∗x^* is a local minimizer of a smooth ff, the gradient vanishes there, ∇f(x∗)=0\nabla f(x^*) = 0, and the Hessian matrix H(x∗)H(x^*) of second derivatives is positive semidefinite, since otherwise some direction would lead downhill. Conversely, if ∇f(x∗)=0\nabla f(x^*) = 0 and H(x∗)H(x^*) is positive definite, then x∗x^* is a strict local minimizer, by the Taylor expansion

f(x∗+p)=f(x∗)+12 p⊤H(x∗) p+O(∥p∥3),p⊤H(x∗) p>0f(x^* + p) = f(x^*) + \frac12\, p^\top H(x^*)\, p + O(\|p\|^3), \quad p^\top H(x^*)\, p > 0

Points where ∇f=0\nabla f = 0 are called stationary points, and they also include maxima and saddle points. The methods below use only local information about ff, so the best they can do is find a stationary point, usually a local minimizer, and which one depends on where they start.

If ff is convex, meaning that its Hessian is positive semidefinite everywhere, every local minimizer is a global minimizer.

Gradient descent

The simplest choice of direction is the steepest one, pk=−∇f(xk)p_k = -\nabla f(x_k).

Quadratics and the condition number

Suppose we have

f(x)=12x⊤Ax−b⊤x,A symmetric positive definite,f(x) = \frac12 x^\top A x - b^\top x, \qquad A \text{ symmetric positive definite},

whose minimizer solves Ax=bAx = b (so minimizing ff is one way to solve a linear system).
The gradient is Ax−bAx - b, and with a fixed step α\alpha the error ek=xk−x∗e_k = x_k - x^* satisfies

ek+1=(I−αA) ek.e_{k+1} = (I - \alpha A)\, e_k .

In the eigenbasis of AA, the component along an eigenvalue λ\lambda is multiplied by 1−αλ1 - \alpha\lambda at each step. Write LL and μ\mu for the largest and smallest eigenvalues. The iteration converges only if α<2/L\alpha < 2/L. With α=1/L\alpha = 1/L the slowest component shrinks by 1−μ/L=1−1/κ1 - \mu/L = 1 - 1/\kappa per step, where κ=L/μ\kappa = L/\mu is the condition number. Gradient descent needs about κlog⁡(1/ε)\kappa \log(1/\varepsilon) iterations to reduce the error by a factor ε\varepsilon.

The iterates bounce from one wall of the valley to the other while creeping along it. The number of iterations grows in proportion to κ\kappa:

For a general ff we don’t know the largest eigenvalue LL of its Jacobian.
A backtracking line search starts with a full step α=1\alpha = 1 and halves it until the step gives a sufficient decrease

f(xk+αpk)≤f(xk)+c α ∇f(xk)⊤pk,f(x_k + \alpha p_k) \le f(x_k) + c\,\alpha\, \nabla f(x_k)^\top p_k,

with a small constant like c=10−4c = 10^{-4} (the Armijo condition). This rules out steps that reduce ff by only a negligible amount, and it works with any descent direction pkp_k, which we will reuse below.

The standard hard test is Rosenbrock’s function f(x,y)=(1−x)2+100 (y−x2)2f(x, y) = (1 - x)^2 + 100\,(y - x^2)^2, whose minimum at (1,1)(1, 1) sits at the bottom of a long, curved, flat-bottomed valley. SciPy provides it as rosen, with gradient rosen_der and Hessian rosen_hess.

More than ten thousand iterations for a two-variable problem. Near the minimum the Hessian of the Rosenbrock function has condition number around 2500, so this is the quadratic picture all over again.

Momentum

A cheap and remarkably effective fix is to remember the previous step. Nesterov’s accelerated gradient method takes

xk+1=yk−1L∇f(yk),yk+1=xk+1+β (xk+1−xk),β=κ−1κ+1.x_{k+1} = y_k - \frac{1}{L}\nabla f(y_k), \qquad y_{k+1} = x_{k+1} + \beta\,(x_{k+1} - x_k), \qquad \beta = \frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}.

The extra term keeps pushing in the direction the iterates have been moving, which builds up speed along the valley floor and damps the bouncing across it. On a quadratic the iteration count drops from O(κ)O(\kappa) to O(κ)O(\sqrt\kappa).

Momentum is the reason the optimizers used to train neural networks (SGD with momentum, Adam) work as well as they do.

Conjugate gradients

For a quadratic f(x)=12x⊤Ax−b⊤xf(x) = \frac12 x^\top A x - b^\top x there is a momentum method that needs no parameters at all. The conjugate gradient (CG) method takes the step length from an exact line search along pkp_k, and it chooses the momentum coefficient βk\beta_k so that each new direction is conjugate to the previous ones, pj⊤Apk=0p_j^\top A p_k = 0 for j≠kj \ne k:

xk+1=xk+αkpk,rk+1=rk−αkApk,pk+1=rk+1+βkpk,x_{k+1} = x_k + \alpha_k p_k, \qquad r_{k+1} = r_k - \alpha_k A p_k, \qquad p_{k+1} = r_{k+1} + \beta_k p_k,
αk=rk⊤rkpk⊤Apk,βk=rk+1⊤rk+1rk⊤rk,\alpha_k = \frac{r_k^\top r_k}{p_k^\top A p_k}, \qquad \beta_k = \frac{r_{k+1}^\top r_{k+1}}{r_k^\top r_k},

starting from p0=r0=b−Ax0p_0 = r_0 = b - Ax_0, where rk=b−Axk=−∇f(xk)r_k = b - Ax_k = -\nabla f(x_k) is the residual. Each step minimizes ff over all the points that can be reached with the directions so far, so in exact arithmetic CG finds the minimizer of an nn-dimensional quadratic in at most nn steps. We compare the two on a quadratic in n=1000n = 1000 variables, with AA diagonal and its eigenvalues spread evenly between 1 and κ\kappa.

Newton’s method

Newton’s method uses second derivatives. Near xkx_k,

f(xk+p)≈f(xk)+∇f(xk)⊤p+12 p⊤H(xk) p,f(x_k + p) \approx f(x_k) + \nabla f(x_k)^\top p + \frac12\, p^\top H(x_k)\, p,

where HH is the Hessian matrix. If HH is positive definite, this quadratic model is minimized by the solution of

H(xk) pk=−∇f(xk),H(x_k)\, p_k = -\nabla f(x_k),

which is the Newton step. This is the same Newton’s method as for root finding in Root Finding, applied to the equation ∇f=0\nabla f = 0. As always, we don’t form H−1H^{-1}, but instead solve the linear system.

On a quadratic, the model is exact, so Newton’s method converges in one step whatever the condition number. More generally, Newton’s method is affine invariant: a linear change of variables does not change its iterates, so ill-conditioning of this kind cannot slow it down. Near a minimum where HH is positive definite the convergence is quadratic, which roughly doubles the number of correct digits per step (see Convergence of Algorithms).

Far from the minimum the Hessian may not be positive definite, and then the Newton step need not go downhill. Practical versions combine it with a line search, falling back on the gradient direction when necessary.

We test this against the Rosenbrock function:

22 iterations instead of thirteen thousand, and the last few show the quadratic convergence: 10−2,10−3,10−6,10−1010^{-2}, 10^{-3}, 10^{-6}, 10^{-10}, then zero to machine precision.

The cost is the Hessian. It has n2n^2 entries to compute and store, and each step solves an n×nn \times n system, O(n3)O(n^3) work for a dense matrix. For large nn that is often out of the question.

Quasi-Newton methods: BFGS

Quasi-Newton methods build up an approximation to the Hessian, or to its inverse, from the gradients they have already computed. After a step sk=xk+1−xks_k = x_{k+1} - x_k the gradient changes by yk=∇f(xk+1)−∇f(xk)≈Hsky_k = \nabla f(x_{k+1}) - \nabla f(x_k) \approx H s_k. The BFGS method updates an approximation Bk≈H−1B_k \approx H^{-1} so that it satisfies Bk+1yk=skB_{k+1} y_k = s_k exactly while changing as little as possible:

Bk+1=(I−ρkskyk⊤) Bk (I−ρkyksk⊤)+ρksksk⊤,ρk=1yk⊤sk.B_{k+1} = (I - \rho_k s_k y_k^\top)\, B_k\, (I - \rho_k y_k s_k^\top) + \rho_k s_k s_k^\top, \qquad \rho_k = \frac{1}{y_k^\top s_k}.

Each iteration costs O(n2)O(n^2) and needs only gradients, and the convergence is superlinear. L-BFGS stores only the last few pairs (sk,yk)(s_k, y_k) instead of the matrix, so it needs O(n)O(n) memory and scales to millions of variables.

Rates of convergence

The distance to the minimizer against the iteration number shows the kinds of convergence from Convergence of Algorithms.

In its first 40 iterations gradient descent hardly moves, apart from the long step at iteration 31. It converges linearly, with a factor per step so close to 1 that it needs thousands more iterations. Once Newton’s method is close to the minimizer it converges quadratically, roughly doubling the number of correct digits at each step. BFGS converges superlinearly: the ratio of successive errors goes to zero, more slowly than for Newton, as BkB_k learns the Hessian.

The BFGS update needs yk⊤sk>0y_k^\top s_k > 0 to keep BkB_k positive definite. SciPy’s BFGS uses a line search that also enforces the curvature condition ∇f(xk+αpk)⊤pk≥c2 ∇f(xk)⊤pk\nabla f(x_k + \alpha p_k)^\top p_k \ge c_2\, \nabla f(x_k)^\top p_k, with c2=0.9c_2 = 0.9, which guarantees it, since then yk⊤sk≥(c2−1) α ∇f(xk)⊤pk>0y_k^\top s_k \ge (c_2 - 1)\,\alpha\,\nabla f(x_k)^\top p_k > 0. Together with the Armijo condition this makes up the Wolfe conditions. Our backtracking line search does not enforce the curvature condition, which is why bfgs checks yk⊤sky_k^\top s_k before updating.

SciPy implements all of these and more. Here is the same problem with several method options, counting iterations (nit) and evaluations of ff (nfev).

Nelder-Mead uses no derivatives at all, which is convenient but scales poorly with the dimension. CG is the nonlinear conjugate gradient method, which needs only O(n)O(n) memory. trust-exact is a trust-region Newton method. The defaults in minimize are BFGS for unconstrained problems and L-BFGS-B when there are bounds.

Nonlinear least squares

Fitting a model to data usually means minimizing a sum of squares,

min⁡θ 12∥r(θ)∥2,ri(θ)=modeli(θ)−datai.\min_\theta\ \frac12 \|r(\theta)\|^2, \qquad r_i(\theta) = \text{model}_i(\theta) - \text{data}_i .

The gradient is J⊤rJ^\top r, where JJ is the Jacobian of the residuals, and the Hessian is J⊤J+∑iri∇2riJ^\top J + \sum_i r_i \nabla^2 r_i. When the model fits well the residuals are small and the second term can be dropped. The resulting Gauss-Newton step solves the linear least squares problem

min⁡p ∥Jp+r∥2,\min_p\ \|J p + r\|^2,

best solved with QR or lstsq rather than the normal equations.

The correction shrinks by a roughly constant factor each step: fast linear convergence. Gauss-Newton is quadratically convergent only when the residual at the solution is zero; with noisy data it is linear, with a rate that is good when the noise is small.

From a poor starting point, plain Gauss-Newton can run away:

The Levenberg-Marquardt method damps the step,

(J⊤J+λI) p=−J⊤r,(J^\top J + \lambda I)\, p = -J^\top r,

and adjusts λ\lambda as it goes. A large λ\lambda gives a short step in the gradient direction; a small one gives the Gauss-Newton step.

Example: fitting an ODE model

In Initial Value Problems you modeled lions and zebras with a predator-prey system. Suppose you have instead counted the animals every 10 months, with 5% counting errors, and want to recover the rates α,β,γ\alpha, \beta, \gamma. The residual function solves the ODE for the trial parameters, so every evaluation of rr is a call to solve_ivp.

Stochastic gradient descent

In statistics and machine learning the objective is usually an average over a data set,

f(θ)=1n∑i=1nfi(θ),f(\theta) = \frac{1}{n}\sum_{i=1}^n f_i(\theta),

for example fi(θ)=12(xi⊤θ−yi)2f_i(\theta) = \frac12 (x_i^\top\theta - y_i)^2 for least squares. One gradient evaluation costs a pass over all nn data points. Stochastic gradient descent (SGD) instead estimates the gradient from a random mini-batch BB of the data,

gk=1∣B∣∑i∈B∇fi(θk),g_k = \frac{1}{|B|} \sum_{i \in B} \nabla f_i(\theta_k),

which is correct on average and far cheaper. SGD takes many cheap, noisy steps instead of a few expensive, accurate ones. Performance is measured in epochs, the number of passes through the data.

Here is a linear regression with n=10,000n = 10{,}000 observations of p=20p = 20 features of very different scales, so that the problem has condition number about 100.

After one pass through the data, SGD has taken about 300 steps while gradient descent has taken one, and SGD is far ahead. With a constant step, SGD then stalls at a level set by the gradient noise: the steps never get small enough to settle down. Decreasing the step size over time removes the floor.

Here the exact answer is one call to lstsq away, so SGD is just a demonstration. It becomes the method of choice when nn is huge, the model is not linear, and an approximate minimizer is good enough, which describes training neural networks.

Constrained optimization

Find the point on the unit circle closest to a=(2,1)a = (2, 1),

minimizex f(x)=∥x−a∥22subject toc(x)=∥x∥22−1=0.\mathop{\mathsf{minimize}}_x\ f(x) = \|x - a\|_2^2 \quad \text{subject to} \quad c(x) = \|x\|_2^2 - 1 = 0 .

Lagrange multipliers

Let the Lagrangian be

L(x,λ)=f(x)+λc(x)\mathcal L(x, \lambda) = f(x) + \lambda c(x)

for some number λ\lambda, the Lagrange multiplier. If (x∗,λ∗)(x^*, \lambda^*) is a stationary point of the Lagrangian, then

∂L/∂x=0,∂L/∂λ=0\partial \mathcal L / \partial x = 0, \quad \partial \mathcal L / \partial \lambda = 0

which is equivalently

∇f(x∗)+λ∗∇c(x∗)=0,c(x∗)=0,\nabla f(x^*) + \lambda^* \nabla c(x^*) = 0, \qquad c(x^*) = 0,

Here the first condition reads 2(x−a)+2λx=02(x - a) + 2\lambda x = 0, so x=a/(1+λ)x = a/(1 + \lambda), and the constraint ∥x∥=1\|x\| = 1 gives 1+λ=∥a∥=51 + \lambda = \|a\| = \sqrt 5. So x∗=a/5x^* = a/\sqrt5 and λ∗=5−1≈1.236\lambda^* = \sqrt5 - 1 \approx 1.236.

The level set of ff through x∗x^* (dashed) touches the circle there, and ∇f\nabla f and ∇c\nabla c point in opposite directions along the same line. For an inequality constraint c(x)≤0c(x) \le 0, such as the disk ∥x∥≤1\|x\| \le 1, the same conditions hold with λ∗≥0\lambda^* \ge 0, and λ∗=0\lambda^* = 0 if the constraint is not active at the solution, since then it could be dropped. These are the KKT conditions (for Karush, Kuhn, and Tucker). The multiplier also measures what the constraint costs: if the constraint is relaxed to c(x)=ϵc(x) = \epsilon, the optimal value changes by about −λ∗ϵ-\lambda^* \epsilon.

Penalty methods

The simplest way to use an unconstrained method is to add a penalty for violating the constraint,

minimizex f(x)+μ2 c(x)2.\mathop{\mathsf{minimize}}_x\ f(x) + \frac{\mu}{2}\, c(x)^2 .

Its minimizer xμx_\mu satisfies ∇f+μ c(xμ)∇c=0\nabla f + \mu\, c(x_\mu) \nabla c = 0, which is the Lagrange condition with λ=μ c(xμ)\lambda = \mu\, c(x_\mu). Since λ∗≠0\lambda^* \ne 0, the constraint stays violated by about c(xμ)≈λ∗/μc(x_\mu) \approx \lambda^*/\mu, so an accurate answer needs a large μ\mu.

The violation and the error fall like 1/μ1/\mu, and μ c(xμ)\mu\, c(x_\mu) converges to λ∗≈1.2361\lambda^* \approx 1.2361. The condition number of the Hessian grows like μ\mu, though, because the penalty makes ff steep across the constraint but not along it, so the subproblems get harder as μ\mu grows (recall that gradient descent needs O(κ)O(\kappa) iterations).

Augmented Lagrangian methods

The augmented Lagrangian method adds the multiplier term of the Lagrangian to the penalty,

minimizex f(x)+λk c(x)+μ2 c(x)2,\mathop{\mathsf{minimize}}_x\ f(x) + \lambda_k\, c(x) + \frac{\mu}{2}\, c(x)^2,

and after each minimization updates the estimate of the multiplier, λk+1=λk+μ c(xk+1)\lambda_{k+1} = \lambda_k + \mu\, c(x_{k+1}). The minimizer satisfies ∇f+(λk+μc)∇c=0\nabla f + (\lambda_k + \mu c)\nabla c = 0, so λk+μc\lambda_k + \mu c is the multiplier that the Lagrange condition sees, and the update carries it over to the next subproblem. Once λk\lambda_k is close to λ∗\lambda^*, the constraint can be satisfied without a large μ\mu.

With μ=10\mu = 10 fixed, each update reduces the violation and the error by a factor of about 10, and λk\lambda_k converges to λ∗=5−1=1.2360679775\lambda^* = \sqrt5 - 1 = 1.2360679775. The first iteration, with λ0=0\lambda_0 = 0, is the penalty method with μ=10\mu = 10. To reach the error 5×10−95 \times 10^{-9} of the eighth iteration, the penalty method would need μ≈108\mu \approx 10^8, with a condition number near 108.

Barrier methods

For an inequality constraint c(x)≤0c(x) \le 0, a barrier keeps the iterates strictly inside the feasible set:

minimizex f(x)−μlog⁡(−c(x)),μ→0.\mathop{\mathsf{minimize}}_x\ f(x) - \mu \log\big(-c(x)\big), \qquad \mu \to 0.

The barrier term grows to infinity at the boundary, so a method that starts inside and only accepts steps that decrease the objective stays inside. We decrease μ\mu by a factor of 10 at a time and minimize with newton from above, starting each time from the previous minimizer. Returning np.inf outside the disk makes the line search reject steps that leave it.

The minimizers xμx_\mu approach x∗x^* from inside the disk, with −c(xμ)-c(x_\mu) and the error proportional to μ\mu, along what is called the central path, and μ/(−c(xμ))\mu/(-c(x_\mu)) converges to λ∗\lambda^*. In fact xμx_\mu satisfies the KKT conditions with λ=μ/(−c(xμ))\lambda = \mu/(-c(x_\mu)), except that λ c(x)=0\lambda\, c(x) = 0 is replaced by λ c(x)=−μ\lambda\, c(x) = -\mu. Interior point methods solve these perturbed conditions with Newton’s method while driving μ\mu to zero, taking a few Newton steps for each value of μ\mu as here.

Which method?

situationmethod
smooth, small or medium nn, gradient availableBFGS (the default in minimize)
large nn, or simple bounds on the variablesL-BFGS-B
Hessian (or Hessian-vector products) availabletrust-exact, trust-ncg, Newton-CG
no derivatives, few variablesNelder-Mead, Powell
sum of squares, fitting a model to dataleast_squares, curve_fit
equality and inequality constraintsSLSQP (the default with constraints), trust-constr
linear objective and linear constraintslinprog, and milp for integer variables
average over a huge data setSGD or Adam (for example in PyTorch)
many local minima, few variablesbasinhopping, differential_evolution

Whatever the method, provide derivatives when you can, scale the variables so they have comparable sizes, and check the result from more than one starting point.

Exercises

Exercise 1

For the quadratic f(x)=12x⊤Axf(x) = \tfrac12 x^\top A x, the step length that exactly minimizes ff along the direction −g-g is α=g⊤g/g⊤Ag\alpha = g^\top g / g^\top A g. Derive this, implement gradient descent with this exact line search, and plot its path for κ=30\kappa = 30. Show numerically that consecutive steps are orthogonal. Is it faster than the best fixed step?

Exercise 2

Apply pure Newton’s method (no line search) to f(x)=1+x2f(x) = \sqrt{1 + x^2}, whose minimum is at x=0x = 0, starting from x0=0.5x_0 = 0.5, 0.9, and 1.1. Show that the Newton iteration is xk+1=−xk3x_{k+1} = -x_k^3. For which starting points does it converge, and how fast? Then add the backtracking line search and try x0=10x_0 = 10.

Exercise 3

Compare BFGS, L-BFGS-B, and CG on the nn-dimensional Rosenbrock function (rosen accepts vectors of any length) for n=10,100,1000n = 10, 100, 1000, starting from zero. Record iterations, function evaluations, and time. How does each scale with nn, and why?