from bayes_opt import BayesianOptimization
#定义一个目标函数,对外部来说,是个黑盒
def black_box_function(x, y):
"""Function with unknown internals we wish to maximize.
This is just serving as an example, for all intents and
purposes think of the internals of this function, i.e.: the process
which generates its output values, as unknown.
"""
return -x ** 2 - (y - 1) ** 2 + 1
#指定参数范围
params = {'x': (2, 10), 'y': (-3, 3)}
#创建一个优化器对象
optimizer = BayesianOptimization(
black_box_function,
params,
random_state=1001)
optimizer.maximize(
init_points=2, # 轮次数,越大,越容易找到最优
n_iter=2) # How many steps of random exploration you want to perform
#展现运行的结果
| iter | target | x | y |
-------------------------------------------------
| 1 | -24.61 | 4.45 | -1.41 |
| 2 | -13.74 | 3.568 | -0.4169 |
| 3 | -19.46 | 4.244 | 2.565 |
| 4 | -59.96 | 7.16 | -2.115 |
=================================================
print(optimizer.max)#打印最佳结果
{'target': -13.741576945116856, 'params': {'x': 3.5684805052092115, 'y': -0.41687114059771435}}
for i,res in enumerate(optimizer.res):
print("Iteration {}:\n\t{}".format(i,res))
Iteration 0:
{'target': -24.607493032291373, 'params': {'x': 4.4498574363904435, 'y': -1.4096186063549654}}
Iteration 1:
{'target': -13.741576945116856, 'params': {'x': 3.5684805052092115, 'y': -0.41687114059771435}}
Iteration 2:
{'target': -19.463673322535417, 'params': {'x': 4.244244180189207, 'y': 2.565268239461041}}
Iteration 3:
{'target': -59.959093951245286, 'params': {'x': 7.159514345708594, 'y': -2.1145542674415116}}
使用贝叶斯调参的API基本步骤
最新推荐文章于 2024-11-14 11:39:34 发布