贝叶斯调参-lgb

朴素贝叶斯

机器学习调参工具:Hyperopt

Hyperopt提供了一个优化接口,这个接口接受一个评估函数和参数空间,能计算出参数空间内的一个点的损失函数值。用户还要指定空间内参数的分布情况。

优化问题的四个部分

贝叶斯优化问题有四个部分:

目标函数:我们想要最小化的内容,在这里,目标函数是机器学习模型使用该组超参数在验证集上的损失。

域空间:要搜索的超参数的取值范围

优化算法:构造替代函数并选择下一个超参数值进行评估的方法。

结果历史记录:来自目标函数评估的存储结果,包括超参数和验证集上的损失。

即fmin()函数里面的一般参数,后两个可选

首先,定义一个目标函数,接受一个变量,计算后返回一个函数的损失值,比如要最小化函数q(x,y) = x**2 + y**2,然后,定义一个参数空间,比如x在0-1区间内取值,y是实数,所以

from hyperopt import hp

space = [hp.uniform(’x’, 0, 1), hp.normal(’y’, 0, 1)]

第三,指定搜索的算法,算法也就是hyperopt的fmin函数的algo参数的取值。当前支持的算法有随机搜索(对应是hyperopt.rand.suggest),模拟退火(对应是hyperopt.anneal.suggest),

TPE算法。举个栗子:

from hyperopt import hp, fmin, rand, tpe, space_eval

best = fmin(q, space, algo=rand.suggest)

print( space_eval(space, best))

搜索算法本身也有内置的参数决定如何去优化目标函数,我们可以指定搜索算法的参数,比如针对TPE,指定jobs:

from functools import partial

from hyperopt import hp, fmin, tpe

algo = partial(tpe.suggest, n_startup_jobs=10)

best = fmin(q, space, algo=algo)

print (space_eval(space, best))

关于参数空间的设置,比如优化函数q,输入

fmin(q,space=hp.uniform(‘a’,0,1))。

 

hp.uniform函数的第一个参数是标签,每个超参数在参数空间内必须具有独一无二的标签。

hp.choice返回一个选项,选项可以是list或者tuple.options可以是嵌套的表达式,用于组成条件参数。

hp.pchoice(label,p_options)以一定的概率返回一个p_options的一个选项。这个选项使得函数在搜索过程中对每个选项的可能性不均匀。

hp.uniform(label,low,high)参数在low和high之间均匀分布。

hp.quniform(label,low,high,q),参数的取值是round(uniform(low,high)/q)*q,适用于那些离散的取值。

hp.loguniform(label,low,high)绘制exp(uniform(low,high)),变量的取值范围是[exp(low),exp(high)] 。

hp.randint(label,upper) 返回一个在[0,upper)前闭后开的区间内的随机整数。

搜索空间可以含有list和dictionary。

 

#基于lgb的测试

from sklearn import datasets

import numpy as np

from sklearn.cross_validation import train_test_split

from sklearn.metrics import accuracy_score

import pandas as pd

from hyperopt import hp, fmin, rand, tpe, space_eval

 

train0=pd.read_csv(os.listdir()[1])

alldata=pd.read_csv(os.listdir()[5])

#训练数据

train_features=alldata.drop(['Unnamed: 0','SK_ID_CURR'],axis=1)[:len(train0)][:50000]

train_labels=train0['TARGET'][:50000]

 

#损失函数

import lightgbm as lgb

from hyperopt import STATUS_OK

#交叉验证次数

N_FOLDS = 5

 

# 数据变换

train_set = lgb.Dataset(train_features, train_labels)

 

#损失函数

def objective(params, n_folds=N_FOLDS):

   '''Objective function for Gradient Boosting Machine Hyperparameter Tuning'''

 

   # Perform n_fold cross validation with hyperparameters

   # Use early stopping and evalute based on ROC AUC

   cv_results = lgb.cv(params, train_set, nfold=n_folds, num_boost_round=1000,

                       early_stopping_rounds=100, metrics='auc', seed=50)

 

   # Extract the best score

   best_score = max(cv_results['auc-mean'])

 

   # Loss must be minimized

   loss = 1 - best_score

 

   # Dictionary with information for evaluation

   return {'loss': loss, 'params': params, 'status': STATUS_OK}

 

#参数区间

# Define the search space

space = {

    'boosting_type': 'gbdt', # 训练方式

    'objective': 'binary', # 目标 二分类

    'metric': 'auc', # 损失函数

    'is_unbalance': False,

    'max_depth':hp.randint("max_depth",10),

   'num_leaves':hp.choice('num_leaves',range(20,200,5)),

    'feature_fraction':hp.loguniform('feature_fraction',np.log(0.1), np.log(1)),

    'bagging_fraction':hp.loguniform('bagging_fraction',np.log(0.1), np.log(1)),

    'bagging_freq':hp.choice('bagging_freq',range(20,60,5)),

    'max_bin':hp.choice('max_bin',range(1,255,5)),

    'min_data_in_leaf': hp.choice('min_data_in_leaf',range(10,200,5)),

    'min_sum_hessian_in_leaf':hp.loguniform('min_sum_hessian_in_leaf', np.log(0.0001), np.log(0.005)),

    'lambda_l1': hp.uniform('lambda_l1', 0.0, 1.0),

   'lambda_l2': hp.uniform('lambda_l2', 0.0, 1.0),

    'min_split_gain':hp.loguniform( 'min_split_gain' ,np.log(0.1), np.log(1)),

   'learning_rate': hp.loguniform('learning_rate', np.log(0.01), np.log(0.2))

}

第三,指定搜索的算法,算法也就是hyperopt的fmin函数的algo参数的取值。当前支持的算法有随机搜索(对应是hyperopt.rand.suggest),模拟退火(对应是hyperopt.anneal.suggest),TPE算法

#指定算法参数

algo = partial(tpe.suggest, n_startup_jobs=10)

best = fmin(q, space, algo=algo)

print space_eval(space, best)

# Algorithm

tpe_algorithm = tpe.suggest

 

#测试

from hyperopt import fmin

MAX_EVALS = 100

# Optimize

best = fmin(fn = objective, space = space, algo = tpe.suggest, max_evals = MAX_EVALS)

作为参考,100次随机搜索迭代返回了一个模型,该模型在测试集上评分为ROC AUC

valid_0's auc: 0.73381

参考资料:

Lightgbm调参文档:http://lightgbm.apachecn.org/cn/latest/Parameters.html

python机器学习案例系列教程——LightGBM算法:

https://blog.csdn.net/luanpeng825485697/article/details/80236759

机器学习调参工具:Hyperopt

https://blog.csdn.net/fengchi863/article/details/80512715

 

猜你喜欢

转载自blog.csdn.net/weixin_41358871/article/details/81512387