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:
- fun - The function representing the equation (when the return value is 0, it means the root is found)
- x0 - The initial guess for the root
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
)
(
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
)
(
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:
- success Indicates whether the algorithm converged successfully
- message Describes the result of the solution process
- x Is the final root found
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:
-
fun - The objective function to be minimized
-
x0 - The initial guess for the independent variable
-
method - The name of the optimization algorithm used; common optional values include:
'CG','BFGS','Newton-CG','L-BFGS-B','TNC','COBYLA','SLSQP' -
callback - A callback function called after each iteration ends
-
options - A dictionary of other control parameters, for example:
{ "disp": boolean, # 是否打印详细的优化过程信息 "gtol": number # 梯度收敛容差(部分算法适用)
}
Example
Minimize a function using the BFGS method x² + x + 2:
from
scipy.
optimize
import
minimize
def
eqn
(
x
)
:
return
x**
2
- x +
2
mymin
=
minimize
(
eqn
,
0
,
method
=
'BFGS'
)
(
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
)
(
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
:
(
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
)
)
(
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
- x
[
1
]
**
2
def
constraint
(
x
)
:
return
x
[
0
]
- x
[
1
]
1
Define Constraints
con
=
{
'type'
:
'eq'
,
'fun'
: constraint
}
result
=
minimize
(
objective
,
[
0
,
0
]
,
constraints
=
con
)
(
f
"optimal solution: x={result.x[0]:.6f}, y={result.x[1]:.6f}"
)
(
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
)
(
f
"optimal solution: x={result.x[0]:.6f}"
)
(
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
- x
result
=
minimize
(
objective
,
0
,
method
=
'Nelder-Mead'
)
(
f
"optimal solution: x={result.x[0]:.6f}"
)
(
f
"minimum value: {result.fun:.6f}"
)
(
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
- Choose an appropriate initial value - The choice of initial value greatly affects the solution result; it is recommended to do a simple visualization or analysis of the objective function before solving.
- Check the convergence status - Always check the
successfield to ensure the algorithm converged successfully. If the solution fails, you can try changing the initial value or the optimization algorithm. - Choose an appropriate algorithm - For unconstrained problems,
BFGSis a good default choice; for high-dimensional problems, you can tryL-BFGS-B; for non-differentiable functions, useNelder-Mead. - Handling multiple-root problems - For problems with multiple roots, it is recommended to solve from multiple different initial values.
- to the parameter - Uses
argsPass extra parameters via the parameter to avoid using global variables.
Summary
SciPy's optimize The module provides powerful optimization and equation-solving tools:
- Root finding:
root()andfsolve()Used to solve nonlinear equations - Unconstrained optimization:
minimize()together withmethodThe parameter implements various algorithms - Constrained Optimization: Through
constraintsThe parameter adds equality and inequality constraints - Boundary limits: When using
boundsThe parameter limits the range of variable values - Gradient-free methods:
Nelder-MeadSuitable for non-differentiable functions
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.