我正在努力使用 hyperopt 来调整我的 ML 模型,但在使用 qloguniform 作为搜索空间时遇到了麻烦。我给出了 official wiki 的示例并更改了搜索空间。
import pickle
import time
#utf8
import pandas as pd
import numpy as np
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
def objective(x):
return {
'loss': x ** 2,
'status': STATUS_OK,
# -- store other results like this
'eval_time': time.time(),
'other_stuff': {'type': None, 'value': [0, 1, 2]},
# -- attachments are handled differently
'attachments':
{'time_module': pickle.dumps(time.time)}
}
trials = Trials()
best = fmin(objective,
space=hp.qloguniform('x', np.log(0.001), np.log(0.1), np.log(0.001)),
algo=tpe.suggest,
max_evals=100,
trials=trials)
pd.DataFrame(trials.trials)
但出现以下错误。
ValueError: ('negative arg to lognormal_cdf', array([-3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764, -3.45387764]))
我尝试过不进行对数转换,如下所示,但输出值结果是 log transformation (ex- 1.017,1.0008,1.02456),这是错误的。与文档一致。
hp.qloguniform('x', 0.001,0.1, 0.001)
谢谢
最佳答案
问题似乎出在 hp.qloguniform
的最后一个参数中,q
以及 tpe.suggest
如何使用它。
首先让我们讨论一下
q
。根据文档:hp.qloguniform(label, low, high, q)
round(exp(uniform(low, high)) / q) * q
Suitable for a discrete variable with respect to which the objective is "smooth" and gets smoother with the size of the value, but which should be bounded both above and below.
q
这里是一个“量化器”
,它将定义空间的输出限制为q
的倍数。例如,以下是qloguniform
内部发生的情况:from hyperopt import pyll, hp n_samples = 10 space = hp.loguniform('x', np.log(0.001), np.log(0.1)) evaluated = [pyll.stochastic.sample(space) for _ in range(n_samples)] # Output: [0.04645754, 0.0083128 , 0.04931957, 0.09468335, 0.00660693, # 0.00282584, 0.01877195, 0.02958924, 0.00568617, 0.00102252] q = 0.005 qevaluated = np.round(np.array(evaluated)/q) * q # Output: [0.045, 0.01 , 0.05 , 0.095, 0.005, 0.005, 0.02 , 0.03 , 0.005, 0.])
比较这里的
evaluated
和qevaluated
。qevaluated
是q
的倍数,或者我们说它在q
的“间隔”(或步骤)中量化。您可以尝试更改q
值以了解更多信息。与生成的样本范围(
0.001 到 0.1
)相比,您在问题中定义的q
非常大:np.log(0.001) # Output: -6.907755278982137
因此,此处所有值的输出都将为 0。
q = np.log(0.001) qevaluated = np.round(np.array(evaluated)/q) * q # Output: [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]
现在来到
tpe.suggest
(this paper 的第 4 节):TPE 使用不同估计量的树来优化搜索过程,在此期间它根据空间生成器(在本例中为qloguniform
)。参见 code here了解详情。为了将空间分成多个部分,它将使用q
。但由于您空间中的所有点都将为 0.0(如上所述),此负
q
会为lognormal_cdf
which is not acceptable 生成无效边界因此错误。
长话短说,您对 q
的用法不正确。正如您在评论中所说:-
Also
q
value should not be used inside the log uniform/log normal random sampling according toround(exp(uniform(low, high)) / q) * q
因此您应该只提供对所需空间有效的 q
值。所以在这里,既然你想生成0.001
和0.1
之间的值,那么q
的值就应该与它们相当。
我同意您在 qloguniform
中提供 np.log(0.001)
和 np.log(0.1)
但就是这样输出值介于 0.001 和 0.1 之间。所以不要在q
中使用np.log
。 q
应该根据生成的值来使用。
关于python - Hyperopt 中的 qloguniform 搜索空间设置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789280/