简体   繁体   English

使用带约束的 hyperopt

[英]Using hyperopt with constraints

To create search space for hyperopt, we can simply do:要为 hyperopt 创建搜索空间,我们可以简单地执行以下操作:

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

However, how can I do this when I want a condition like x + y = 1 ?但是,当我想要像x + y = 1这样的条件时,我该怎么做呢? And extend it to many variables like x+y+z+t = 1并将其扩展到许多变量,例如x+y+z+t = 1

I had the same problem.我有同样的问题。 What worked for me was defining the function for parameter optimization without one of the parameters whose value was then calculated on the fly by subtracting the values of the other parameters from a constant (the number you want the parameters to add up to):对我有用的是在没有参数之一的情况下定义参数优化函数,然后通过从常量(您希望参数加起来的数字)中减去其他参数的值来动态计算其值:

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

Originally, I also tried an iteration of bene's approach, testing if x+y+z+t = 1 and returning infinity if not:最初,我还尝试了 bene 方法的迭代,测试 x+y+z+t = 1 是否为 1,否则返回无穷大:

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

But this never produced any other value than Inf as the probability of four randomly chosen floats to add up exactly to 1 is negligible.但这除了 Inf 之外从未产生任何其他值,因为四个随机选择的浮点数加起来恰好为 1 的概率可以忽略不计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM