Skip to content

Tutorial: Your first optimization

Gustavo Rosa edited this page Jul 23, 2020 · 17 revisions

Every code starts with some imports, correct?

import numpy as np

from opytimizer import Opytimizer
from opytimizer.core.function import Function
from opytimizer.math import benchmark
from opytimizer.optimizers.swarm.fa import FA
from opytimizer.spaces.search import SearchSpace

First of all, let us define a random seed for experimental consistency.

# Random seed for experimental consistency
np.random.seed(0)

Let us instantiate the first required class. We will need a search space to fit all of this stuff, right? We need the number of agents, number of variables, number of iterations, and lower and upper bound for each variable (they have to be a list of 'n_variables' size).

# Number of agents
n_agents = 20

# Number of decision variables
n_variables = 2

# Number of running iterations
n_iterations = 1000

# Lower and upper bounds (has to be the same size as n_variables)
lower_bound = (-10, -10)
upper_bound = (10, 10)

# Creating the SearchSpace class
s = SearchSpace(n_agents=n_agents, n_iterations=n_iterations,
                n_variables=n_variables, lower_bound=lower_bound,
                upper_bound=upper_bound)

So, we have a search space, but what is missing? Yes! We want to optimize so that we will need an optimizer. Remember that every optimizer might have some initialization parameters.

# Hyperparameters for the optimizer
hyperparams = {
    'alpha': 0.5,
    'beta': 0.2,
    'gamma': 1.0
}

# Creating FA's optimizer
p = FA(hyperparams=hyperparams)

We want to optimize things, right? So you can define whatever your desires are. In this case, we will use a simple x^2, where x is a vector of n variables, pre-loaded from the benchmarking package. With an objective function, we can create a Function class.

# Creating Function's object
f = Function(pointer=benchmark.sphere)

Finally, we can plug everything into your tasker, Opytimizer. With this class in hand, send a start command to initiate the optimization smoothly.

# Finally, we can create an Opytimizer class
o = Opytimizer(space=s, optimizer=p, function=f)

# Running the optimization task
history = o.start()

Notice that we have a history returning from the Opytimizer? It is optional! Nevertheless, hey, there is vital historical information from the optimization task; it might be necessary. So, let us see it!

print(history)

There you go! Just sequentially put this instruction in a single file and run it. You can also get the file in examples/applications/single_objective_optimization.py. Stay focus and you should be ready for everything.

Clone this wiki locally