对于机器学习工程师,要选择使用的模型,也要调整各个模型的参数,才找到最好的匹配。即使模型还可以,如果它的参数设置不匹配,同样无法输出好的结果。
常用的调参方式有 grid search 和 random search ,grid search 是全空间扫描,所以比较慢,random search 虽然快,但可能错失空间上的一些重要的点,精度不够,于是,贝叶斯优化出现了。
hyperopt是一种通过贝叶斯优化来调整参数的工具,对于像XGBoost这种参数比较多的算法,可以用它来获取比较好的参数值。
安装
pip install hyperopt
它会安装 networkx,如果运行异常,碰到 TypeError: 'generator' object is not subscriptable
的话,可以卸载并换成老版本来解决
pip uninstall networkx
pip install networkx==1.11
几个重要的函数,变量和概念
fmin
from hyperopt import fmin, tpe, hp
best = fmin(
fn=lambda x: x,
space=hp.uniform('x', 0, 1),
algo=tpe.suggest,
max_evals=100)
print best
以上面的函数为例,fmin寻找最佳匹配的 space ,使 fn 的函数返回值最小,采用了 tpe.suggest (tree of Parzen estimators) 的算法,反复尝试100次,最终得到的结果类似于 {'x': 0.000269455723739237}
space
对于变量的变化范围与取值概率,一般定义有这么几个
- hp.choice(label, options) where options should be a python list or tuple. 如果需要枚举从[1, 100],那么用choice,而不应该用quniform
- hp.randint(label, upper) 返回从[0, upper)的随机整数,一般用作随机数的种子值。如果这个值会影响loss函数,那么需要考虑使用 quniform
- hp.uniform(label, low, high) where low and high are the lower and upper bounds on the range. 限制上下边界的平均分布
- hp.quniform(label, low, high) where low and high are the lower and upper bounds on the range. 但只取整数(round), ⌊[low,high]q⌋×q 。返回可能是 1.0 这样的数值,如果参数类型有Interger的限制ÿ