This section looks at the algorithms behind the method= argument. We minimize a smooth function
(first without constraints). Almost every method has the form of iterations
a search direction and a step length . The methods differ in how they choose the two.
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp
from scipy.optimize import minimize, least_squares
rng = np.random.default_rng(37830)Optimality conditions¶
If is a local minimizer of a smooth , the gradient vanishes there, , and the Hessian matrix of second derivatives is positive semidefinite, since otherwise some direction would lead downhill. Conversely, if and is positive definite, then is a strict local minimizer, by the Taylor expansion
Points where are called stationary points, and they also include maxima and saddle points. The methods below use only local information about , so the best they can do is find a stationary point, usually a local minimizer, and which one depends on where they start.
If 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, .
Quadratics and the condition number¶
Suppose we have
whose minimizer solves (so minimizing is one way to solve a linear system).
The gradient is , and with a fixed step the error satisfies
In the eigenbasis of , the component along an eigenvalue is multiplied by at each step. Write and for the largest and smallest eigenvalues. The iteration converges only if . With the slowest component shrinks by per step, where is the condition number. Gradient descent needs about iterations to reduce the error by a factor .
def quadratic(kappa, angle=np.pi / 6):
"""
SPD matrix with eigenvalues 1 and kappa, eigenvectors rotated by angle
"""
c, s = np.cos(angle), np.sin(angle)
Q = np.array([[c, -s], [s, c]])
return Q @ np.diag([1.0, kappa]) @ Q.T
def gd_fixed(A, x0, alpha, tol=1e-8, maxit=200_000):
"""
gradient descent on f = x^T A x / 2 with a fixed step; returns the iterates
"""
x = np.array(x0, dtype=float)
path = [x.copy()]
for _ in range(maxit):
g = A @ x
if np.linalg.norm(g) < tol:
break
x = x - alpha * g
path.append(x.copy())
return np.array(path)
fig, ax = plt.subplots(1, 2, figsize=(12, 4.5))
xx, yy = np.meshgrid(np.linspace(-1.2, 1.2, 200), np.linspace(-1.2, 1.2, 200))
for a, kappa in zip(ax, [3, 30]):
A = quadratic(kappa)
F = 0.5 * (A[0, 0] * xx**2 + 2 * A[0, 1] * xx * yy + A[1, 1] * yy**2)
path = gd_fixed(A, [-1.0, 0.6], alpha=2 / (1 + kappa)) # the best fixed step
a.contour(xx, yy, F, levels=np.logspace(-3, 1, 12), colors='gray', linewidths=0.6)
a.plot(path[:60, 0], path[:60, 1], 'o-', ms=3)
a.set_aspect('equal')
a.set_title(f'$\\kappa = {kappa}$: {len(path) - 1} iterations to $|\\nabla f| < 10^{{-8}}$')
plt.show()The iterates bounce from one wall of the valley to the other while creeping along it. The number of iterations grows in proportion to :
print(f"{'kappa':>7} {'step 1/L':>10} {'step 2/(L+mu)':>14}")
for kappa in [10, 100, 1000, 10000]:
A = quadratic(kappa)
n1 = len(gd_fixed(A, [1.0, 1.0], alpha=1 / kappa)) - 1
n2 = len(gd_fixed(A, [1.0, 1.0], alpha=2 / (1 + kappa))) - 1
print(f"{kappa:7d} {n1:10d} {n2:14d}")Line search¶
For a general we don’t know the largest eigenvalue of its Jacobian.
A backtracking line search starts with a full step and halves it until the
step gives a sufficient decrease
with a small constant like (the Armijo condition). This rules out steps that reduce by only a negligible amount, and it works with any descent direction , which we will reuse below.
def backtracking(f, grad, x, p, alpha=1.0, c=1e-4, shrink=0.5):
"""
largest alpha in {1, 1/2, 1/4, ...} satisfying the Armijo condition
"""
fx, slope = f(x), grad(x) @ p
while f(x + alpha * p) > fx + c * alpha * slope:
alpha *= shrink
return alpha
def gradient_descent(f, grad, x0, tol=1e-6, maxit=100_000):
"""
gradient descent with backtracking; returns the array of iterates
"""
x = np.array(x0, dtype=float)
path = [x.copy()]
for _ in range(maxit):
g = grad(x)
if np.linalg.norm(g) < tol:
break
x = x - backtracking(f, grad, x, -g) * g
path.append(x.copy())
return np.array(path)The standard hard test is Rosenbrock’s function
, whose minimum at sits at the bottom
of a long, curved, flat-bottomed valley. SciPy provides it as rosen, with gradient
rosen_der and Hessian rosen_hess.
from scipy.optimize import rosen, rosen_der, rosen_hess
x0 = np.array([-1.2, 1.0])
start = time.perf_counter()
path_gd = gradient_descent(rosen, rosen_der, x0)
print(f"gradient descent: {len(path_gd) - 1} iterations, {time.perf_counter() - start:.1f} s, "
f"final point {path_gd[-1]}")
path = np.array(path_gd)
xx, yy = np.meshgrid(np.linspace(-1.5, 1.5, 300), np.linspace(-0.5, 1.5, 300))
plt.figure(figsize=(8, 5))
plt.contour(xx, yy, rosen([xx, yy]), levels=np.logspace(-1, 3, 12),
colors='gray', linewidths=0.6)
plt.plot(path[:, 0], path[:, 1], 'o-', ms=3)
plt.plot(1, 1, 'k*', ms=12)
plt.title('iterates of minimize on the Rosenbrock function')
plt.show()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
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 to .
def nesterov(A, x0, tol=1e-8, maxit=200_000):
"""
Nesterov's method on f = x^T A x / 2; returns the number of iterations
"""
lam = np.linalg.eigvalsh(A)
L, kappa = lam.max(), lam.max() / lam.min()
beta = (np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)
x = y = np.array(x0, dtype=float)
for k in range(maxit):
x_new = y - (A @ y) / L
y = x_new + beta * (x_new - x)
x = x_new
if np.linalg.norm(A @ x) < tol:
return k + 1
return maxit
print(f"{'kappa':>7} {'gradient descent':>17} {'Nesterov':>9}")
for kappa in [10, 100, 1000, 10000]:
A = quadratic(kappa)
n_gd = len(gd_fixed(A, [1.0, 1.0], alpha=1 / kappa)) - 1
print(f"{kappa:7d} {n_gd:17d} {nesterov(A, [1.0, 1.0]):9d}")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 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 , and it chooses the momentum coefficient so that each new direction is conjugate to the previous ones, for :
starting from , where is the residual. Each step minimizes over all the points that can be reached with the directions so far, so in exact arithmetic CG finds the minimizer of an -dimensional quadratic in at most steps. We compare the two on a quadratic in variables, with diagonal and its eigenvalues spread evenly between 1 and .
def conjugate_gradient(A, b, x0, tol=1e-8, maxit=100_000):
"""
CG for the minimizer of x^T A x / 2 - b^T x, A symmetric positive definite;
returns the minimizer and the number of iterations
"""
x = np.array(x0, dtype=float)
r = b - A @ x # the residual, minus the gradient
p = r.copy()
rr = r @ r
for k in range(maxit):
if np.sqrt(rr) < tol:
return x, k
Ap = A @ p
alpha = rr / (p @ Ap) # exact line search along p
x = x + alpha * p
r = r - alpha * Ap
rr_new = r @ r
p = r + (rr_new / rr) * p
rr = rr_new
return x, maxit
N = 1000 # number of variables
print(f"{'kappa':>7} {'Nesterov':>9} {'CG':>5}")
for kappa in [10, 100, 1000, 10000]:
A = np.diag(np.linspace(1, kappa, N)) # eigenvalues spread evenly in [1, kappa]
x_start = np.ones(N)
_, n_cg = conjugate_gradient(A, np.zeros(N), x_start)
print(f"{kappa:7d} {nesterov(A, x_start):9d} {n_cg:5d}")Newton’s method¶
Newton’s method uses second derivatives. Near ,
where is the Hessian matrix. If is positive definite, this quadratic model is minimized by the solution of
which is the Newton step. This is the same Newton’s method as for root finding in Root Finding, applied to the equation . As always, we don’t form , 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 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:
def newton(f, grad, hess, x0, tol=1e-10, maxit=100):
"""
Newton's method with backtracking; uses -grad when the Newton step points uphill
"""
x = np.array(x0, dtype=float)
path = [x.copy()]
for _ in range(maxit):
g = grad(x)
if np.linalg.norm(g) < tol:
break
p = np.linalg.solve(hess(x), -g)
if g @ p >= 0: # not a descent direction
p = -g
x = x + backtracking(f, grad, x, p) * p
path.append(x.copy())
return np.array(path)
path_newton = newton(rosen, rosen_der, rosen_hess, x0)
err = np.linalg.norm(path_newton - 1, axis=1)
print(f"Newton: {len(path_newton) - 1} iterations")
print("distance to the minimum over the last iterations:", np.array2string(err[-6:], precision=1))22 iterations instead of thirteen thousand, and the last few show the quadratic convergence: , then zero to machine precision.
The cost is the Hessian. It has entries to compute and store, and each step solves an system, work for a dense matrix. For large 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 the gradient changes by . The BFGS method updates an approximation so that it satisfies exactly while changing as little as possible:
Each iteration costs and needs only gradients, and the convergence is superlinear. L-BFGS stores only the last few pairs instead of the matrix, so it needs memory and scales to millions of variables.
def bfgs(f, grad, x0, tol=1e-8, maxit=1000):
"""
BFGS with backtracking; returns the array of iterates
"""
x = np.array(x0, dtype=float)
I = np.eye(len(x))
B = np.eye(len(x)) # approximate inverse Hessian
g = grad(x)
path = [x.copy()]
for _ in range(maxit):
if np.linalg.norm(g) < tol:
break
p = -B @ g
s = backtracking(f, grad, x, p) * p
x_new = x + s
g_new = grad(x_new)
y = g_new - g
if y @ s > 1e-12: # skip the update if the curvature is not positive
rho = 1 / (y @ s)
B = (I - rho * np.outer(s, y)) @ B @ (I - rho * np.outer(y, s)) + rho * np.outer(s, s)
x, g = x_new, g_new
path.append(x.copy())
return np.array(path)
path_bfgs = bfgs(rosen, rosen_der, x0)
print(f"BFGS: {len(path_bfgs) - 1} iterations, final point {path_bfgs[-1]}")
xx, yy = np.meshgrid(np.linspace(-1.5, 1.5, 300), np.linspace(-0.5, 1.5, 300))
F = rosen(np.array([xx, yy]))
plt.figure(figsize=(8, 5))
plt.contour(xx, yy, F, levels=np.logspace(-1, 3, 14), colors='gray', linewidths=0.6)
plt.plot(path_gd[:, 0], path_gd[:, 1], '.-', ms=2, lw=0.8, label='gradient descent')
plt.plot(path_bfgs[:, 0], path_bfgs[:, 1], 'o-', ms=4, label='BFGS')
plt.plot(path_newton[:, 0], path_newton[:, 1], 's-', ms=4, label='Newton')
plt.plot(1, 1, 'k*', ms=14)
plt.legend()
plt.title('paths on the Rosenbrock function')
plt.show()Rates of convergence¶
The distance to the minimizer against the iteration number shows the kinds of convergence from Convergence of Algorithms.
plt.figure(figsize=(7, 4))
for name, path in [("gradient descent", path_gd), ("BFGS", path_bfgs), ("Newton", path_newton)]:
plt.semilogy(np.linalg.norm(path - 1, axis=1), 'o-', ms=3, label=name)
plt.xlim(0, 40)
plt.xlabel('iteration $k$')
plt.ylabel(r'$\|x_k - x^*\|$')
plt.legend()
plt.title('Rosenbrock function from $(-1.2, 1)$')
plt.show()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 learns the Hessian.
The BFGS update needs to keep positive definite. SciPy’s BFGS uses a
line search that also enforces the curvature condition
, with , which
guarantees it, since then .
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
before updating.
SciPy implements all of these and more. Here is the same problem with several method
options, counting iterations (nit) and evaluations of (nfev).
print(f"{'method':12} {'nit':>5} {'nfev':>5} {'distance to (1, 1)':>18}")
for method in ["Nelder-Mead", "CG", "BFGS", "L-BFGS-B", "Newton-CG", "trust-exact"]:
options = {}
if method != "Nelder-Mead":
options["jac"] = rosen_der
if method in ("Newton-CG", "trust-exact"):
options["hess"] = rosen_hess
res = minimize(rosen, x0, method=method, **options)
print(f"{method:12} {res.nit:5d} {res.nfev:5d} {np.linalg.norm(res.x - 1):18.1e}")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
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,
The gradient is , where is the Jacobian of the residuals, and the Hessian is . 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
best solved with QR or lstsq rather than the normal equations.
def gauss_newton(r, jac, theta0, tol=1e-12, maxit=50):
"""
Gauss-Newton iteration for min ||r(theta)||^2; returns the iterates
"""
theta = np.array(theta0, dtype=float)
path = [theta.copy()]
for _ in range(maxit):
p, *_ = np.linalg.lstsq(jac(theta), -r(theta), rcond=None)
theta = theta + p
path.append(theta.copy())
if np.linalg.norm(p) <= tol * (1 + np.linalg.norm(theta)):
break
return np.array(path)
# noisy samples of a decaying exponential a * exp(-b t)
t = np.linspace(0, 4, 40)
y = 2.0 * np.exp(-1.3 * t) + 0.02 * rng.standard_normal(t.size)
r = lambda th: th[0] * np.exp(-th[1] * t) - y
jac = lambda th: np.column_stack([np.exp(-th[1] * t), -th[0] * t * np.exp(-th[1] * t)])
path = gauss_newton(r, jac, [1.0, 1.0])
print("Gauss-Newton from (1, 1):")
for k, th in enumerate(path):
print(f" step {k}: a = {th[0]:.10f}, b = {th[1]:.10f}")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:
print("Gauss-Newton from (1, 5):", gauss_newton(r, jac, [1.0, 5.0])[-1])
print("Levenberg-Marquardt from (1, 5):", least_squares(r, [1.0, 5.0], jac=jac, method='lm').x)The Levenberg-Marquardt method damps the step,
and adjusts as it goes. A large 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
. The residual function solves the ODE for the trial parameters,
so every evaluation of is a call to solve_ivp.
def lions_zebras(t, y, alpha, beta, gamma):
lions, zebras = y
return [-gamma * lions + beta / 500 * lions * zebras,
alpha * zebras - beta / 100 * lions * zebras]
true_params = np.array([0.02, 0.3, 0.02])
y0 = [5.0, 50.0]
t_obs = np.arange(0, 601, 10.0)
truth = solve_ivp(lions_zebras, (0, 600), y0, t_eval=t_obs, args=tuple(true_params),
rtol=1e-10, atol=1e-10).y
counts = truth * (1 + 0.05 * rng.standard_normal(truth.shape))
def count_residuals(params):
"""
model minus data, in units of the 5% counting error
"""
sol = solve_ivp(lions_zebras, (0, 600), y0, t_eval=t_obs, args=tuple(params),
rtol=1e-8, atol=1e-8)
if not sol.success:
return np.full(counts.size, 1e3) # penalize parameters that break the solver
return ((sol.y - counts) / (0.05 * counts)).ravel()
start = time.perf_counter()
fit = least_squares(count_residuals, [0.03, 0.2, 0.03], x_scale='jac')
cov = np.linalg.inv(fit.jac.T @ fit.jac) # standard Gauss-Newton estimate of the covariance
print(f"{fit.nfev} residual evaluations, {time.perf_counter() - start:.2f} s")
for name, est, sd, tr in zip(["alpha", "beta", "gamma"], fit.x, np.sqrt(np.diag(cov)), true_params):
print(f" {name:5} = {est:.5f} +/- {sd:.5f} (true value {tr})")fine_t = np.linspace(0, 600, 600)
fitted = solve_ivp(lions_zebras, (0, 600), y0, t_eval=fine_t, args=tuple(fit.x),
rtol=1e-8, atol=1e-8).y
plt.figure(figsize=(8, 4))
plt.plot(t_obs, counts[1], 'k.', label='zebra counts')
plt.plot(t_obs, counts[0], 'r.', label='lion counts')
plt.plot(fine_t, fitted[1], 'k')
plt.plot(fine_t, fitted[0], 'r')
plt.xlabel('months')
plt.ylabel('population')
plt.legend()
plt.title('fitted predator-prey model')
plt.show()Stochastic gradient descent¶
In statistics and machine learning the objective is usually an average over a data set,
for example for least squares. One gradient evaluation costs a pass over all data points. Stochastic gradient descent (SGD) instead estimates the gradient from a random mini-batch of the data,
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 observations of features of very different scales, so that the problem has condition number about 100.
n, p = 10_000, 20
X = rng.standard_normal((n, p)) * np.linspace(1, 10, p)
y = X @ rng.standard_normal(p) + 0.5 * rng.standard_normal(n)
loss = lambda th: 0.5 * np.mean((X @ th - y)**2)
th_star, *_ = np.linalg.lstsq(X, y, rcond=None)
loss_star = loss(th_star)
L = np.linalg.eigvalsh(X.T @ X / n).max()
def full_gradient_descent(epochs):
th = np.zeros(p)
gaps = [loss(th) - loss_star]
for _ in range(epochs):
th = th - (X.T @ (X @ th - y) / n) / L
gaps.append(loss(th) - loss_star)
return np.array(gaps)
def sgd(epochs, batch=32, lr=0.5 / L, decay=False):
th = np.zeros(p)
gaps = [loss(th) - loss_star]
steps_per_epoch = n // batch
k = 0
for _ in range(epochs):
order = rng.permutation(n)
for j in range(steps_per_epoch):
idx = order[j * batch:(j + 1) * batch]
g = X[idx].T @ (X[idx] @ th - y[idx]) / batch
step = lr / (1 + k / (2 * steps_per_epoch)) if decay else lr
th = th - step * g
k += 1
gaps.append(loss(th) - loss_star)
return np.array(gaps)
epochs = 50
plt.figure(figsize=(7, 4))
plt.semilogy(full_gradient_descent(epochs), 'o-', ms=3, label='gradient descent (1 step per epoch)')
plt.semilogy(sgd(epochs), 'o-', ms=3, label='SGD, constant step')
plt.semilogy(sgd(epochs, decay=True), 'o-', ms=3, label='SGD, decreasing step')
plt.xlabel('epochs (passes through the data)')
plt.ylabel(r'$f(\theta) - f(\theta^*)$')
plt.legend()
plt.title('least squares with n = 10,000')
plt.show()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 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 ,
Lagrange multipliers¶
Let the Lagrangian be
for some number , the Lagrange multiplier. If is a stationary point of the Lagrangian, then
which is equivalently
Here the first condition reads , so , and the constraint gives . So and .
a = np.array([2.0, 1.0])
f = lambda x: np.sum((x - a)**2)
grad_f = lambda x: 2 * (x - a)
c = lambda x: x @ x - 1
grad_c = lambda x: 2 * x
x_star, lam_star = a / np.sqrt(5), np.sqrt(5) - 1
xx, yy = np.meshgrid(np.linspace(-1.5, 2.5, 300), np.linspace(-1.5, 1.5, 300))
F = (xx - a[0])**2 + (yy - a[1])**2
theta = np.linspace(0, 2 * np.pi, 300)
plt.figure(figsize=(6, 4.5))
plt.contour(xx, yy, F, levels=[0.25, 1, 2.25, 4, 6.25, 9], colors='gray', linewidths=0.6)
plt.contour(xx, yy, F, levels=[f(x_star)], colors='gray', linestyles='dashed')
plt.plot(np.cos(theta), np.sin(theta), 'k', label='$c(x) = 0$')
plt.quiver(*x_star, *grad_f(x_star), angles='xy', scale_units='xy', scale=3, color='C0',
label=r'$\nabla f(x^*)$')
plt.quiver(*x_star, *grad_c(x_star), angles='xy', scale_units='xy', scale=3, color='C1',
label=r'$\nabla c(x^*)$')
plt.plot(*a, 'k*', ms=12)
plt.plot(*x_star, 'ko')
plt.gca().set_aspect('equal')
plt.legend(loc='lower right')
plt.title('closest point on the unit circle to $a$ (star)')
plt.show()The level set of through (dashed) touches the circle there, and and point in opposite directions along the same line. For an inequality constraint , such as the disk , the same conditions hold with , and 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 , the optimal value changes by about .
Penalty methods¶
The simplest way to use an unconstrained method is to add a penalty for violating the constraint,
Its minimizer satisfies , which is the Lagrange condition with . Since , the constraint stays violated by about , so an accurate answer needs a large .
print(f"{'mu':>6} {'c(x_mu)':>9} {'error':>9} {'mu c(x_mu)':>11} {'cond(Hessian)':>14}")
for mu in [1, 10, 100, 1000, 10000]:
phi = lambda x: f(x) + mu / 2 * c(x)**2
grad_phi = lambda x: grad_f(x) + mu * c(x) * grad_c(x)
x = minimize(phi, np.zeros(2), jac=grad_phi, method='BFGS', options={'gtol': 1e-10}).x
H = 2 * np.eye(2) + mu * (4 * np.outer(x, x) + 2 * c(x) * np.eye(2)) # Hessian of phi
print(f"{mu:6d} {c(x):9.1e} {np.linalg.norm(x - x_star):9.1e} {mu * c(x):11.4f} "
f"{np.linalg.cond(H):14.1e}")The violation and the error fall like , and converges to . The condition number of the Hessian grows like , though, because the penalty makes steep across the constraint but not along it, so the subproblems get harder as grows (recall that gradient descent needs iterations).
Augmented Lagrangian methods¶
The augmented Lagrangian method adds the multiplier term of the Lagrangian to the penalty,
and after each minimization updates the estimate of the multiplier, . The minimizer satisfies , so is the multiplier that the Lagrange condition sees, and the update carries it over to the next subproblem. Once is close to , the constraint can be satisfied without a large .
mu, lam = 10.0, 0.0
x = np.zeros(2)
for k in range(8):
phi = lambda x: f(x) + lam * c(x) + mu / 2 * c(x)**2
grad_phi = lambda x: grad_f(x) + (lam + mu * c(x)) * grad_c(x)
x = minimize(phi, x, jac=grad_phi, method='BFGS', options={'gtol': 1e-12}).x # warm start
lam = lam + mu * c(x)
print(f"k = {k + 1}: lambda = {lam:.10f}, |c(x)| = {abs(c(x)):.1e}, "
f"error = {np.linalg.norm(x - x_star):.1e}")With fixed, each update reduces the violation and the error by a factor of about 10, and converges to . The first iteration, with , is the penalty method with . To reach the error of the eighth iteration, the penalty method would need , with a condition number near 108.
Barrier methods¶
For an inequality constraint , a barrier keeps the iterates strictly inside the feasible set:
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 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.
x = np.zeros(2) # strictly inside the disk
for mu in [1, 0.1, 0.01, 0.001, 0.0001]:
phi = lambda x: f(x) - mu * np.log(-c(x)) if c(x) < 0 else np.inf
grad_phi = lambda x: grad_f(x) - mu / c(x) * grad_c(x)
hess_phi = lambda x: (2 - 2 * mu / c(x)) * np.eye(2) + mu / c(x)**2 * np.outer(grad_c(x), grad_c(x))
# near the minimizer phi changes by less than its rounding error, so ask for |grad| < 1e-8
path = newton(phi, grad_phi, hess_phi, x, tol=1e-8)
x = path[-1]
print(f"mu = {mu:<6}: {len(path) - 1} Newton steps, -c(x) = {-c(x):.1e}, "
f"error = {np.linalg.norm(x - x_star):.1e}, mu / (-c(x)) = {mu / -c(x):.5f}")The minimizers approach from inside the disk, with and the error proportional to , along what is called the central path, and converges to . In fact satisfies the KKT conditions with , except that is replaced by . Interior point methods solve these perturbed conditions with Newton’s method while driving to zero, taking a few Newton steps for each value of as here.
Which method?¶
| situation | method |
|---|---|
| smooth, small or medium , gradient available | BFGS (the default in minimize) |
| large , or simple bounds on the variables | L-BFGS-B |
| Hessian (or Hessian-vector products) available | trust-exact, trust-ncg, Newton-CG |
| no derivatives, few variables | Nelder-Mead, Powell |
| sum of squares, fitting a model to data | least_squares, curve_fit |
| equality and inequality constraints | SLSQP (the default with constraints), trust-constr |
| linear objective and linear constraints | linprog, and milp for integer variables |
| average over a huge data set | SGD or Adam (for example in PyTorch) |
| many local minima, few variables | basinhopping, 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 , the step length that exactly minimizes along the direction is . Derive this, implement gradient descent with this exact line search, and plot its path for . Show numerically that consecutive steps are orthogonal. Is it faster than the best fixed step?
# Your code hereExercise 2¶
Apply pure Newton’s method (no line search) to , whose minimum is at , starting from , 0.9, and 1.1. Show that the Newton iteration is . For which starting points does it converge, and how fast? Then add the backtracking line search and try .
# Your code hereExercise 3¶
Compare BFGS, L-BFGS-B, and CG on the -dimensional Rosenbrock function (rosen
accepts vectors of any length) for , starting from zero. Record
iterations, function evaluations, and time. How does each scale with , and why?
# Your code here