The scipy.optimize package provides several commonly used
optimization algorithms. A detailed listing is available:
scipy.optimize (can also be found by help(scipy.optimize)).
Local minimization of multivariate scalar functions (minimize)
The function provides a common interface to unconstrained
and constrained minimization algorithms for multivariate scalar functions
in . To demonstrate the minimization function, consider the
problem of minimizing the Rosenbrock function of variables:
The minimum value of this function is 0 which is achieved when
xi=1.
Note that the Rosenbrock function and its derivatives are included in
scipy.optimize. The implementations shown in the following sections
provide examples of how to define an objective function as well as its
jacobian and hessian functions. Objective functions in scipy.optimize
expect a numpy array as their first parameter which is to be optimized
and must return a float value. The exact calling signature must be
f(x,*args) where x represents a numpy array and args
a tuple of additional arguments supplied to the objective function.
The simplex algorithm is probably the simplest way to minimize a fairly
well-behaved function. It requires only function evaluations and is a good
choice for simple minimization problems. However, because it does not use
any gradient evaluations, it may take longer to find the minimum.
Another optimization algorithm that needs only function calls to find
the minimum is Powell’s method available by setting method='powell' in
minimize.
To demonstrate how to supply additional arguments to an objective function,
let us minimize the Rosenbrock function with an additional scaling factor a
and an offset b:
f(x,a,b)=i=1∑N−1a(xi+1−xi2)2+(1−xi)2+b.
Again using the minimize routine this can be solved by the following
code block for the example parameters a=0.5 and b=1.
>>> defrosen_with_args(x,a,b):... """The Rosenbrock function with additional arguments"""... returnsum(a*(x[1:]-x[:-1]**2.0)**2.0
As an alternative to using the args parameter of minimize, simply
wrap the objective function in a new function that accepts only x. This
approach is also useful when it is necessary to pass additional parameters to
the objective function as keyword arguments.
>>> defrosen_with_args(x,a,*,b):# b is a keyword-only argument... returnsum(a*(x[1:]-x[:-1]**2.0)**2.0
In order to converge more quickly to the solution, this routine uses
the gradient of the objective function. If the gradient is not given
by the user, then it is estimated using first-differences. The
Broyden-Fletcher-Goldfarb-Shanno (BFGS) method typically requires
fewer function calls than the simplex algorithm even when the gradient
must be estimated.
To demonstrate this algorithm, the Rosenbrock function is again used.
The gradient of the Rosenbrock function is the vector:
Newton-Conjugate Gradient algorithm is a modified Newton’s
method and uses a conjugate gradient algorithm to (approximately) invert
the local Hessian [NW]. Newton’s method is based on fitting the function
locally to a quadratic form:
The Newton-CG method is a line search method: it finds a direction
of search minimizing a quadratic approximation of the function and then uses
a line search algorithm to find the (nearly) optimal step size in that direction.
An alternative approach is to, first, fix the step size limit Δ and then find the
optimal step p inside the given trust-radius by solving
the following quadratic subproblem:
\begin{eqnarray*}
\min_{\mathbf{p}} f\left(\mathbf{x}_{k}\right)+\nabla f\left(\mathbf{x}_{k}\right)\cdot\mathbf{p}+\frac{1}{2}\mathbf{p}^{T}\mathbf{H}\left(\mathbf{x}_{k}\right)\mathbf{p};&\\
\text{subject to: } \|\mathbf{p}\|\le \Delta.&
\end{eqnarray*}
The solution is then updated xk+1=xk+p and
the trust-radius is adjusted according to the degree of agreement of the quadratic
model with the real function. This family of methods is known as trust-region methods.
The algorithm is a trust-region method that uses a conjugate gradient algorithm
to solve the trust-region subproblem .
Similar to the trust-ncg method, the trust-krylov method is a method
suitable for large-scale problems as it uses the hessian only as linear
operator by means of matrix-vector products.
It solves the quadratic subproblem more accurately than the trust-ncg
method.
\begin{eqnarray*}
\min_{\mathbf{p}} f\left(\mathbf{x}_{k}\right)+\nabla f\left(\mathbf{x}_{k}\right)\cdot\mathbf{p}+\frac{1}{2}\mathbf{p}^{T}\mathbf{H}\left(\mathbf{x}_{k}\right)\mathbf{p};&\\
\text{subject to: } \|\mathbf{p}\|\le \Delta.&
\end{eqnarray*}
This method wraps the [TRLIB] implementation of the [GLTR] method solving
exactly a trust-region subproblem restricted to a truncated Krylov subspace.
For indefinite problems it is usually better to use this method as it reduces
the number of nonlinear iterations at the expense of few more matrix-vector
products per subproblem solve in comparison to the method.
All methods Newton-CG, trust-ncg and trust-krylov are suitable for dealing with
large-scale problems (problems with thousands of variables). That is because the conjugate
gradient algorithm approximately solve the trust-region subproblem (or invert the Hessian)
by iterations without the explicit Hessian factorization. Since only the product of the Hessian
with an arbitrary vector is needed, the algorithm is specially suited for dealing
with sparse Hessians, allowing low storage requirements and significant time savings for
those sparse problems.
For medium-size problems, for which the storage and factorization cost of the Hessian are not critical,
it is possible to obtain a solution within fewer iteration by solving the trust-region subproblems
almost exactly. To achieve that, a certain nonlinear equations is solved iteratively for each quadratic
subproblem [CGT]. This solution requires usually 3 or 4 Cholesky factorizations of the
Hessian matrix. As the result, the method converges in fewer number of iterations
and takes fewer evaluations of the objective function than the other implemented
trust-region methods. The Hessian product option is not supported by this algorithm. An
example using the Rosenbrock function follows:
Constrained minimization
The minimize function provides several algorithms for constrained minimization,
namely 'trust-constr' , 'SLSQP', 'COBYLA', and 'COBYQA'. They require the constraints
to be defined using slightly different structures. The methods 'trust-constr', 'COBYQA', and 'COBYLA' require
the constraints to be defined as a sequence of objects LinearConstraint and
NonlinearConstraint. Method 'SLSQP', on the other hand,
requires constraints to be defined as a sequence of dictionaries, with keys
type, fun and jac.
As an example let us consider the constrained minimization of the Rosenbrock function:
When cjl=cju the method reads the -th constraint as an
equality constraint and deals with it accordingly. Besides that, one-sided constraint
can be specified by setting the upper or lower bound to with the appropriate sign.
Sequential Least SQuares Programming (SLSQP) Algorithm (method='SLSQP')
The SLSQP method deals with constrained minimization problems of the form:
Where E or I are sets of indices
containing equality and inequality constraints.
Both linear and nonlinear constraints are defined as dictionaries with keys type, fun and .
Local minimization solver comparison
Find a solver that meets your requirements using the table below.
If there are multiple candidates, try several and see which ones best
meet your needs (e.g. execution time, objective function value).
Solver
Bounds Constraints
Nonlinear Constraints
Uses Gradient
Uses Hessian
Utilizes Sparsity
CG
✓
BFGS
✓
dogleg
✓
✓
trust-ncg
✓
✓
trust-krylov
✓
✓
trust-exact
✓
✓
Newton-CG
✓
✓
✓
Nelder-Mead
✓
Powell
✓
L-BFGS-B
✓
✓
TNC
✓
✓
COBYLA
✓
✓
COBYQA
✓
✓
SLSQP
✓
✓
✓
trust-constr
✓
✓
✓
✓
✓
Global optimization
Global optimization aims to find the global minimum of a function within given
bounds, in the presence of potentially many local minima. Typically, global
minimizers efficiently search the parameter space, while using a local
minimizer (e.g., minimize) under the hood. SciPy contains a
number of good global optimizers. Here, we’ll use those on the same objective
function, namely the (aptly named) eggholder function:
We now use the global optimizers to obtain the minimum and the function value
at the minimum. We’ll store the results in a dictionary so we can compare
different optimization results later.
>>> results['DA']=optimize.dual_annealing(eggholder,bounds)>>> results['DA'] fun: -956.9182316237413 # may vary message: ['Maximum number of iteration reached'] nfev: 4091 nhev: 0 nit: 1000 njev: 0 x: array([482.35324114, 432.87892901])
All optimizers return an OptimizeResult, which in addition to the solution
contains information on the number of function evaluations, whether the
optimization was successful, and more. For brevity, we won’t show the full
output of the other optimizers:
Find a solver that meets your requirements using the table below.
If there are multiple candidates, try several and see which ones best
meet your needs (e.g. execution time, objective function value).
SciPy is capable of solving robustified bound-constrained nonlinear
least-squares problems:
xmin21i=1∑mρ(fi(x)2)subject to lb≤x≤ub
Here fi(x) are smooth functions from
Rn to R, we refer to them as residuals.
The purpose of a scalar-valued function ρ(⋅) is to reduce the
influence of outlier residuals and contribute to robustness of the solution,
we refer to it as a loss function. A linear loss function gives a standard
least-squares problem. Additionally, constraints in a form of lower and upper
bounds on some of are allowed.
All methods specific to least-squares minimization utilize a m×n
matrix of partial derivatives called Jacobian and defined as
Jij=∂fi/∂xj. It is highly recommended to
compute this matrix analytically and pass it to ,
otherwise, it will be estimated by finite differences, which takes a lot of
additional time and can be very inaccurate in hard cases.
Function least_squares can be used for fitting a function
φ(t;x) to empirical data {(ti,yi),i=0,…,m−1}.
To do this, one should simply precompute residuals as
, where
are weights assigned to each observation.
Example of solving a fitting problem
Here we consider an enzymatic reaction [1]. There are 11 residuals defined as
Often only the minimum of a univariate function (i.e., a function that
takes a scalar as input) is needed. In these circumstances, other
optimization techniques have been developed that can work faster. These are
accessible from the minimize_scalar function, which proposes several
algorithms.
Unconstrained minimization (method='brent')
There are, actually, two methods that can be used to minimize a univariate
function: brent and golden, but golden is included only for academic
purposes and should rarely be used. These can be respectively selected
through the method parameter in minimize_scalar. The brent
method uses Brent’s algorithm for locating a minimum. Optimally, a bracket
(the bracket parameter) should be given which contains the minimum desired. A
bracket is a triple (a,b,c) such that f(a)>f(b)<f(c) and a<b<c . If this is not given, then alternatively two starting points can
be chosen and a bracket will be found from these points using a simple
marching algorithm. If these two starting points are not provided, 0 and
1 will be used (this may not be the right choice for your function and
result in an unexpected minimum being returned).
Very often, there are constraints that can be placed on the solution space
before minimization occurs. The bounded method in minimize_scalar
is an example of a constrained minimization procedure that provides a
rudimentary interval constraint for scalar functions. The interval
constraint allows the minimization to occur only between two fixed
endpoints, specified using the mandatory bounds parameter.
For example, to find the minimum of J1(x) near
x=5 , can be called using the interval
as a constraint. The result is
:
Custom minimizers
Sometimes, it may be useful to use a custom method as a (multivariate
or univariate) minimizer, for example, when using some library wrappers
of minimize (e.g., basinhopping).
We can achieve that by, instead of passing a method name, passing
a callable (either a function or an object implementing a __call__
method) as the method parameter.
Let us consider an (admittedly rather virtual) need to use a trivial
custom multivariate minimization method that will just search the
neighborhood in each dimension independently with a fixed step size:
If one has a single-variable equation, there are multiple different root
finding algorithms that can be tried. Most of these algorithms require the
endpoints of an interval in which a root is expected (because the function
changes signs). In general, brentq is the best choice, but the other
methods may be useful in certain circumstances or for academic purposes.
When a bracket is not available, but one or more derivatives are available,
then newton (or halley, secant) may be applicable.
This is especially the case if the function is defined on a subset of the
complex plane, and the bracketing methods cannot be used.
Fixed-point solving
A problem closely related to finding the zeros of a function is the
problem of finding a fixed point of a function. A fixed point of a
function is the point at which evaluation of the function returns the
point: g(x)=x. Clearly, the fixed point of g
is the root of f(x)=g(x)−x.
Equivalently, the root of f is the fixed point of
g(x)=f(x)+x. The routine
fixed_point provides a simple iterative method using Aitkens
sequence acceleration to estimate the fixed point of g given a
starting point.
Sets of equations
Finding a root of a set of non-linear equations can be achieved using the
root function. Several methods are available, amongst which hybr
(the default) and lm, which, respectively, use the hybrid method of Powell
and the Levenberg-Marquardt method from MINPACK.
The following example considers the single-variable transcendental
equation
x+2cos(x)=0,
Root finding for large problems
Methods hybr and lm in root cannot deal with a very large
number of variables (N), as they need to calculate and invert a dense N
x N Jacobian matrix on every Newton step. This becomes rather inefficient
when N grows.
Consider, for instance, the following problem: we need to solve the
following integrodifferential equation on the square
[0,1]×[0,1]:
(∂x2+∂y2)P+5(∫01∫01cosh(P)dxdy)2=0
Still too slow? Preconditioning.
When looking for the zero of the functions fi(x)=0,
i = 1, 2, …, N, the krylov solver spends most of the
time inverting the Jacobian matrix,
The function linprog can minimize a linear objective function
subject to linear equality and inequality constraints. This kind of
problem is well known as linear programming. Linear programming solves
problems of the following form:
Consider the problem of selecting students for a swimming medley relay team.
We have a table showing times for each swimming style of five students:
Student
backstroke
breaststroke
butterfly
freestyle
A
43.5
47.1
48.4
38.2
B
45.5
42.1
49.6
36.8
C
43.4
39.1
42.1
43.2
D
46.5
44.1
44.5
41.2
E
46.3
47.8
50.4
37.2
We need to choose a student for each of the four swimming styles such that
the total relay time is minimized.
This is a typical linear sum assignment problem. We can use linear_sum_assignment to solve it.
The linear sum assignment problem is one of the most famous combinatorial optimization problems.
Given a “cost matrix” C, the problem is to choose
exactly one element from each row
without choosing more than one element from any column
such that the sum of the chosen elements is minimized
In other words, we need to assign each row to one column such that the sum of
the corresponding entries is minimized.
Formally, let X be a boolean matrix where X[i,j] = 1 iff row i is assigned to column j.
Then the optimal assignment has cost
\min \sum_i \sum_j C_{i,j} X_{i,j}
The first step is to define the cost matrix.
In this example, we want to assign each swimming style to a student.
linear_sum_assignment is able to assign each row of a cost matrix to a column.
Therefore, to form the cost matrix, the table above needs to be transposed so that the rows
correspond with swimming styles and the columns correspond with students:
Note that this result is not the same as the sum of the minimum times for each swimming style:
>>> np.min(cost,axis=1).sum()161.39999999999998
because student “C” is the best swimmer in both “breaststroke” and “butterfly” style.
We cannot assign student “C” to both styles, so we assigned student C to the “breaststroke” style
and D to the “butterfly” style to minimize the total time.
References
Some further reading and related software, such as Newton-Krylov [KK],
PETSc [PP], and PyAMG [AMG]:
The knapsack problem is a well known combinatorial optimization problem.
Given a set of items, each with a size and a value, the problem is to choose
the items that maximize the total value under the condition that the total size
is below a certain threshold.
Formally, let
x_i be a boolean variable that indicates whether item i is
included in the knapsack,
Although the objective function and inequality constraints are linear in the
decision variablesx_i, this differs from a typical linear
programming problem in that the decision variables can only assume integer
values. Specifically, our decision variables can only be 0 or
1, so this is known as a binary integer linear program (BILP). Such
a problem falls within the larger class of mixed integer linear programs
(MILPs), which we we can solve with milp.
In our example, there are 8 items to choose from, and the size and value of
each is specified as follows.
We need to constrain our eight decision variables to be binary. We do so
by adding a Bounds: constraint to ensure that they lie between
0 and 1, and we apply “integrality” constraints to ensure that
they are either0or1.
If we are following the usual rules of linear algebra, the input A should
be a two-dimensional matrix, and the lower and upper bounds lb and ub
should be one-dimensional vectors, but LinearConstraint is forgiving
as long as the inputs can be broadcast to consistent shapes.
Using the variables defined above, we can solve the knapsack problem using
milp. Note that milp minimizes the objective function, but we
want to maximize the total value, so we set c to be negative of the values.
This means that we should select the items 1, 2, 4, 5, 6 to optimize the total
value under the size constraint. Note that this is different from we would have
obtained had we solved the linear programming relaxation (without integrality
constraints) and attempted to round the decision variables.
If we were to round this solution up to
array([1.,1.,1.,1.,1.,1.,0.,0.]), our knapsack would be over the
capacity constraint, whereas if we were to round down to
array([1.,1.,1.,1.,0.,1.,0.,0.]), we would have a sub-optimal
solution.
For more MILP tutorials, see the Jupyter notebooks on SciPy Cookbooks:
Some SciPy optimization methods, such as differential_evolution, offer
parallelization through the use of a workers keyword.
For differential_evolution there are two loops (iteration) levels in the
algorithm. The outer loop represents successive generations of a population. This
loop can’t be parallelized. For a given generation candidate solutions are generated
that have to be compared against existing population members. The fitness of the
candidate solution can be done in a loop, but it’s also possible to parallelize the
calculation.
Parallelization is also possible in other optimization algorithms. For example in
various minimize methods numerical differentiation is used to estimate
derivatives. For a simple gradient calculation using two-point forward differences a
total of N+1 objective function calculations have to be done, where N is the
number of parameters. These are just small perturbations around a given location
(the +1). Those N+1 calculations are also parallelizable. The calculation of
numerical derivatives are used by the minimization algorithm to generate new steps.
Each optimization algorithm is quite different in how they work, but they often have
locations where multiple objective function calculations are required before the
algorithm does something else. Those locations are what can be parallelized.
There are therefore common characteristics in how workers is used. These
commonalities are described below.
If an int is supplied then a multiprocessing.Pool is
created, with the object’s map method being used to evaluate solutions in
parallel. With this approach it is mandatory that the objective function is pickleable.
Lambda functions do not meet that requirement.
>>> importnumpyasnp>>> fromscipy.optimizeimportrosen,differential_evolution,Bounds>>> bnds=Bounds([0.,0.,0.],[10.,10.,10.])>>> res
It is also possible to use a map-like callable as a worker. Here the map-like function
is provided with a series of vectors that the optimization algorithm provides.
The map-like function needs to evaluate each vector against the objective function.
In the following example we use multiprocessing.Pool
as the map-like. As before, the objective function still needs to be pickleable.
This example is semantically identical to the previous example.
It can be an advantage to use this pattern because the Pool can be re-used for further
calculations - there is a significant amount of overhead in creating those objects.
Alternatives to multiprocessing.Pool include the
mpi4py package, which enables parallel
processing on clusters.
In Scipy 1.16.0 the workers keyword was introduced to selected minimize
methods. Here parallelization is typically applied during numerical differentiation.
Either of the two approaches outlined above can be used, although it’s strongly
advised to supply the map-like callable due to the overhead of creating new processes.
Performance gains will only be made if the objective function is expensive to
calculate.
Let’s compare how much parallelization can help compared to the serial version. To
simulate a slow function we use the time package.
In[1]: rng = np.random.default_rng()In[2]: x0 = rng.uniform(low=0.0, high=10.0, size=(20,))In[3]:%timeit minimize(slow_func, x0, method='L-BFGS-B')# serial approach365 ms ± ms per loop mean ± std dev of runs loop each
Now the parallel version:
In [4]: with Pool() as pwl: # parallel approach
... %timeit minimize(slow_func, x0, method='L-BFGS-B', options={'workers':pwl.map})
70.5 ms ± 146 μs per loop (mean ± std. dev. of 7 runs, 1 loop each) # may vary
If the objective function can be vectorized, then a map-like can be used to take
advantage of vectorization during function evaluation. Vectorization means that the
objective function can carry out the required calculations in a single (rather than
multiple) call, which is typically very efficient:
In[5]:defvectorized_maplike(fun, iterable):... arr = np.array([i for i initer(iterable)])# arr.shape = (S, N)... arr_t = arr.T # arr_t.shape = (N, S)... r =slow_func(arr_t)# calculation vectorized over S... r
There are several important points to note about this example:
The iterable represents the series of parameter vectors that the algorithm wishes
to be evaluated.
The iterable is first converted to an iterator, before being made into an array via
a list comprehension. This allows the iterable to be a generator, list, array, etc.
Within the map-like the calculation is done using slow_func instead of using
fun. The map-like is actually supplied with a wrapped version of the objective
function. The wrapping is used to detect various types of common user errors,
including checking whether the objective function returns a scalar. If fun is
used then a RuntimeError will result, because fun(arr_t) will be a 1-D
array and not a scalar. We therefore use slow_func directly.
arr.T is sent to the objective function. This is because ,
where is the number of parameter vectors to evaluate and is the number of
variables. For vectorization occurs on shaped arrays.
[:
-
1
])
**
2.0
)
1e-8
,
'disp'
:
True
})
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 339
Function evaluations: 571
+
(
1
-
x
[:
-
1
])
**
2.0
)
+
b
,
1.
),
options
=
{
'xatol'
:
1e-8
,
'disp'
:
True
})
Optimization terminated successfully.
Current function value: 1.000000
Iterations: 319 # may vary
Function evaluations: 525 # may vary
+
(
1
-
x
[:
-
1
])
**
2.0
)
+
b
>>>
def
wrapped_rosen_without_args
(
x
):
...
return
rosen_with_args
(
x
,
0.5
,
b
=
1.
)
# pass in `a` and `b`
>>>
x0
=
np
.
array
([
1.3
,
0.7
,
0.8
,
1.9
,
1.2
])
>>>
res
=
minimize
(
wrapped_rosen_without_args
,
x0
,
method
=
'nelder-mead'
,
...
options
=
{
'xatol'
:
1e-8
,})
>>>
print
(
res
.
x
)
[1. 1. 1. 1. 0.99999999]
options
=
{
'xatol'
:
1e-8
,})
>>>
print
(
res
.
x
)
[1. 1. 1. 1. 0.99999999]
def
rosen_der
(
x
):
...
xm
=
x
[
1
:
-
1
]
...
xm_m1
=
x
[:
-
2
]
...
xm_p1
=
x
[
2
:]
...
der
=
np
.
zeros_like
(
x
)
...
der
[
1
:
-
1
]
=
200
*
(
xm
-
xm_m1
**
2
)
-
400
*
(
xm_p1
-
xm
**
2
)
*
xm
-
2
*
(
1
-
xm
)
...
der
[
0
]
=
-
400
*
x
[
0
]
*
(
x
[
1
]
-
x
[
0
]
**
2
)
-
2
*
(
1
-
x
[
0
])
...
der
[
-
1
]
=
200
*
(
x
[
-
1
]
-
x
[
-
2
]
**
2
)
...
return
der
This gradient information is specified in the minimize function
through the jac parameter as illustrated below.
>>> res=minimize(rosen,x0,method='BFGS',jac=rosen_der,... options={'disp':True})Optimization terminated successfully. Current function value: 0.000000 Iterations: 25 # may vary Function evaluations: 30 Gradient evaluations: 30>>> res.xarray([1., 1., 1., 1., 1.])
Avoiding Redundant Calculation
It is common for the objective function and its gradient to share parts of the
calculation. For instance, consider the following problem.
>>> deff(x):... return-expensive(x[0])**2>>>>>> defdf(x):... return-2*expensive(x[0])*dexpensive(x[0])>>>>>> defexpensive(x):... # this function is computationally expensive!... expensive.count+=1# let's keep track of how many times it runs... returnnp.sin(x)>>> expensive.count=0>>>>>> defdexpensive(x):... returnnp.cos(x)>>>>>> res=minimize(f,0.5,jac=df)>>> res.fun-0.9999999999999174>>> res.nfev,res.njev6, 6>>> expensive.count12
Here, expensive is called 12 times: six times in the objective function and
six times from the gradient. One way of reducing redundant calculations is to
create a single function that returns both the objective function and the
gradient.
When we call minimize, we specify jac==True to indicate that the provided
function returns both the objective function and its gradient. While
convenient, not all scipy.optimize functions support this feature,
and moreover, it is only for sharing calculations between the function and its
gradient, whereas in some problems we will want to share calculations with the
Hessian (second derivative of the objective function) and constraints. A more
general approach is to memoize the expensive parts of the calculation. In
simple situations, this can be accomplished with the
functools.lru_cache wrapper.
>>> fromfunctoolsimportlru_cache>>> expensive.count=0# reset the counter>>> expensive=lru_cache(expensive)>>> res=minimize(f,0.5,jac=df)>>> res.fun-0.9999999999999174>>> expensive.count6
where H(x0) is a matrix of second-derivatives (the Hessian). If the Hessian is
positive definite then the local minimum of this function can be found
by setting the gradient of the quadratic form to zero, resulting in
xopt=x0−H−1∇f.
The inverse of the Hessian is evaluated using the conjugate-gradient
method. An example of employing this method to minimizing the
Rosenbrock function is given below. To take full advantage of the
Newton-CG method, a function which computes the Hessian must be
provided. The Hessian matrix itself does not need to be constructed,
only a vector which is the product of the Hessian with an arbitrary
vector needs to be available to the minimization routine. As a result,
the user can provide either a function to compute the Hessian matrix,
or a function to compute the product of the Hessian with an arbitrary
vector.
>>> res=minimize(rosen,x0,method='Newton-CG',... jac=rosen_der,hess=rosen_hess,... options={'xtol':1e-8,'disp':True})Optimization terminated successfully. Current function value: 0.000000 Iterations: 19 # may vary Function evaluations: 22 Gradient evaluations: 19 Hessian evaluations: 19>>> res.xarray([1., 1., 1., 1., 1.])
Hessian product example
For larger minimization problems, storing the entire Hessian matrix can
consume considerable time and memory. The Newton-CG algorithm only needs
the product of the Hessian times an arbitrary vector. As a result, the user
can supply code to compute this product rather than the full Hessian by
giving a hess function which take the minimization vector as the first
argument and the arbitrary vector as the second argument (along with extra
arguments passed to the function to be minimized). If possible, using
Newton-CG with the Hessian product option is probably the fastest way to
minimize the function.
In this case, the product of the Rosenbrock Hessian with an arbitrary
vector is not difficult to compute. If p is the arbitrary
vector, then H(x)p has
elements:
>>> res=minimize(rosen,x0,method='Newton-CG',... jac=rosen_der,hessp=rosen_hess_p,... options={'xtol':1e-8,'disp':True})Optimization terminated successfully. Current function value: 0.000000 Iterations: 20 # may vary Function evaluations: 23 Gradient evaluations: 20 Hessian evaluations: 44>>> res.xarray([1., 1., 1., 1., 1.])
According to [NW] p. 170 the Newton-CG algorithm can be inefficient
when the Hessian is ill-conditioned because of the poor quality search directions
provided by the method in those situations. The method trust-ncg,
according to the authors, deals more effectively with this problematic situation
and will be described next.
F. Lenders, C. Kirches, A. Potschka: “trlib: A vector-free
implementation of the GLTR method for iterative solution of
the trust region problem”, arXiv:1611.04718
N. Gould, S. Lucidi, M. Roma, P. Toint: “Solving the
Trust-Region Subproblem using the Lanczos Method”,
SIAM J. Optim., 9(2), 504–525, (1999).
DOI:10.1137/S1052623497322735
Conn, A. R., Gould, N. I., & Toint, P. L.
“Trust region methods”. Siam. (2000). pp. 169-200.
j
np.inf
The implementation is based on [EQSQP] for equality-constraint problems and on [TRIP]
for problems with inequality constraints. Both are trust-region type algorithms suitable
for large-scale problems.
Defining Bounds Constraints
The bound constraints 0≤x0≤1 and −0.5≤x1≤2.0
are defined using a Bounds object.
When the evaluation of the Hessian H(x,v)
is difficult to implement or computationally infeasible, one may use HessianUpdateStrategy.
Currently available strategies are BFGS and SR1.
The Jacobian of the constraints can be approximated by finite differences as well. In this case,
however, the Hessian cannot be computed with finite differences and needs to
be provided by the user or defined using HessianUpdateStrategy.
Solving the Optimization Problem
The optimization problem is solved using:
>>> x0=np.array([0.5,0])>>> res=minimize(rosen,x0,method='trust-constr',jac=rosen_der,hess=rosen_hess,... constraints=[linear_constraint,nonlinear_constraint],... options={'verbose':1},bounds=bounds)# may vary`gtol` termination condition is satisfied.Number of iterations: 12, function evaluations: 8, CG iterations: 7, optimality: 2.99e-09, constraint violation: 1.11e-16, execution time: 0.016 s.>>> print(res.x)[0.41494531 0.17010937]
When needed, the objective function Hessian can be defined using a LinearOperator object,
>>> defrosen_hess_linop(x):... defmatvec(p):... returnrosen_hess_p(x,p)... returnLinearOperator((2,2),matvec=matvec)>>> res=minimize(rosen,x0,method='trust-constr',jac=rosen_der,hess=rosen_hess_linop,... constraints=[linear_constraint,nonlinear_constraint],... options={'verbose':1},bounds=bounds)# may vary`gtol` termination condition is satisfied.Number of iterations: 12, function evaluations: 8, CG iterations: 7, optimality: 2.99e-09, constraint violation: 1.11e-16, execution time: 0.018 s.>>> print(res.x)[0.41494531 0.17010937]
or a Hessian-vector product through the parameter hessp.
>>> res=minimize(rosen,x0,method='trust-constr',jac=rosen_der,hessp=rosen_hess_p,... constraints=[linear_constraint,nonlinear_constraint],... options={'verbose':1},bounds=bounds)# may vary`gtol` termination condition is satisfied.Number of iterations: 12, function evaluations: 8, CG iterations: 7, optimality: 2.99e-09, constraint violation: 1.11e-16, execution time: 0.018 s.>>> print(res.x)[0.41494531 0.17010937]
Alternatively, the first and second derivatives of the objective function can be approximated.
For instance, the Hessian can be approximated with SR1 quasi-Newton approximation
and the gradient with finite differences.
>>> fromscipy.optimizeimportSR1>>> res=minimize(rosen,x0,method='trust-constr',jac="2-point",hess=SR1(),... constraints=[linear_constraint,nonlinear_constraint],... options={'verbose':1},bounds=bounds)# may vary`gtol` termination condition is satisfied.Number of iterations: 12, function evaluations: 24, CG iterations: 7, optimality: 4.48e-09, constraint violation: 0.00e+00, execution time: 0.016 s.>>> print(res.x)[0.41494531 0.17010937]
Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999.
An interior point algorithm for large-scale nonlinear programming.
SIAM Journal on Optimization 9.4: 877-900.
Lalee, Marucha, Jorge Nocedal, and Todd Plantega. 1998. On the
implementation of an algorithm for large-scale equality constrained
optimization. SIAM Journal on Optimization 8.3: 682-706.
where yi are measurement values and ui are values of
the independent variable. The unknown vector of parameters is
x=(x0,x1,x2,x3)T. As was said previously, it is
recommended to compute Jacobian matrix in a closed form:
We are going to use the “hard” starting point defined in [2]. To find a
physically meaningful solution, avoid potential division by zero and assure
convergence to the global minimum we impose constraints
0≤xj≤100,j=0,1,2,3.
The code below implements least-squares estimation of x and
finally plots the original data and the fitted model function:
We define the objective function so that it also returns the Jacobian and
indicate this by setting the jac parameter to True. Also, the
Levenberg-Marquardt solver is used here.
with the boundary condition P(x,1)=1 on the upper edge and
P=0 elsewhere on the boundary of the square. This can be done
by approximating the continuous function P by its values on a grid,
Pn,m≈P(nh,mh), with a small grid spacing
h. The derivatives and integrals can then be approximated; for
instance ∂x2P(x,y)≈(P(x+h,y)−2P(x,y)+P(x−h,y))/h2. The problem is then equivalent to finding the root of
some function residual(P), where P is a vector of length
NxNy.
Now, because NxNy can be large, methods hybr or lm in
root will take a long time to solve this problem. The solution can,
however, be found using one of the large-scale solvers, for example
krylov, broyden2, or anderson. These use what is known as the
inexact Newton method, which instead of computing the Jacobian matrix
exactly, forms an approximation for it.
If you have an approximation for the inverse matrix
M≈J−1, you can use it for preconditioning the
linear-inversion problem. The idea is that instead of solving
Js=y one solves MJs=My: since
matrix MJ is “closer” to the identity matrix than J
is, the equation should be easier for the Krylov method to deal with.
The matrix M can be passed to root with method krylov as an
option options['jac_options']['inner_M']. It can be a (sparse) matrix
or a scipy.sparse.linalg.LinearOperator instance.
For the problem in the previous section, we note that the function to
solve consists of two parts: the first one is the application of the
Laplace operator, [∂x2+∂y2]P, and the second
is the integral. We can actually easily compute the Jacobian corresponding
to the Laplace operator part: we know that in 1-D
∂x2≈hx21−210…1−2101−20⋯0⋯1⋯=hx−2L
so that the whole 2-D operator is represented by
J1=∂x2+∂y2≃hx−2L⊗I+hy−2I⊗L
The matrix J2 of the Jacobian corresponding to the integral
is more difficult to calculate, and since all of it entries are
nonzero, it will be difficult to invert. J1 on the other hand
is a relatively simple matrix, and can be inverted by
scipy.sparse.linalg.splu (or the inverse can be approximated by
scipy.sparse.linalg.spilu). So we are content to take
M≈J1−1 and hope for the best.
In the example below, we use the preconditioner M=J1−1.
fromscipy.optimizeimportrootfromscipy.sparseimportdia_array,kronfromscipy.sparse.linalgimportspilu,LinearOperatorfromnumpyimportcosh,zeros_like,mgrid,zeros,eye# parametersnx,ny=75,75hx,hy=1./(nx-1),1./(ny-1)P_left,P_right=0,0P_top,P_bottom=1,0defget_preconditioner():"""Compute the preconditioner M"""diags_x=zeros((3,nx))diags_x[0,:]=1/hx/hxdiags_x[1,:]=-2/hx/hxdiags_x[2,:]=1/hx/hxLx=dia_array((diags_x,[-1,0,1]),shape=(nx,nx))diags_y=zeros((3,ny))diags_y[0,:]=1/hy/hydiags_y[1,:]=-2/hy/hydiags_y[2,:]=1/hy/hyLy=dia_array((diags_y,[-1,0,1]),shape=(ny,ny))J1=kron(Lx,eye(ny))+kron(eye(nx),Ly)# Now we have the matrix `J_1`. We need to find its inverse `M` --# however, since an approximate inverse is enough, we can use# the *incomplete LU* decompositionJ1_ilu=spilu(J1)# This returns an object with a method .solve() that evaluates# the corresponding matrix-vector product. We need to wrap it into# a LinearOperator before it can be passed to the Krylov methods:M=LinearOperator(shape=(nx*ny,nx*ny),matvec=J1_ilu.solve)returnMdefsolve(preconditioning=True):"""Compute the solution"""count=[0]defresidual(P):count[0]+=1d2x=zeros_like(P)d2y=zeros_like(P)d2x[1:-1]=(P[2:]-2*P[1:-1]+P[:-2])/hx/hxd2x[0]=(P[1]-2*P[0]+P_left)/hx/hxd2x[-1]=(P_right-2*P[-1]+P[-2])/hx/hxd2y[:,1:-1]=(P[:,2:]-2*P[:,1:-1]+P[:,:-2])/hy/hyd2y[:,0]=(P[:,1]-2*P[:,0]+P_bottom)/hy/hyd2y[:,-1]=(P_top-2*P[:,-1]+P[:,-2])/hy/hyreturnd2x+d2y+5*cosh(P).mean()**2# preconditionerifpreconditioning:M=get_preconditioner()else:M=None# solveguess=zeros((nx,ny),float)sol=root(residual,guess,method='krylov',options={'disp':True,'jac_options':{'inner_M':M}})print('Residual',abs(residual(sol.x)).max())print('Evaluations',count[0])returnsol.xdefmain():sol=solve(preconditioning=True)# visualizeimportmatplotlib.pyplotaspltx,y=mgrid[0:1:(nx*1j),0:1:(ny*1j)]plt.clf()plt.pcolor(x,y,sol)plt.clim(0,1)plt.colorbar()plt.show()if__name__=="__main__":main()
Using a preconditioner reduced the number of evaluations of the
residual function by a factor of 4. For problems where the
residual is expensive to compute, good preconditioning can be crucial
— it can even decide whether the problem is solvable in practice or
not.
Preconditioning is an art, science, and industry. Here, we were lucky
in making a simple choice that worked reasonably well, but there is a
lot more depth to this topic than is shown here.
l
u
Aub
Aeq
We need some mathematical manipulations to convert the target problem to the form accepted by linprog.
First of all, let’s consider the objective function.
We want to maximize the objective
function, but linprog can only accept a minimization problem. This is easily remedied by converting the maximize
29x1+45x2 to minimizing −29x1−45x2. Also, x3,x4 are not shown in the objective
function. That means the weights corresponding with x3,x4 are zero. So, the objective function can be
converted to:
x1,x2,x3,x4min−29x1−45x2+0x3+0x4
If we define the vector of decision variables x=[x1,x2,x3,x4]T, the objective weights vector c of linprog in this problem
should be
c=[−29,−45,0,0]T
Next, let’s consider the two inequality constraints. The first one is a “less than” inequality, so it is already in the form accepted by linprog.
The second one is a “greater than” inequality, so we need to multiply both sides by −1 to convert it to a “less than” inequality.
Explicitly showing zero coefficients, we have:
x1−x2−3x3+0x4−2x1+3x2+7x3−3x4≤5≤−10
These equations can be converted to matrix form:
Aubx≤bub
where
Aub=[1−2−13−370−3]
bub=[5−10]
Next, let’s consider the two equality constraints. Showing zero weights explicitly, these are:
2x1+8x2+1x3+0x44x1+4x2+0x3+1x4=60=60
These equations can be converted to matrix form:
Aeqx=beq
where
Aeq=[24841001]
beq=[6060]
Lastly, let’s consider the separate inequality constraints on individual decision variables, which are known as
“box constraints” or “simple bounds”. These constraints can be applied using the bounds argument of linprog.
As noted in the linprog documentation, the default value of bounds is (0,None), meaning that the
lower bound on each decision variable is 0, and the upper bound on each decision variable is infinity:
all the decision variables are non-negative. Our bounds are different, so we will need to specify the lower and upper bound on each
decision variable as a tuple and group these tuples into a list.
Finally, we can solve the transformed problem using linprog.
>>> importnumpyasnp>>> fromscipy.optimizeimportlinprog>>> c=np.array([-29.0,-45.0,0.0,0.0])>>> A_ub=np.array([[1.0,-1.0,-3.0,0.0],... [-2.0,3.0,7.0,-3.0]])>>> b_ub=np.array([5.0,-10.0])>>> A_eq=np.array([[2.0,8.0,1.0,0.0],... [4.0,4.0,0.0,1.0]])>>> b_eq=np.array([60.0,60.0])>>> x0_bounds=(0,None)>>> x1_bounds=(0,5.0)>>> x2_bounds=(-np.inf,0.5)# +/- np.inf can be used instead of None>>> x3_bounds=(-3.0,None)>>> bounds=[x0_bounds,x1_bounds,x2_bounds,x3_bounds]>>> result=linprog(c,A_ub=A_ub,b_ub=b_ub,A_eq=A_eq,b_eq=b_eq,bounds=bounds)>>> print(result.message)The problem is infeasible. (HiGHS Status 8: model_status is Infeasible; primal_status is None)
The result states that our problem is infeasible, meaning that there is no solution vector that satisfies all the
constraints. That doesn’t necessarily mean we did anything wrong; some problems truly are infeasible.
Suppose, however, that we were to decide that our bound constraint on x1 was too tight and that it could be loosened
to 0≤x1≤6. After adjusting our code x1_bounds=(0,6) to reflect the change and executing it again:
The result shows the optimization was successful.
We can check the objective value (result.fun) is same as c^Tx:
>>> x=np.array(result.x)>>> obj=result.fun>>> print(c@x)-505.97435889013434 # may vary>>> print(obj)-505.97435889013434 # may vary
We can also check that all constraints are satisfied within reasonable tolerances:
>>> print(b_ub-(A_ub@x).flatten())# this is equivalent to result.slack[ 6.52747190e-10, -2.26730279e-09] # may vary>>> print(b_eq-(A_eq@x).flatten())# this is equivalent to result.con[ 9.78840831e-09, 1.04662945e-08]] # may vary>>> print([0<=result.x[0],0<=result.x[1]<=6.0,result.x[2]<=0.5,-3.0<=result.x[3]])[True, True, True, True]