gugarosa / opytimizer

🐦 Opytimizer is a Python library consisting of meta-heuristic optimization algorithms.
https://opytimizer.readthedocs.io
Apache License 2.0
599 stars 40 forks source link

[REG]How to plot convergence diagram? #23

Closed amir1m closed 3 years ago

amir1m commented 3 years ago

Hello, I was looking for convergence diagram. Found an example of using convergence function opytimizer/examples/visualization/convergence_plotting.py /. However, it uses few constant values of agent positions. Is there a convergence example that shows how to use this function with actual optimization problem such as after carrying out PSO?

Thanks,

gugarosa commented 3 years ago

Hello amir1m! I hope everything is going well with you!

Sorry for not having a script that depicts on how to use the actual optimization problem to make the convergence plot. We ran into some issues where people used to say that there was not file to be loaded and opted to remove such an example.

Nevertheless, here is a draft that might help you:

import numpy as np
from opytimark.markers.n_dimensional import Sphere

from opytimizer import Opytimizer
from opytimizer.core import Function
from opytimizer.optimizers.swarm import PSO
from opytimizer.spaces import SearchSpace

import opytimizer.visualization.convergence as c

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

# Number of agents and decision variables
n_agents = 20
n_variables = 2

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

# Creates the space, optimizer and function
space = SearchSpace(n_agents, n_variables, lower_bound, upper_bound)
optimizer = PSO()
function = Function(Sphere())

# Bundles every piece into Opytimizer class
opt = Opytimizer(space, optimizer, function, save_agents=False)

# Runs the optimization task
opt.start(n_iterations=1000)

# Retrieves the best agent's position and fitness
best_agent_pos, best_agent_fit = opt.history.get_convergence('best_agent')

# Plots the convergence of x0 and x1
c.plot(best_agent_pos[0], best_agent_pos[1])

Note that the idea is to retrieve a list of positions/fitness through the get_convergence() method of the History class. With these lists, it is possible to feed them to the convergence.plot() method.

Additionally, after performing an optimization, you can save the whole task using opt.save() and load it into another script with opt = Opytimizer.load(). The History object will be available as an property of Opytimizer, e.g., opt.history.

Please let me know if it works!

Best regards, Gustavo.

amir1m commented 3 years ago

Awesome! Works as expected.

Thanks @gugarosa ! Appreciate the quick turnaround!

Take care. Amir