版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wxf2012301351/article/details/82017076
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials, space_eval
import numpy as np
def func(param_dict):
loss=(param_dict['x'] ** 2 - 20 * param_dict['x'])
ret = {
"loss": loss,
"attachments": {
"x": param_dict['x'],
'y':34
},
"status": STATUS_OK
}
return ret
def run():
param_dict = {#搜索空间
'x': hp.quniform('x', 5, 100, 5)
}
trials = Trials()#Trials检查实验期间计算的所有返回值
best = fmin(func,param_dict, tpe.suggest, 10, trials)#fmin优化函数,func目标函数
print('best:',best)
best_params = space_eval(param_dict, best)# at the point best using the hyperopt.space_eval function
#to see param_dict's parameter values in the output
print('best_params:',best_params)
trial_loss = np.asarray(trials.losses(), dtype=float)
best_ind = np.argmin(trial_loss)
best_loss = -trial_loss[best_ind]
best_x = trials.trial_attachments(trials.trials[best_ind])["x"]#检索次序为best_ind的参数。
print('best_x:',best_x)
参考文档: