python 使用带约束的hyperopt

mfpqipee  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(112)

要为hyperopt创建搜索空间,我们可以简单地执行以下操作:

space = {
    'x': hp.uniform('x', -10, 10),
    'y': hp.uniform('y', -10, 10)
}

但是,当我需要一个像x + y = 1这样的条件时,我该如何做到这一点呢?并将其扩展到许多像x+y+z+t = 1这样的变量

qacovj5a

qacovj5a1#

我也遇到了同样的问题,我的解决方法是定义参数优化函数,而不使用其中一个参数,然后通过从一个常数(您希望参数相加的数字)中减去其他参数的值来动态计算该参数的值:

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"]

最初,我也尝试过贝内方法的迭代,测试x+y+z+t是否等于1,如果不等于,则返回无穷大:

def fn(x,y,z):
    if(x+y+z+t!=1):
      return float('inf')
    else:
      return x*y+z*t

但这不会产生除Inf之外的任何其他值,因为四个随机选择的浮点数加起来正好为1的概率可以忽略不计。

相关问题