带约束的单目标¶
在本教程中,我们将介绍如何使用OpenBox优化一个约束问题。
问题设置¶
首先,定义搜索空间和定义目标函数 以最小化。这里我们使用受约束的Mishra函数。
import numpy as np
from openbox import space as sp
def mishra(config: sp.Configuration):
X = np.array([config['x%d' % i] for i in range(2)])
x, y = X[0], X[1]
t1 = np.sin(y) * np.exp((1 - np.cos(x))**2)
t2 = np.cos(x) * np.exp((1 - np.sin(y))**2)
t3 = (x - y)**2
result = dict()
result['objectives'] = [t1 + t2 + t3, ]
result['constraints'] = [np.sum((X + 5)**2) - 25, ]
return result
params = {
'float': {
'x0': (-10, 0, -5),
'x1': (-6.5, 0, -3.25)
}
}
space = sp.Space()
space.add_variables([
sp.Real(name, *para) for name, para in params['float'].items()
])
评估后,目标函数返回一个dict (推荐)。
结果字典应包含:
'objectives': 一个列表/元组,包含目标值(需要最小化)。 在这个例子中,我们只有一个目标,因此元组包含一个单一的值。'constraints': 一个列表/元组的约束值。 非正的约束值(“<=0”)意味着可行性。
优化¶
在定义了搜索空间和目标函数之后,我们可以按照以下方式运行优化过程:
from openbox import Optimizer
opt = Optimizer(
mishra,
space,
num_constraints=1,
num_objectives=1,
surrogate_type='gp', # try using 'auto'!
acq_optimizer_type='random_scipy', # try using 'auto'!
max_runs=50,
task_id='soc',
# Have a try on the new HTML visualization feature!
# visualization='advanced', # or 'basic'. For 'advanced', run 'pip install "openbox[extra]"' first
# auto_open_html=True, # open the visualization page in your browser automatically
)
history = opt.run()
在这里我们创建了一个Optimizer实例,并将目标函数和搜索空间传递给它。
其他参数包括:
num_objectives=1和num_constraints=1表示我们的函数返回一个带有单一约束的单一值。max_runs=50表示优化将进行50轮(优化目标函数50次)。task_id用于标识优化过程。visualization:'none','basic'或'advanced'. 参见 HTML Visualization.auto_open_html: 是否自动在浏览器中打开可视化页面。 参见 HTML Visualization。
然后,调用opt.run()以启动优化过程。
可视化¶
优化后,opt.run() 返回优化历史。或者你可以调用
opt.get_history() 来获取历史。
然后,调用 print(history) 查看结果:
history = opt.get_history()
print(history)
+-------------------------+---------------------+
| Parameters | Optimal Value |
+-------------------------+---------------------+
| x0 | -3.172421 |
| x1 | -1.506397 |
+-------------------------+---------------------+
| Optimal Objective Value | -105.72769850551406 |
+-------------------------+---------------------+
| Num Configs | 50 |
+-------------------------+---------------------+
调用 history.plot_convergence() 来可视化优化过程:
import matplotlib.pyplot as plt
history.plot_convergence(true_minimum=-106.7645367)
plt.show()
(新功能!)
调用 history.visualize_html() 在HTML页面中可视化优化过程。
对于 show_importance 和 verify_surrogate,请先运行 pip install "openbox[extra]"。
更多详情请参见 HTML Visualization。
history.visualize_html(open_html=True, show_importance=True,
verify_surrogate=True, optimizer=opt)