Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

SciPy Optimizer

SciPy Optimizer

SciPy's optimize module provides implementations of commonly used numerical optimization and equation-solving algorithms. We can directly call these functions to solve practical problems, such as finding the minimum or maximum of a function, or solving the roots of an equation.

NumPy itself mainly focuses on array computation and linear algebra operations; it provides tools forpolynomial root findingtools (such as numpy.roots), but does not provide a generalnumerical root-finding interface for nonlinear equations. When we need to solve nonlinear equations in general form, we need to use SciPy's optimization module.

For example, the following nonlinear equation:

x + cos(x)

For such problems, you can use the scipy.optimize.root function to solve. The two commonly used core parameters of this function are:

root The function returns a result object (OptimizeResult), which contains information such as the solution status, whether it succeeded, the function value, and the final solution.

The actual solution found is stored in the return object's x attribute, as shown in the example below:

Example

Find x + cos(x) = 0 The root of the equation:

from

scipy.

optimize

import

root

from

math

import

cos

def

eqn

(

x

)

:

   

return

x + cos

(

x

)

myroot

=

root

(

eqn

,

0

)

print

(

myroot.

x

)

View More Information

print(myroot)

After executing the above code, the output is as follows:

[-0.73908513]

If you print the return object directly, you can view more complete solution information:

Example

from

scipy.

optimize

import

root

from

math

import

cos

def

eqn

(

x

)

:

   

return

x + cos

(

x

)

myroot

=

root

(

eqn

,

0

)

print

(

myroot

)

After executing the above code, the output is as follows:



     fjac: array([[-1.]])

      fun: array([0.])

  message: 'The solution converged.'

     nfev: 9

      qtf: array([-2.66786593e-13])

        r: array([-1.67361202])

   status: 1

  success: True

        x: array([-0.73908513])

Where:

Minimizing a Function

In mathematical and engineering problems, a function can usually be represented as a curve, and a curve often has highs and lows.

The high point of a curve is calledMaximum value.

The low point of a curve is calledMinimum value.

The highest point of the entire curve is calledglobal maximum, while the other higher but not highest points are calledlocal maximum.

Similarly, the lowest point of the entire curve is calledglobal minimum, while the other lower but not lowest points are calledlocal minimum.

In SciPy, you can use the scipy.optimize.minimize() function to find the minimum of a function.

minimize() The commonly used parameters of the function are described as follows:

}

Example

Minimize a function using the BFGS method x² + x + 2:

from

scipy.

optimize

import

minimize

def

eqn

(

x

)

:

   

return

x**

2

2

mymin

=

minimize

(

eqn

,

0

,

method

=

'BFGS'

)

print

(

mymin

)

After executing the above code, the output is as follows:



       fun: 1.75

  hess_inv: array([[0.50000001]])

       jac: array([0.])

   message: 'Optimization terminated successfully.'

      nfev: 8

       nit: 2

      njev: 4

    status: 0

   success: True

         x: array([-0.50000001])

From the result, we can see that the function reaches its minimum at x ≈ -0.5 , and the corresponding minimum function value is 1.75, which is consistent with the analytical calculation.

minimize() The function also supports constrained optimization problems and can add constraints parameters to add equality or inequality constraints, suitable for more complex real-world application scenarios.

When the objective function cannot be differentiated directly, you can choose method='Nelder-Mead' and other optimization algorithms that do not require gradient information; such methods gradually approach the optimal solution through simplex search.

In practical use,success field indicates whether the optimization converged successfully, fun field is the optimal objective function value, x field is the optimal solution. It is recommended to always check success status to ensure the solution is reliable.

Advanced Root Finding

Besides root() In addition to the function, SciPy also provides the fsolve() function for solving equation roots; its use is more concise and suitable for quickly solving simple equations.

Example

Use fsolve Solve x + cos(x) = 0:

from

scipy.

optimize

import

fsolve

from

math

import

cos

def

eqn

(

x

)

:

   

return

x + cos

(

x

)

result

=

fsolve

(

eqn

,

0

)

print

(

result

)

After executing the above code, the output is as follows:

[-0.73908513]

fsolve() returns the solution array directly, while root() returns a result object containing more information. For simple scenarios that only need the solution,fsolve is more convenient.

Solving with Multiple Initial Values

For equations with multiple roots, starting from different initial values may yield different roots. The following solves x² - 4 = 0 for its two roots:

Example

from

scipy.

optimize

import

root

def

eqn

(

x

)

:

   

return

x**

2

4

Solve from different initial values

for

guess

in

[

3

,

0

,

3

]

:

    result

=

root

(

eqn

,

guess

)

   

if

result.

success

:

       

print

(

f

"initial guess {guess:2d} -> root: {result.x[0]:.6f}"

)

After executing the above code, the output is as follows:



初始值 -3 -> 根: -2.000000

初始值  0 -> 根:  2.000000

初始值  3 -> 根:  2.000000

Solving Equations with Parameters

In practical problems, equations often contain parameters. We can pass extra parameters to the objective function via the args parameter:

Example

from

scipy.

optimize

import

root

def

eqn

(

x

,

a

,

b

)

:

   

return

a * x + b * cos

(

x

)

Solve 2x + cos(x) = 0

result

=

root

(

eqn

,

0

,

args

=

(

2

,

1

)

)

print

(

f

"solution: {result.x[0]:.6f}"

)

After executing the above code, the output is as follows:

解: -0.450184

Constrained Optimization

minimize() The function supports adding constraints, including equality and inequality constraints. The following is an example of a constrained optimization problem:

Example

Minimize x² + y², subject to the constraint x + y = 1:

from

scipy.

optimize

import

minimize

def

objective

(

x

)

:

   

return

x

[

0

]

**

2

[

1

]

**

2

def

constraint

(

x

)

:

   

return

x

[

0

]

[

1

]

1

Define Constraints

con

=

{

'type'

:

'eq'

,

'fun'

: constraint

}

result

=

minimize

(

objective

,

[

0

,

0

]

,

constraints

=

con

)

print

(

f

"optimal solution: x={result.x[0]:.6f}, y={result.x[1]:.6f}"

)

print

(

f

"minimum value: {result.fun:.6f}"

)

After executing the above code, the output is as follows:



最优解: x=0.500000, y=0.500000

最小值: 0.500000

Constraint Types 'eq' indicates an equality constraint (the constraint function must equal 0), 'ineq' indicates an inequality constraint (the constraint function must be greater than or equal to 0).

Bounded Constrained Optimization

In addition to functional constraints, you can also limit the range of the independent variable via the bounds parameter:

Example

in x ∈ [0, 2] Minimize within a range (x - 1)² + 2:

from

scipy.

optimize

import

minimize

def

objective

(

x

)

:

   

return

(

x -

1

)

**

2

2

Define Bounds

bounds

=

[

(

0

,

2

)

]

result

=

minimize

(

objective

,

0

,

bounds

=

bounds

)

print

(

f

"optimal solution: x={result.x[0]:.6f}"

)

print

(

f

"minimum value: {result.fun:.6f}"

)

After executing the above code, the output is as follows:



最优解: x=1.000000

最小值: 2.000000

Gradient-Free Optimization

When the objective function is non-differentiable or its derivative is hard to compute, you can use optimization algorithms that do not require gradient information, such as Nelder-Mead method in the component:

Example

Minimize using the Nelder-Mead method sin(x) + 0.5*x:

from

scipy.

optimize

import

minimize

from

math

import

sin

def

objective

(

x

)

:

   

return

sin

(

x

)

0.5

result

=

minimize

(

objective

,

0

,

method

=

'Nelder-Mead'

)

print

(

f

"optimal solution: x={result.x[0]:.6f}"

)

print

(

f

"minimum value: {result.fun:.6f}"

)

print

(

f

"success: {result.success}"

)

After executing the above code, the output is as follows:



最优解: x=-1.047198

最小值: -1.523599

是否成功: True

Frequently Asked Questions and Suggestions

Summary

SciPy's optimize The module provides powerful optimization and equation-solving tools:

After mastering these basic functions, readers can further explore optimize the module's more features, such as curve fitting (curve_fit), global optimization (basinhopping, differential_evolution) and other advanced features.