-
2020-04-12 21:18:57
Hyperopt介绍
超参数优化是实现模型性能最大化的重要步骤,scikit-learn提供了GridSearchCV和RandomizedSearchCV两个比较流行的选项。Hyperopt,是python中的一个用于"分布式异步算法组态/超参数优化"的类库。Hyperopt提供了能够超越随机搜索的算法,并且可以找到与网格搜索相媲美的结果。它是一种通过贝叶斯优化来调整参数的工具,可结合MongoDB可以进行分布式调参,快速找到相对较优的参数。
Hyheropt四个重要的因素:
指定需要最小化的函数
参数搜索空间
存储搜索计算结果
所使用的搜索算法
Xgboost介绍
XGBoost是一个优化的分布式梯度增强库, 它在Gradient Boosting框架下实现机器学习算法。XGBoost成功背后最重要的因素是它在所有场景中的可扩展性,模型具有可解释性,在工业系统中被大量使用,xgboost与gbdt相比,gbdt只用到了一阶导数信息,而xgboost则同时用到了一阶与二阶导数,并且xgboost在惩罚函数中加入了正则化项,用于控制模型的复杂度,防止过拟合。
XGBoost具有三类参数,(常规参数)general parameters,(提升器参数)booster parameters和(任务参数)task parameters。
常规参数与我们用于提升的提升器有关,通常是树模型或线性模型
提升器参数取决于你所选择的提升器,提升模型表现
任务参数决定了学习场景, 例如回归任务、二分类任务
通常Xgboost训练模型,
xgboost.train(params, dtrain, num_boost_round=10, evals=(), \ obj=None, feval=None, maximize=False, early_stopping_rounds=None, \ evals_result=None, verbose_eval=True, learning_rates=None, \ xgb_model=None, callbacks=None)
其中params为一个dict,
params = { 'booster':'gbtree', 'min_child_weight': 100, 'eta': 0.02, 'colsample_bytree': 0.7, 'max_depth': 12, 'subsample': 0.7, 'alpha': 1, 'gamma': 1, 'silent': 1, 'objective': 'reg:linear', 'verbose_eval': True, 'seed': 12 }
General Parameters
booster [default=gbtree]
有两种模型可以选择,gbtree和gblinear。gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算。缺省值为gbtree。
silent [default=0]
取0时表示打印出运行时信息,取1时表示以缄默方式运行,不打印运行时信息。缺省值为0。
nthread
XGBoost运行时的线程数。缺省值是当前系统可以获得的最大线程数
Booster Parameters
eta [default=0.3]
为了防止过拟合,更新过程中用到的收缩步长。在每次提升计算之后,算法会直接获得新特征的权重。eta通过缩减特征的权重使提升计算过程更加保守。缺省值为0.3
通过减少每一步的权重,可以提高模型的鲁棒性。取值范围为:[0,1]
gamma [default=0]
在节点分裂时,只有分裂后损失函数的值下降了,才会分裂这个节点。Gamma指定了节点分裂所需的最小损失函数下降值。这个参数的值越大,算法越保守。这个参数的值和损失函数息息相关,所以是需要调整的。
range: [0,∞]
max_depth [default=6]
数的最大深度。缺省值为6,max_depth越大,模型会学到更具体更局部的样本。
取值范围为:[1,∞]
min_child_weight [default=1]
最小样本权重的和。如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束。在现行回归模型中,这个参数是指建立每个模型所需要的最小样本数。该成熟越大算法越conservative
取值范围为: [0,∞]
max_delta_step [default=0]
这参数限制每棵树权重改变的最大步长。如果这个参数的值为0,那就意味着没有约束。如果它被赋予了某个正值,那么它会让这个算法更加保守。
取值范围为:[0,∞]
subsample [default=1]
用于训练模型的子样本占整个样本集合的比例。如果设置为0.5则意味着XGBoost将随机从整个样本集合中随机的抽取出50%的子样本,建立树模型,这能够防止过拟合。减小这个参数的值,算法会更加保守,避免过拟合。但是,如果这个值设置得过小,它可能会导致欠拟合。
取值范围为:(0,1]
colsample_bytree [default=1]
在建立树时对特征采样的比例。缺省值为1
取值范围:(0,1]
colsample_bylevel
用来控制树的每一级的每一次分裂,对列数的采样的占比。
取值范围:(0,1]
lambda
权重的L2正则化项
参数是用来控制XGBoost的正则化部分的,
alpha
权重的L1正则化项
可以应用在很高维度的情况下,使得算法的速度更快。
scale_pos_weight
在各类别样本十分不平衡时,把这个参数设定为一个正值,可以使算法更快收敛。
Task Parameters
objective [ default=reg:linear ]
binary:logistic, 二分类的逻辑回归,返回预测的概率(不是类别)。
multi:softmax, 使用softmax的多分类器,返回预测的类别(不是概率)。
multi:softprob, 和multi:softmax参数一样,但是返回的是每个数据属于各个类别的概率。
base_score [ default=0.5 ]
eval_metric
校验数据所需要的评价指标,不同的目标函数将会有缺省的评价指标
rmse, logloss, auc等
seed
随机数种子,设置成某个值可以复现随机数据的结果,也可以用于调整参数
GridSearchCV
from sklearn.model_selection import GridSearchCV, cross_val_score from xgboost import XGBClassifier gs = GridSearchCV(estimator=XGBClassifier(), param_grid={'max_depth': [3, 6, 9], 'learning_rate': [0.001, 0.01, 0.05]}, cv=2) scores = cross_val_score(gs, X, y, cv=2)
Hyperopt自动调参
import xgboost as xgb from hyperopt import STATUS_OK, Trials, fmin, hp, tpe def score(params): print("Training with params: ") print(params) num_round = int(params['n_estimators']) del params['n_estimators'] dtrain = xgb.DMatrix(train_features, label=y_train) dvalid = xgb.DMatrix(valid_features, label=y_valid) watchlist = [(dvalid, 'eval'), (dtrain, 'train')] gbm_model = xgb.train(params, dtrain, num_round, evals=watchlist, verbose_eval=True) predictions = gbm_model.predict(dvalid, ntree_limit=gbm_model.best_iteration + 1) score = roc_auc_score(y_valid, predictions) # TODO: Add the importance for the selected features print("\tScore {0}\n\n".format(score)) # The score function should return the loss (1-score) # since the optimize function looks for the minimum loss = 1 - score return {'loss': loss, 'status': STATUS_OK} def optimize( #trials, random_state=SEED): """ This is the optimization function that given a space (space here) of hyperparameters and a scoring function (score here), finds the best hyperparameters. """ # To learn more about XGBoost parameters, head to this page: # https://github.com/dmlc/xgboost/blob/master/doc/parameter.md space = { 'n_estimators': hp.quniform('n_estimators', 100, 1000, 1), 'eta': hp.quniform('eta', 0.025, 0.5, 0.025), # A problem with max_depth casted to float instead of int with # the hp.quniform method. 'max_depth': hp.choice('max_depth', np.arange(1, 14, dtype=int)), 'min_child_weight': hp.quniform('min_child_weight', 1, 6, 1), 'subsample': hp.quniform('subsample', 0.5, 1, 0.05), 'gamma': hp.quniform('gamma', 0.5, 1, 0.05), 'colsample_bytree': hp.quniform('colsample_bytree', 0.5, 1, 0.05), 'eval_metric': 'auc', 'objective': 'binary:logistic', # Increase this number if you have more cores. Otherwise, remove it and it will default # to the maxium number. 'nthread': 4, 'booster': 'gbtree', 'tree_method': 'exact', 'silent': 1, 'seed': random_state } # Use the fmin function from Hyperopt to find the best hyperparameters best = fmin(score, space, algo=tpe.suggest, # trials=trials, max_evals=250) return best """ 其他特征处理步骤 """ if __name__ == "__main__": trials = Trials() optimize(trials)
更多相关内容 -
如何使用hyperopt对xgboost进行自动调参
2018-12-17 10:26:17本教程重点在于传授如何使用Hyperopt对xgboost进行自动调参。但是这份代码也是我一直使用的代码模板之一,所以在其他数据集上套用该模板也是十分容易的。 同时因为xgboost,lightgbm,catboost。三个类库调用方法都...本教程重点在于传授如何使用Hyperopt对xgboost进行自动调参。但是这份代码也是我一直使用的代码模板之一,所以在其他数据集上套用该模板也是十分容易的。
同时因为xgboost,lightgbm,catboost。三个类库调用方法都比较一致,所以在本部分结束之后,我们有理由相信,你将会学会在这三个类库上使用hyperopt。除此之外要额外说明的是,本文并不涉及交叉验证的问题,交叉验证请查看其他教程。
什么是Hyperopt?
Hyperopt:是python中的一个用于"分布式异步算法组态/超参数优化"的类库。使用它我们可以拜托繁杂的超参数优化过程,自动获取最佳的超参数。广泛意义上,可以将带有超参数的模型看作是一个必然的非凸函数,因此hyperopt几乎可以稳定的获取比手工更加合理的调参结果。尤其对于调参比较复杂的模型而言,其更是能以远快于人工调参的速度同样获得远远超过人工调参的最终性能。
文档地址?
目前中文文档的地址由本人FontTian在2017年翻译,但是hyperopt文档本身确实写的不怎么样。所以才有了这份教程。源代码请前往Github教程地址下载下载。
教程
获取数据
这里我们使用UCI的红酒质量数据集,除此之外我还额外增加了两个特征。
from hyperopt import fmin, tpe, hp, partial import numpy as np from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import mean_squared_error, zero_one_loss import xgboost as xgb import pandas as pd def GetNewDataByPandas(): wine = pd.read_csv("../data/wine.csv") wine['alcohol**2'] = pow(wine["alcohol"], 2) wine['volatileAcidity*alcohol'] = wine["alcohol"] * wine['volatile acidity'] y = np.array(wine.quality) X = np.array(wine.drop("quality", axis=1)) columns = np.array(wine.columns) return X, y, columns
分割数据并转换
首先将数据分割为三份,一部分用于预测,训练数据则同样分成额外的两部分用于evallist参数。
同时为了加快速度和减少内存,我们将数据转换为
xgboost
自带的读取格式。# Read wine quality data from file X, y, wineNames = GetNewDataByPandas() # split data to [[0.8,0.2],01] x_train_all, x_predict, y_train_all, y_predict = train_test_split(X, y, test_size=0.10, random_state=100) x_train, x_test, y_train, y_test = train_test_split(x_train_all, y_train_all, test_size=0.2, random_state=100) dtrain = xgb.DMatrix(data=x_train,label=y_train,missing=-999.0) dtest = xgb.DMatrix(data=x_test,label=y_test,missing=-999.0) evallist = [(dtest, 'eval'), (dtrain, 'train')]
定义参数空间
使用hyperopt自带的函数定义参数空间,但是因为其
randint()
方法产生的数组范围是从0开始的,所以我额外定义了一个数据转换方法,对原始参数空间进行一次转换。关于hyperopt中定义参数区间需要使用的函数请参考:
# 自定义hyperopt的参数空间 space = {"max_depth": hp.randint("max_depth", 15), "n_estimators": hp.randint("n_estimators", 300), 'learning_rate': hp.uniform('learning_rate', 1e-3, 5e-1), "subsample": hp.randint("subsample", 5), "min_child_weight": hp.randint("min_child_weight", 6), } def argsDict_tranform(argsDict, isPrint=False): argsDict["max_depth"] = argsDict["max_depth"] + 5 argsDict['n_estimators'] = argsDict['n_estimators'] + 150 argsDict["learning_rate"] = argsDict["learning_rate"] * 0.02 + 0.05 argsDict["subsample"] = argsDict["subsample"] * 0.1 + 0.5 argsDict["min_child_weight"] = argsDict["min_child_weight"] + 1 if isPrint: print(argsDict) else: pass return argsDict
创建模型工厂与分数获取器
xgboost模型工厂用于生产我们需要的model,而分数获取器则是为了解耦。这样在实际的测试工作中更加套用代码和修改。
def xgboost_factory(argsDict): argsDict = argsDict_tranform(argsDict) params = {'nthread': -1, # 进程数 'max_depth': argsDict['max_depth'], # 最大深度 'n_estimators': argsDict['n_estimators'], # 树的数量 'eta': argsDict['learning_rate'], # 学习率 'subsample': argsDict['subsample'], # 采样数 'min_child_weight': argsDict['min_child_weight'], # 终点节点最小样本占比的和 'objective': 'reg:linear', 'silent': 0, # 是否显示 'gamma': 0, # 是否后剪枝 'colsample_bytree': 0.7, # 样本列采样 'alpha': 0, # L1 正则化 'lambda': 0, # L2 正则化 'scale_pos_weight': 0, # 取值>0时,在数据不平衡时有助于收敛 'seed': 100, # 随机种子 'missing': -999, # 填充缺失值 } params['eval_metric'] = ['rmse'] xrf = xgb.train(params, dtrain, params['n_estimators'], evallist,early_stopping_rounds=100) return get_tranformer_score(xrf) def get_tranformer_score(tranformer): xrf = tranformer dpredict = xgb.DMatrix(x_predict) prediction = xrf.predict(dpredict, ntree_limit=xrf.best_ntree_limit) return mean_squared_error(y_predict, prediction)
调用Hyperopt开始调参
之后我们调用hyperopt进行自动调参即可,同时通过返回值获取最佳模型的结果。
# 开始使用hyperopt进行自动调参 algo = partial(tpe.suggest, n_startup_jobs=1) best = fmin(xgboost_factory, space, algo=algo, max_evals=20, pass_expr_memo_ctrl=None)
[15:23:32] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 142 extra nodes, 0 pruned nodes, max_depth=10 [0] eval-rmse:5.03273 train-rmse:4.90203 Multiple eval metrics have been passed: 'train-rmse' will be used for early stopping. Will train until train-rmse hasn't improved in 100 rounds. [15:23:32] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 172 extra nodes, 0 pruned nodes, max_depth=10 [1] eval-rmse:4.77384 train-rmse:4.64767 ... [15:24:04] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 192 extra nodes, 0 pruned nodes, max_depth=15 [299] eval-rmse:0.570382 train-rmse:0.000749
展示结果
展示我们获取的最佳参数,以及该模型在训练集上的最终表现,如果想要使用交叉验证请参考其他教程。
RMSE = xgboost_factory(best) print('best :', best) print('best param after transform :') argsDict_tranform(best,isPrint=True) print('rmse of the best xgboost:', np.sqrt(RMSE))
[15:24:52] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 428 extra nodes, 0 pruned nodes, max_depth=14 [0] eval-rmse:5.02286 train-rmse:4.89385 Multiple eval metrics have been passed: 'train-rmse' will be used for early stopping. Will train until train-rmse hasn't improved in 100 rounds. [15:24:52] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 680 extra nodes, 0 pruned nodes, max_depth=14 [1] eval-rmse:4.75938 train-rmse:4.63251 ... [298] eval-rmse:0.583923 train-rmse:0.000705 [15:24:54] /workspace/src/tree/updater_prune.cc:74: tree pruning end, 1 roots, 22 extra nodes, 0 pruned nodes, max_depth=7 [299] eval-rmse:0.583926 train-rmse:0.000704 best : {'learning_rate': 0.05385158551863543, 'max_depth': 14, 'min_child_weight': 2, 'n_estimators': 173, 'subsample': 0.8} best param after transform : {'learning_rate': 0.051077031710372714, 'max_depth': 19, 'min_child_weight': 3, 'n_estimators': 323, 'subsample': 0.5800000000000001} rmse of the best xgboost: 0.5240080946197716
-
应用hyperopt给keras项目自动调参
2021-12-03 17:09:46python用hyperopt自动调参的简单介绍1、hyperopt干什么
这个python库可以在给定的参数空间中随机取点,每一组参数训练一个模型,最后记录和比较所有模型的表现,给出表现最好的一组参数。
它兼容大部分的机器学习任务,不需要对你的模型做什么太大的修改(只需要改一下超参数的写法,把超参数写到字典里面,例如lr改成params['lr'])。
2、hyperopt的使用
a) 安装并导入需要的程序
pip install hyperopt from hyperopt import hp, STATUS_OK, Trials, fmin
b) 定义参数空间
space = { 'lr':hp.loguniform('lr',-9,-5), 'lambda_l2':hp.loguniform('lambda_l2',-5,0), 'batch_size'hp.choice('batch_size',[8,16]) }
严格地说这里的参数指的是机器学习任务中的超参数,即训练过程中不进行梯度下降的部分。
参数空间是一个字典,在参数空间中,我定义了学习率lr,L2正则化系数lambda_l2,以及minibatch的大小batch_size。
其中,学习率和正则化系数的取值范围是一个均匀对数的范围,例如hp.loguniform('lr',-9,-5)就意味着取值范围是exp(-9)到exp(-5),指数在 [-9, -5] 之间均匀分布。注意这里确实是自然指数,不是10为底的指数。
minibatch大小的取值范围则是离散的,从给定的8和16中二选一。(你可可以把这个列表改成你需要的那些值)
除了loguniform和choice,hp中的参数空间还有:uniform(线性空间中均匀随机取值)、quniform(线性离散取值)、qloguniform等
c) 把调参的任务描述为一个以参数为输入的函数
例如,在我的参数空间中有lr, lambda_l2, batch_size这三个参数,我希望最后得到一个最小化测试集的f1指数的模型,可以写成如下的方式(我的代码其实就是训练模型并输出测试集上的f1指数,你把中间的部分改成你的训练代码就行,注意要把参数换成params['batch_size']这种形式):
def trainAmodel(params): #params={'lr':??, 'lambda_l2':??, 'batch_size':??} global X_train,X_test,Y_test,Y_train print('Params testing: ', params) # 创建模型 & 训练模型 model_v1 = V1_utils.modelV1(X_train.shape[1:],params) opt = tensorflow.keras.optimizers.Adam(lr=params['lr']) model_v1.compile(loss="binary_crossentropy", metrics=['accuracy'], optimizer=opt) steps_per_epoch = (np.shape(X_train)[0] + params['batch_size'] - 1) // params['batch_size'] history = model_v1.fit_generator(generator=data_generator(X_train, Y_train, params['batch_size']), steps_per_epoch=steps_per_epoch, epochs=30, verbose=0, validation_data=(X_test[::20], Y_test[::20]), ) # 评估模型 testres = model_v1.predict_generator(pre_generator(X_test, 4), verbose=0) testf1s, cache = V1_utils.fmeasure(Y_test, cvres) p, r = cache print("f1 = {}, precision = {}, recall = {}".format(testf1s, p, r)) # 返回关心的指标(越小越好),状态 return { 'loss':-testf1s, 'status':STATUS_OK }
注意,fmin默认是把指标越小认为表现越好,所以如果指标是f1指数、正确率这种越大越好的,可以加上负号,就变成越小越好。
另外,如果你希望在中途保存表现最好的模型,可以保存最好的表现,实时对比,如果更好就保存新的模型(我就不写了)。
d) 最后调用fmin开始跑不同参数下的模型,并保存。
trials = Trials() best = fmin(trainAmodel, space, algo=tpe.suggest, max_evals=50, trials=trials) import numpy as np filename= 'model/v1/log_v1_4.npz' np.savez(filename,trails=trials,best=best)
fmin的参数:
max_evals:要跑多少个模型,这个视你的需要,跑的越多肯多越有可能找到表现更好的模型,但是也意味着耗时增加。
algo:我还不清楚,应该是选择参数的算法?我直接用的suggest,也许选择一些算法能提高搜索效率。
3、结果
trials中会保留每一次训练的超参数、模型表现,我们可以根据这些画出模型在参数空间中的表现,帮助我们选择最后的超参数。例如我的这个结果:
-
自动调参——贝叶斯优化算法hyperopt
2021-01-12 05:51:28本篇文章主要记录了贝叶斯优化算法hyperopt的学习笔记,如果想看自动化调参中的网格调参和遗传优化算法TPOT,请查看我另外两篇文章:网格搜索gridSearchCV和遗传优化算法TPOT。1、算法思想贝叶斯优化算法与网格搜索...注:转载请注明出处。
本篇文章主要记录了贝叶斯优化算法hyperopt的学习笔记,如果想看自动化调参中的网格调参和遗传优化算法TPOT,请查看我另外两篇文章:网格搜索gridSearchCV和遗传优化算法TPOT。
1、算法思想
贝叶斯优化算法与网格搜索和随机搜索完全不同,会充分利用之前测试点的信息。贝叶斯优化算法通过对目标函数形状进行学习,找到使目标函数想全局最优提升的参数。
2、具体步骤首先根据先验分布,假设一个搜索函数。
然后每次使用新的测试点来测试目标函数时,利用这个信息来更新目标函数的先验分布。
最后,算法测试由后验分布给出的全局最值可能出现的位置的点。
3、缺陷与弥补缺陷:一旦找到一个局部最优,会在该区域不断地采样,很容易陷入局部最优值。
弥补方式:在探索和利用之间找到一个平衡点。“探索”就是在还未取样的区域获取采样点;利用是在根据后验分布在最可能出现全局最值的区域进行采样。
4、具体实现-python库 hyperopt
1. 功能可以针对某个模型进行调优。
可以同时调整多个模型的超参,并取得全局最优模型。–棒棒棒!!
2. hyperopt 参数简介需导入模块:hyperopt
调用方法和主要参数
1
2
3
4
5
6
7from 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:作用就是在有限的迭代次数下,求使目标函数fn取得最小值的超参数(超参数的阈值在space中),在space中搜索超参数的方法使由algo进行指定。
fn :目标函数当不是求最小值时,需要转化为求最小值。
space:超参数的阈值空间。
algo:超参数搜索算法
max_evals: 最大迭代次数
输出历史结果,甚至进行可视化:trails matplotlib.pyplot
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29from hyperopt import STATUS_OK,Trials
fspace={
'x': hp.uniform('x',-5,5)
}
def f(params):
x=params['x']
val=x**2
return {'loss': val,'status': STATUS_OK}
trials = Trials()
best1=fmin(fn=f,space=fspace,algo=tpe.suggest,max_evals=500,trials=trials)
print(best1)
print('trials:')
for trial in trials.trials[:10]:
print(trial)
## 可视化
# x随时间t的变化
import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xs = [t['tid'] for t in trials.trials]
ys = [t['misc']['vals']['x'] for t in trials.trials]
ax.set_xlim(xs[0]-10, xs[-1]+10)
ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)
ax.set_title('$x$ $vs$ $t$ ', fontsize=18)
ax.set_xlabel('$t$', fontsize=16)
ax.set_ylabel('$x$', fontsize=16)
plt.show()
输出图片结果:由图片可以看出最初算法从整个范围中均匀地选择值,但随着时间的推移以及参数对目标函数的影响了解越来越多,该算法越来越聚焦于它认为会取得最大收益的区域-一个接近0的范围。它仍然探索整个解空间,但频率有所下降。
1
2
3
4
5
6
7
8
9
10
11# 目标函数随时间t的变化
import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xs = [t['tid'] for t in trials.trials]
ys = [t['result']['loss'] for t in trials.trials]
ax.set_xlim(xs[0]-10, xs[-1]+10)
ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)
ax.set_title('$y$ $vs$ $t$ ', fontsize=18)
ax.set_xlabel('$t$', fontsize=16)
ax.set_ylabel('$y$', fontsize=16)
plt.show()
输出图片结果:可以看出目标函数逐渐趋向最小值0.
目标函数与x的变化
1
2
3
4
5
6
7
8
9import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xs = [t['misc']['vals']['x'] for t in trials.trials]
ys = [t['result']['loss'] for t in trials.trials]
ax.scatter(xs, ys, s=20, linewidth=0.01, alpha=0.75)
ax.set_title('$y$ $vs$ $x$ ', fontsize=18)
ax.set_xlabel('$x$', fontsize=16)
ax.set_ylabel('$y$', fontsize=16)
plt.show()
输出图片结果:可以看出在y取最小值处,点比较密集。
功能2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63digits = datasets.load_digits()
X = digits.data
y = digits.target
print X.shape, y.shape
def hyperopt_train_test(params):
t = params['type']
del params['type']
if t == 'naive_bayes':
clf = BernoulliNB(**params)
elif t == 'svm':
clf = SVC(**params)
elif t == 'dtree':
clf = DecisionTreeClassifier(**params)
elif t == 'knn':
clf = KNeighborsClassifier(**params)
else:
return 0
return cross_val_score(clf, X, y).mean()
space = hp.choice('classifier_type', [
{
'type': 'naive_bayes',
'alpha': hp.uniform('alpha', 0.0, 2.0)
},
{
'type': 'svm',
'C': hp.uniform('C', 0, 10.0),
'kernel': hp.choice('kernel', ['linear', 'rbf']),
'gamma': hp.uniform('gamma', 0, 20.0)
},
{
'type': 'randomforest',
'max_depth': hp.choice('max_depth', range(1,20)),
'max_features': hp.choice('max_features', range(1,5)),
'n_estimators': hp.choice('n_estimators', range(1,20)),
'criterion': hp.choice('criterion', ["gini", "entropy"]),
'scale': hp.choice('scale', [0, 1]),
'normalize': hp.choice('normalize', [0, 1])
},
{
'type': 'knn',
'n_neighbors': hp.choice('knn_n_neighbors', range(1,50))
}
])
count = 0
best = 0
def f(params):
global best, count
count += 1
acc = hyperopt_train_test(params.copy())
if acc > best:
print 'new best:', acc, 'using', params['type']
best = acc
if count % 50 == 0:
print 'iters:', count, ', acc:', acc, 'using', params
return {'loss': -acc, 'status': STATUS_OK}
trials = Trials()
best = fmin(f, space, algo=tpe.suggest, max_evals=1500, trials=trials)
print 'best:'
print best
5、参考
-
【机器学习实践】自动调参的实践(hyperopt)
2019-04-25 10:12:04直到一提的是,keras有其对应的自动调参工具:hyperas[8],你甚至可以用它来调整神经网络的结构。 } 结语: { 我对西瓜书第10章的内容还是有些不明白,所以最近买了csdn上的视频课[9],先看着... -
自动调参库hyperopt+lightgbm 调参demo
2018-11-08 14:25:00自动调参库hyperopt可用tpe算法自动调参,实测强于随机调参。 hyperopt 需要自己写个输入参数,返回模型分数的函数(只能求最小化,如果分数是求最大化的,加个负号),设置参数空间。 本来最优参数fmin函数会自己... -
hyperopt自动调参初体验
2022-04-27 17:24:35想要使用hyperopt自动调参,首先得设定你参数的取值范围: space = { 'k': hp.uniformint('k', 0, 10), 'b': hp.uniformint('b', -10, 10), } 接着,你要写下一个函数——在这个函数中写你的模型(只要可以预测出... -
python调参神器hyperopt
2017-03-04 11:28:22机器学习常见的模型有KNN,SVM,PCA,决策树,GBDT等一系列的算法,但是在实际应用中,我们需要选取合适的模型,并对模型调参,得到一组合适的参数。尤其是在模型的调参阶段,需要花费大量的时间和精力,却又效率低下... -
CatBoost自动调参—Optuna和Hyperopt耗时和效果对比
2021-10-28 17:18:10本文主要讲解:Optuna和Hyperopt性能对比(catboost示例) -
hyperopt自动调参
2018-10-22 20:05:00hyperopt自动调参 在传统机器学习和深度学习领域经常需要调参,调参有些是通过通过对数据和算法的理解进行的,这当然是上上策,但还有相当一部分属于"黑盒" hyperopt可以帮助我们做很多索然无味的调参工作 示例 直接... -
一文掌握模型调参神器:Hyperopt
2022-04-29 00:26:32本文将介绍一种快速有效的方法用于实现机器学习模型的调参。有两种常用的调参方法:网格搜索和随机搜索。每一种都有自己的优点和缺点。网格搜索速度慢,但在搜索整个搜索空间方面效果很好,而随机... -
使用Hyperopt实现机器学习自动调参
2021-04-17 12:27:31文章目录机器学习自动调参1. Hyperopt**Hyperopt搜索参数空间**参数空间的设置使用sample函数从参数空间内采样:在参数空间内使用函数:**指定搜索的算法**实例Hyperopt调参XGBoost2. 贝叶斯调参 机器学习自动调参 ... -
机器学习自动调参小试
2021-06-07 15:01:36""" 贝叶斯自动寻参数 :param_space: 参数范围,组合范围 :X_train: 训练集特征 :y_train: 寻链接标签 :X_test: 测试集特征 :y_test: 测试集标签 :num_eval: 寻参次数 :log_path: log文件存储路径 """ start = time... -
使用Ray Tune自动调参
2022-04-19 22:31:21本文基于PyTorch框架构建的卷积网络模型介绍如何使用Ray Tune进行自动调参。 提示:以下是本篇文章正文内容,下面案例可供参考 一、Ray Tune是什么? Ray Tune是一个用来实验执行和超参数调优的Python包,其中集成... -
基于贝叶斯优化方法的自动调参实现
2021-10-27 22:46:06文章目录1. 贝叶斯优化方法2. Python中的选择3. 优化问题的四个部分4. 代码演示 1. 贝叶斯优化方法 (注意是方法,是一种思想) 贝叶斯优化通过基于目标函数的过去评估结果建立替代函数...贝叶斯调参发使用不断更新的 -
AutoML: 自动调参工具Ray tune
2021-04-14 10:10:38强化学习 NNI 支持 支持 支持 支持 Google Vizier 支持 支持 支持 支持 ray tune 支持 不支持 支持 支持 支持 Hyteropt 支持 不支持 支持 支持 NNI/Google Vizier 偏向神经网络参数和模型结构的自动化搜索。... -
自动化机器学习(AutoML)之自动贝叶斯调参
2018-07-24 17:38:58【导读】机器学习中,调参是一项繁琐但至关重要的任务,因为它很大程度上影响了算法的性能。手动调参十分耗时,网格和随机搜索不需要人力,但需要很长的运行时间。因此,诞生了许多自动调整超参数的方法。贝叶斯优化... -
一文详解模型调参神器:Hyperopt,体验后真的很棒
2022-05-02 10:59:16本文将介绍一种快速有效的方法用于实现机器学习模型的调参。有两种常用的调参方法:网格搜索和随机搜索。每一种都有自己的优点和缺点。网格搜索速度慢,但在搜索整个搜索空间方面效果很好,而随机搜索很快,但可能会... -
[自动调参]深度学习模型的超参数自动化调优详解
2019-01-10 20:21:04自动调参 即可获取。 HFT 比特币预测 我使用的数据来自 Kaggle,这是用户 @Zielak 贴出的比特币过去 5 年的每分钟价格数据,数据集地址:https://www.kaggle.com/mczielinski/bitcoin-historical-data。 比特币价格... -
机器学习调参自动优化方法
2021-09-02 00:22:14本文旨在介绍当前被大家广为所知的超参自动优化方法,像网格搜索、随机搜索、贝叶斯优化和Hyperband,并附有相关的样例代码供大家学习。一、网格搜索(Grid Search)网格搜索是暴力... -
机器学习4种调参自动优化方法,第二款是我的最爱!
2021-09-01 23:16:39本文旨在介绍当前被大家广为所知的超参自动优化方法,像网格搜索、随机搜索、贝叶斯优化和Hyperband,并附有相关的样例代码供大家学习。一、网格搜索(Grid Search)网格搜索是暴力搜索,在给定超参搜索空间内,尝试...