Note
Go to the end to download the full example code
Minimize a function#
This examples shows a basic usage of stochopy.optimize.minimize()
.
Let’s import an objective function to optimize. stochopy.factory
has several sample benchmark functions to test.
We also have to define the feasible space (or boundaries) for each variable to optimize. The length of the boundary array is used internally to define the dimensionality of the problem. In this example, we will optimize 20 variables within [-5.12, 5.12].
import numpy as np
from stochopy.factory import rosenbrock
upper = np.full(20, 5.12)
bounds = np.column_stack((-upper, upper))
The main optimization function stochopy.optimize.minimize()
has an API inspired by scipy
.
In this example, we will use CMA-ES to minimize the Rosenbrock function
from stochopy.optimize import minimize
x = minimize(rosenbrock, bounds, method="cmaes", options={"maxiter": 2000, "popsize": 20, "seed": 42})
stochopy.optimize.minimize()
returns a stochopy.optimize.OptimizeResult
dictionary-like that contains the optimization result.
print(x)
fun: 9.145428857212641e-09
message: 'best solution value is lower than ftol'
nfev: 26940
nit: 1347
status: 1
success: True
x: array([1.00000007, 0.99999874, 0.99999912, 0.99999904, 0.99999866,
0.99999691, 0.99999746, 0.99999983, 1.00000106, 1.00000124,
1.00000022, 1.00000054, 1.00000062, 1.00000048, 1.00000085,
1.00000487, 1.00000562, 1.00001043, 1.00002107, 1.0000445 ])
Total running time of the script: ( 0 minutes 0.904 seconds)