from hyperopt import fmin, tpe, hp
# the function; parameter t is calculated automatically, only x,y,z are optimized
def fn(x,y,z):
t = 1 - x - y - z # ensures that x+y+z+t always equals 1
return x*y+z*t # whatever
# Define the search space for the function arguments
space = hp.choice('parameters', [
{'x': hp.uniform('x', -10, 10),
'y': hp.uniform('y', -10, 10),
'z': hp.uniform('z', -10, 10)},
])
# Define the objective function
def objective(params):
x = params['x']
y = params['y']
z = params['z']
return fn(x,y,z)
# Use the fmin function to find the minimum value
best = fmin(objective, space, algo=tpe.suggest, max_evals=1000)
# Print the best parameters and the minimum value
print(best)
print(objective(best))
# the value of t can be easily calculated by subtracting from one
t = 1 - best["x"] - best["y"] - best["z"]
1条答案
按热度按时间qacovj5a1#
我也遇到了同样的问题,我的解决方法是定义参数优化函数,而不使用其中一个参数,然后通过从一个常数(您希望参数相加的数字)中减去其他参数的值来动态计算该参数的值:
最初,我也尝试过贝内方法的迭代,测试x+y+z+t是否等于1,如果不等于,则返回无穷大:
但这不会产生除Inf之外的任何其他值,因为四个随机选择的浮点数加起来正好为1的概率可以忽略不计。