Hill-climbing optimisation
Global maximum
Let’s try it with the function
\[ f(x,y) = e^{-\left(x^2+y^2\right)} \]
import numpy as np
import matplotlib.pyplot as plt
from plotutils import *
= np.linspace(-2.0, 2.0, 1000)
x = np.linspace(-2.0, 2.0, 1000)
y = np.meshgrid(x, y)
X, Y
= np.exp(-(X ** 2 + Y ** 2))
Z
= plt.subplots(1, 1)
fig, ax = ax.contourf(X, Y, Z, cmap=cmaps[1])
cp
"f(x,y)")
ax.set_title("x")
ax.set_xlabel("y")
ax.set_ylabel( plt.show()
from gradient_free_optimizers import HillClimbingOptimizer
= {
search_space "x": x,
"y": y,
}
= HillClimbingOptimizer(search_space) opt
def f(pos):
= pos["x"]
x = pos["y"]
y = np.exp(-(x**2 + y**2))
z return z
= opt.search(f,
result =30000,
n_iter=['print_times']) verbosity
Evaluation time : 0.9117169380187988 sec [28.97 %]
Optimization time : 2.235219955444336 sec [71.03 %]
Iteration time : 3.1469368934631348 sec [9533.08 iter/sec]
opt.best_para
{'x': -0.002002002002001957, 'y': 0.002002002002002179}
Local maximum
Let’s try it with the function
\[ f(x,y) = e^{-\left(x^2+y^2\right)}+2e^{-\left((x-1.7)^2+(y-1.7)^2\right)} \]
= np.linspace(-1.0, 3.0, 1000)
x = np.linspace(-1.0, 3.0, 1000)
y = np.meshgrid(x, y)
X, Y
= np.exp(-(X**2 + Y**2))+2*np.exp(-((X-1.7)**2+(Y-1.7)**2))
Z
=plt.subplots(1,1)
fig,ax= ax.contourf(X, Y, Z, cmap=cmaps[1])
cp
'f(x,y)')
ax.set_title('x')
ax.set_xlabel('y')
ax.set_ylabel( plt.show()
= HillClimbingOptimizer(search_space) opt
def f(pos):
= pos["x"]
x = pos["y"]
y = np.exp(-(x**2 + y**2))+2*np.exp(-((x-1.7)**2+(y-1.7)**2))
z return z
= opt.search(f,
result =30000,
n_iter=['print_times']) verbosity
Evaluation time : 0.9092590808868408 sec [29.73 %]
Optimization time : 2.148698091506958 sec [70.27 %]
Iteration time : 3.057957172393799 sec [9810.47 iter/sec]
opt.best_para
{'x': 1.6956956956956954, 'y': 1.6956956956956954}