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 in SciPy

Open in Colab

Optimization seeks to find the best (optimal) value of some function subject to constraints

minimizexf(x),subject to c(x)≤b\mathop{\mathsf{minimize}}_x f(x), \quad \text{subject to } c(x) \le b

The function ff is the objective, and the points xx that satisfy the constraints form the feasible set.

A feasible point x∗x^* is a global minimizer if f(x∗)≤f(x)f(x^*) \le f(x) for every feasible xx, and a local minimizer if this holds for every feasible xx near x∗x^*. SciPy only has minimizers, in order to maximize ff, you instead minimize −f-f.

Functions of One Variable

An easy example is to minimize a quadratic

There is a clear minimum at x = 0. You can search for minima using opt.minimize_scalar

The return type gives you the function value sol.fun, as well as the value of x which achieve the minimum sol.x

If you want to add constraints such as x≥1x \ge 1, you can use bounds, along with specifying the bounded method:

For more complicated functions, there may be multiple solutions

Note that you will only find one minimum, and this minimum will generally only be a local minimum, not a global minimum.

Functions of Multiple variables

You might also wish to minimize functions of multiple variables. In this case, you use opt.minimize

A multivariate quadratic generally has the form x^T A x + b^T x + c, where x is an n-dimensional vector, A is a n x n matrix, b is a n-dimensional vector, and c is a scalar. When A is positive definite (PD), there is a unique minimum.

The solution for the above problem is x = b

We can increase the dimension of the problem to be much greater:

What minimize returns

The result is an OptimizeResult, which behaves like a dictionary. Besides the minimizer x and the value fun, it reports whether the method thinks it succeeded (success and message) and how much work it did (nit iterations and nfev evaluations of ff). Check success before using x, because a method that fails still returns the last point it reached. Here we allow only two iterations:

Extra arguments and callbacks

An objective often depends on parameters of ff. The entries of the tuple args are passed to ff after xx on every call.

The function callback is called after every iteration with the current point, which is a simple way to record the path of the method. Here is the Rosenbrock function (a−x0)2+b (x1−x02)2(a - x_0)^2 + b\,(x_1 - x_0^2)^2, whose minimum at (a,a2)(a, a^2) lies at the bottom of a long curved valley.

Example: Solving a Linear System

Recall that solving a linear system means finding xx so that Ax=bA x = b. We can turn this into an optimization problem by seeking to minimize the residual ∥b−Ax∥2\|b - Ax\|_2:

minimizex∥b−Ax∥2\mathop{\mathsf{minimize}}_x \|b - Ax\|_2

Exercises

  1. Modify the above example to minimize ∥b−Ax∥1\|b-Ax\|_1 instead of ∥b−Ax∥2\| b - Ax\|_2 (look at documentation for la.norm). Is there any difference in the output of opt.minimize?

  2. How fast is la.solve compared to the above example?

Constraints

Passing in a function to be optimized is fairly straightforward. Constraints are slightly less trivial. These are specified using classes LinearConstraint and NonlinearConstraint

  • Linear constraints take the form lb <= A @ x <= ub

  • Nonlinear constraints take the form lb <= fun(x) <= ub

For the special case of a linear constraint with the form lb <= x <= ub, you can use Bounds

Linear Constraints

Let’s look at how you might implement the linear constraints on a 2-vector x

{−1≤x0≤1c≤A∗x≤d\begin{cases} -1 \le x_0 \le 1\\ c \le A * x \le d \end{cases}

where A = np.array([[1,1],[0, 1]], c = -2 * np.ones(2), and d = 2 * np.ones(2)

here’s a visualization of the constrained region:

Now, let’s say we want to minimize a function f(x) subject to x obeying the constraints given above. We can simply pass in the constraints

Let’s visualize the function in the constrained region:

The minimum value f=−2f = -2 is attained at two corners of the feasible set, (−1,2)(-1, 2) and (1,−2)(1, -2), and which one minimize returns depends on the starting point.

Nonlinear constraints

Nonlinear constraints can be used to define more complicated domains. For instance, let’s look at the constraint

1≤∥x∥2≤21 \le \| x \|_2 \le 2

we can visualize this constraint again, and we see that it defines an annulus

Let’s try minimizing the same function as before: f(x)=x[0]∗x[1]f(x) = x[0] * x[1]

The solution is close to one of the two true minimizers, x=(−2,2)x = (-\sqrt{2}, \sqrt{2}) and x=(2,−2)x = (\sqrt{2}, -\sqrt{2}), where f=−2f = -2.

Example: Eigenvalues and Eigenvectors

One example of an optimization problem is to find the largest eigenvalue/eigenvector pair of a matrix AA. If AA is symmetric, and (λ,x)(\lambda, x) is the largest eigenvalue pair, then xx satisfies

minimizex−xTAxsubject to ∥x∥2=1\mathop{\mathsf{minimize}}_x -x^T A x \quad \text{subject to } \|x\|_2 = 1

And we have xTAx=λx^T A x = \lambda. Let’s try encoding this as an optimization problem.

Let’s take a look at a solution obtained using eigh:

Optimization Options

So far, we haven’t worried too much about the internals of opt.minimize. However, for large problems, you’re often going to want to choose an appropriate solver, and provide Jacobian and Hessian information if you are able to.

A list of available solvers is available in the minimize documentation.

Jacobian

The Jacobian of a multi-valued function f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m is the m×nm\times n matrix JfJ_f, where

Jf[i,j]=∂fi∂xjJ_f[i,j] = \frac{\partial{f}_i}{\partial{x_j}}

If ff is scalar-valued (i.e. m=1m = 1), then the Jacobian is the transpose of the gradient Jf=(∇f)TJ_f = (\nabla f)^T

In our examples so far, we only provided the function. If you are able to provide the Jacobian as well, then you can typically solve problems with fewer function evaluations because you have better information about how to decrease the function value. If you don’t provide the Jacobian, many solvers will try to approximate the Jacobian using finite difference approximations, but these are typically less accurate (and slower) than if you can give an explicit formula.

Note that you can also provide a Jacobian to NonlinearConstraint

We see that when we provide the Jacobian, the number of function evaluations nfev decreases.

Checking derivatives

A wrong Jacobian is a common bug, and it raises no error, since the method just gets wrong information about which way is downhill. opt.check_grad(f, jac, x) compares jac(x) with a finite difference approximation and returns the norm of the difference, and opt.approx_fprime(x, f) returns the approximation itself. Here is a Jacobian with a sign error:

Hessian

The Hessian of a multivariate function f:Rn→Rf: \mathbb{R}^n \to \mathbb{R} is a n×nn\times n matrix HfH_f of second derivatives:

H[i,j]=∂2f∂xi∂xjH[i,j] = \frac{\partial^2 f}{\partial x_i \partial x_j}

The Hessian provides information about the curvature of the function ff, which can be used to accelerate convergence of the optimization algorithm. If you don’t provide the Hessian, many solvers will numerically approximate it, which will typically not work as well as an explicit Hessian.

Again, you can also provide a Hessian to NonlinearConstraint

We see that the default method BFGS does not use the Hessian. Let’s choose one that does, like Newton-CG.

Supplying the Jacobian cuts the number of evaluations of ff from 15 to 5, since BFGS no longer needs finite differences, while the error stays at about 5×10−65 \times 10^{-6}, which is set by the default tolerance on the gradient. Newton-CG also uses the Hessian and finds the minimizer to 10-13 in 5 iterations. The savings grow with the number of variables nn, since a finite difference gradient costs nn extra evaluations of ff.

Solvers

Here’s a guide to a couple of different solvers. See the notes section of minimize for additional details.

  • Unconstrained minimization: BFGS - uses Jacobian evaluations to get a low-rank approximation to the Hessian. This is the default when there are no bounds or constraints.

  • Bound constrained minimization: L-BFGS-B - Variation of BFGS which uses limited memory (the L). Use with very large problems. Only uses Jacobian (not Hessian). This is the default when there are bounds.

  • Unconstrained minimization with Jacobian/Hessian: Newton-CG - uses Jacobian and Hessian to exactly solve quadratic approximations to the objective.

  • General constrained minimization: SLSQP - sequential quadratic programming, which minimizes a quadratic model of the objective subject to linearized constraints at each step. This is the default when there are constraints.

  • General constrained minimization: trust-constr - a trust region method for constrained optimization problems. Can use the Hessian of both the objective and constraints.

  • No derivatives: Nelder-Mead - moves a simplex of n+1n + 1 points around; convenient for a few variables, slow for many.

You can find a lot of information and examples about these different options in the scipy.optimize tutorial

Example: A Hanging Chain

A chain hanging between two points settles into the shape that minimizes its potential energy. Model it as nn rigid links of length ℓ\ell, hanging from (0,0)(0, 0) and (1,0)(1, 0).

With the positions (xi,yi)(x_i, y_i) of the joints as variables, there is one equality constraint for the length of each link.

With the angles θi\theta_i of the links as variables, the joints are at

(xk,yk)=ℓ∑i<k(cos⁡θi,sin⁡θi),k=0,…,n,(x_k, y_k) = \ell \sum_{i < k} (\cos\theta_i, \sin\theta_i), \qquad k = 0, \dots, n,

every link automatically has length ℓ\ell, and only the far end needs a constraint, (xn,yn)=(1,0)(x_n, y_n) = (1, 0). The potential energy is proportional to the sum of the heights of the midpoints of the links.

The exact shape of a continuous chain is a catenary,

y=acosh⁡(x−1/2a)−acosh⁡(12a),y = a\cosh\left(\frac{x - 1/2}{a}\right) - a\cosh\left(\frac{1}{2a}\right),

where aa is fixed by the length of the chain: the arc length 2asinh⁡(1/(2a))2a\sinh\big(1/(2a)\big) must equal 1.5. That equation for aa is a job for root_scalar.

The joints lie within 2×10−42 \times 10^{-4} of the catenary. The difference comes from replacing a continuous chain by 40 straight links, and it shrinks as the links get shorter.

Exercise

Repeat the hanging chain with n=10,20,40,80n = 10, 20, 40, 80 links and plot the largest distance from the catenary against nn on a log-log plot. How fast does it decrease? How does the number of iterations of SLSQP change with nn?

Linear Programming

When the objective and the constraints are all linear, the problem is a linear program:

minimizexcTx,subject to Aub x≤bub,Aeq x=beq,l≤x≤u\mathop{\mathsf{minimize}}_x c^T x, \quad \text{subject to } A_{ub}\, x \le b_{ub}, \quad A_{eq}\, x = b_{eq}, \quad l \le x \le u

Linear programs come up in scheduling, transportation, and resource allocation, and can be solved using opt.linprog.

A workshop makes tables and chairs. A table needs 4 hours of carpentry and 2 hours of painting and earns a profit of $70, and a chair needs 3 hours of carpentry and 1 hour of painting and earns $50. There are 240 hours of carpentry and 100 hours of painting per week. To maximize the profit 70x+50y70x + 50y we minimize −70x−50y-70x - 50y. The bounds x,y≥0x, y \ge 0 are the default in linprog; we write them out anyway.

Here is the feasible set, with lines of constant profit.

The profit grows toward the upper right, and the best feasible point is the corner where both constraints are active, (30,40)(30, 40). When a linear program has a solution, one of its solutions is at a corner (a vertex) of the feasible set. The simplex method walks from vertex to vertex, improving the objective at each step, while interior point methods approach the optimal vertex through the inside of the feasible set.

Integer variables

Suppose the workshop had 245 hours of carpentry. The linear program then asks for 27.5 tables. Requiring the variables to be integers gives a mixed-integer linear program, which opt.milp solves. It takes the constraints as a LinearConstraint and the bounds as Bounds.

The integer solution is not the rounded LP solution: rounding (27.5,45)(27.5, 45) down to (27,45)(27, 45) gives a profit of $4140, and (28,45)(28, 45) needs 247 hours of carpentry, while (26,47)(26, 47) gives $4170. Integer programs are much harder than linear programs in general (they are NP-hard), and milp solves a sequence of linear programs with extra bounds on the variables.

Global Optimization

opt.minimize is good for finding local minima of functions. What if your function has many local minima, but you want to find the global minimum? You can use one of the global optimization functions.

Note that finding a global minimum is generally a much more difficult problem than finding a local minimum, and these functions are not guaranteed to find the true global minimum, and may not be very fast.

Here’s an example of a function which has a global minimum, but many local minima:

Starting from (5,5)(5, 5), minimize finds the local minimum nearest the start:

The simplest global strategy is multistart: run a local method from many random starting points and keep the best result.

basinhopping is a multistart that uses what it has found. From the current local minimum it jumps by a random step, of size stepsize, and minimizes again. It accepts the new local minimum if it is lower, and otherwise with probability e−Δf/Te^{-\Delta f / T}, where Δf\Delta f is the increase in ff and the “temperature” T should be comparable to the differences in ff between neighboring local minima. By default it also adjusts stepsize as it goes.

Basin hopping stayed in the basin where it started. Neighboring local minima of ff are about 2π2\pi apart, and jumps of the default size 0.5 lead back to the same minimum. Jumps of about half the distance between minima can reach the neighboring basins:

Here’s the same problem using opt.dual_annealing and opt.differential_evolution, which search a box given by bounds instead of starting from a point:

Both find the global minimum. They need bounds but no starting point. All of these global methods are expensive: differential evolution used about 500 evaluations of ff, the multistart about 700, basin hopping about 2500, and dual annealing about 4000, against 30 for the local minimization from (5,5)(5, 5). None of them can guarantee that the minimum it returns is global. They are a good choice when ff is cheap to evaluate and there are few variables.

Finding Roots

A root of a function f:Rm→Rnf: \mathbb{R}^m \to \mathbb{R}^n is a point xx so that f(x)=0f(x) = 0. The go-to function for this is opt.root

for scalar functions, you can also use root_scalar

You can also find roots of multi-valued functions. E.g. if we want to solve the nonlinear system

x0cos⁡(x1)=4,x0x1−x1=5x_0 \cos(x_1) = 4, \quad x_0 x_1 - x_1 = 5

we can seek to find a root

x0cos⁡(x1)−4=0,x0x1−x1−5=0x_0 \cos(x_1) - 4 = 0, \quad x_0 x_1 - x_1 - 5 = 0

You can also specify the Jacobian for faster convergence (in this case, the Jacobian is 2×22 \times 2)

We see that the computed root in this case satisfies the equations more precisely.

Exercise

Compute a root of the above example using opt.minimize instead of opt.root. One way to do this is to minimize ∥f(x)∥\|f(x)\|. Do the results differ if you use a 1-norm vs a 2-norm?

Above examples: find roots of multi-valued functions. E.g. if we want to solve the nonlinear system

x0cos⁡(x1)=4x_0 \cos(x_1) = 4
x0x1−x1=5x_0 x_1 - x_1 = 5

As we can see from the result, 1-norm result and 2-norm result are slightly different. But they are both very close to the result computed by opt.root.