Yabox: Yet another black-box optimization library for Python - https://github.com/pablormier/yabox
Tutorial of the basic functionality of Yabox
Author: Pablo Rodríguez-Mier, @pablormier
In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sys
# Load Yabox (from local)
# Comment this line to use the installed version
sys.path.insert(0, '../')
import yabox as yb
# Import the DE implementations
from yabox.algorithms import DE, PDE
print('Yabox version: ', yb.__version__)
In [19]:
DE(lambda x: sum(x**2) + 1, [(-10, 10)] * 5, maxiters=10000).solve(show_progress=True)
Out[19]:
In many scenarios, the function to optimize may depend on many other components or other fixed parameters. It is very convenient to define a function to create your optimizable function. Here is an example of this, where create_loss
is a function that prepares the data and returns another function to be optimize:
In [65]:
def create_loss(p1, p2, p3):
# Prepare here whatever you need. Load parameters,
# read from file, etc
a = p1 * p2
b = p2 / p3
# Define the function to be optimized as an inner function
# that can make use of the other parameters
def f(x):
return 1 + a*x - b*x**2 + 0.01*x**3 + 0.001 * x**4
return f
f = create_loss(5, 2, 0.1)
f(0)
Out[65]:
In [43]:
x = np.arange(-150, 150, 0.1)
plt.plot(x, f(x));
In [63]:
xo, yo = DE(f, [(-150, 150)], maxiters=1000).solve(show_progress=True)
xo, yo
Out[63]:
In [64]:
fig, ax = plt.subplots()
ax.plot(x, f(x));
ax.plot(xo[0][0], yo[0], '*')
Out[64]:
You can control also the search process. Use geniterator()
to get an iterator at the level of the population (by default, .iterator()
returns an iterator at the level of individual (thus it iteraters maxiters * popsize times)
In [67]:
# Control the iteration process
de = DE(f, [(-150, 150)], maxiters=30)
for step in de.geniterator():
idx = step.best_idx
norm_vector = step.population[idx]
best_params = de.denormalize([norm_vector])
print(step.best_fitness, norm_vector, best_params[0])