XGBoost

来源:互联网 发布:勇者盟约精灵升星数据 编辑:程序博客网 时间:2024/05/16 10:17

声明: 本片博客是有关XGBoost 的总结,全部是复制过来的。仅为方便阅读。

xgboost 安装: Ubuntu   http://blog.csdn.net/qq_26192973/article/details/52141606


参考博客:   http://blog.csdn.net/wzmsltw/article/details/50994481

                        http://www.2cto.com/kf/201607/528771.html

                       


(  一  )  参数


在analytics vidhya上看到一篇<Complete Guide to Parameter Tuning in XGBoost in Python>,写的很好。因此打算翻译一下这篇文章,也让自己有更深的印象。具体内容主要翻译文章的关键意思。

原文见:

http://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/

这篇文章按照原文的分节,共分为三个部分,其中本章介绍第一部分。

 1、简介与XGboost

2、参数理解

3、参数调优



关于XGBoost的参数,发现已经有比较完善的翻译了。故本文转载其内容,并作了一些修改与拓展。

原文链接见:http://blog.csdn.NET/zc02051126/article/details/46711047

XGBoost参数

XGBoost的参数可以分为三种类型:通用参数、booster参数以及学习目标参数

  • General parameters:参数控制在提升(boosting)过程中使用哪种booster,常用的booster有树模型(tree)和线性模型(linear model)。
  • Booster parameters:这取决于使用哪种booster。
  • Learning Task parameters:控制学习的场景,例如在回归问题中会使用不同的参数控制排序。
  • 除了以上参数还可能有其它参数,在命令行中使用

General Parameters

  • booster [default=gbtree] 
    • 有两种模型可以选择gbtree和gblinear。gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算。缺省值为gbtree
  • silent [default=0] 
    • 取0时表示打印出运行时信息,取1时表示以缄默方式运行,不打印运行时的信息。缺省值为0
    • 建议取0,过程中的输出数据有助于理解模型以及调参。另外实际上我设置其为1也通常无法缄默运行。。
  • nthread [default to maximum number of threads available if not set] 
    • XGBoost运行时的线程数。缺省值是当前系统可以获得的最大线程数
    • 如果你希望以最大速度运行,建议不设置这个参数,模型将自动获得最大线程
  • num_pbuffer [set automatically by xgboost, no need to be set by user] 
    • size of prediction buffer, normally set to number of training instances. The buffers are used to save the prediction results of last boosting step.
  • num_feature [set automatically by xgboost, no need to be set by user] 
    • boosting过程中用到的特征维数,设置为特征个数。XGBoost会自动设置,不需要手工设置

Booster Parameters

From xgboost-unity, the bst: prefix is no longer needed for booster parameters. Parameter with or without bst: prefix will be equivalent(i.e. both bst:eta and eta will be valid parameter setting) .

Parameter for Tree Booster

  • eta [default=0.3] 
    • 为了防止过拟合,更新过程中用到的收缩步长。在每次提升计算之后,算法会直接获得新特征的权重。 eta通过缩减特征的权重使提升计算过程更加保守。缺省值为0.3
    • 取值范围为:[0,1]
    • 通常最后设置eta为0.01~0.2
  • gamma [default=0] 
    • minimum loss reduction required to make a further partition on a leaf node of the tree. the larger, the more conservative the algorithm will be.
    • range: [0,∞]
    • 模型在默认情况下,对于一个节点的划分只有在其loss function 得到结果大于0的情况下才进行,而gamma 给定了所需的最低loss function的值
    • gamma值使得算法更conservation,且其值依赖于loss function ,在模型中应该进行调参。
  • max_depth [default=6] 
    • 树的最大深度。缺省值为6
    • 取值范围为:[1,∞]
    • 指树的最大深度
    • 树的深度越大,则对数据的拟合程度越高(过拟合程度也越高)。即该参数也是控制过拟合
    • 建议通过交叉验证(xgb.cv ) 进行调参
    • 通常取值:3-10
  • min_child_weight [default=1] 
    • 孩子节点中最小的样本权重和。如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束。在现行回归模型中,这个参数是指建立每个模型所需要的最小样本数。该成熟越大算法越conservative。即调大这个参数能够控制过拟合。
    • 取值范围为: [0,∞]
  • max_delta_step [default=0] 
    • Maximum delta step we allow each tree’s weight estimation to be. If the value is set to 0, it means there is no constraint. If it is set to a positive value, it can help making the update step more conservative. Usually this parameter is not needed, but it might help in logistic regression when class is extremely imbalanced. Set it to value of 1-10 might help control the update
    • 取值范围为:[0,∞]
    • 如果取值为0,那么意味着无限制。如果取为正数,则其使得xgboost更新过程更加保守。
    • 通常不需要设置这个值,但在使用logistics 回归时,若类别极度不平衡,则调整该参数可能有效果
  • subsample [default=1] 
    • 用于训练模型的子样本占整个样本集合的比例。如果设置为0.5则意味着XGBoost将随机的从整个样本集合中抽取出50%的子样本建立树模型,这能够防止过拟合。
    • 取值范围为:(0,1]
  • colsample_bytree [default=1] 
    • 在建立树时对特征随机采样的比例。缺省值为1
    • 取值范围:(0,1]
  • colsample_bylevel[default=1]
    • 决定每次节点划分时子样例的比例
    • 通常不使用,因为subsample和colsample_bytree已经可以起到相同的作用了
  • scale_pos_weight[default=0]
    • A value greater than 0 can be used in case of high class imbalance as it helps in faster convergence.
    • 大于0的取值可以处理类别不平衡的情况。帮助模型更快收敛

Parameter for Linear Booster

  • lambda [default=0] 
    • L2 正则的惩罚系数
    • 用于处理XGBoost的正则化部分。通常不使用,但可以用来降低过拟合
  • alpha [default=0] 
    • L1 正则的惩罚系数
    • 当数据维度极高时可以使用,使得算法运行更快。
  • lambda_bias 
    • 在偏置上的L2正则。缺省值为0(在L1上没有偏置项的正则,因为L1时偏置不重要)

Task Parameters

  • objective [ default=reg:linear ] 
    • 定义学习任务及相应的学习目标,可选的目标函数如下:
    • “reg:linear” –线性回归。
    • “reg:logistic” –逻辑回归。
    • “binary:logistic” –二分类的逻辑回归问题,输出为概率。
    • “binary:logitraw” –二分类的逻辑回归问题,输出的结果为wTx。
    • “count:poisson” –计数问题的poisson回归,输出结果为poisson分布。
    • 在poisson回归中,max_delta_step的缺省值为0.7。(used to safeguard optimization)
    • “multi:softmax” –让XGBoost采用softmax目标函数处理多分类问题,同时需要设置参数num_class(类别个数)
    • “multi:softprob” –和softmax一样,但是输出的是ndata * nclass的向量,可以将该向量reshape成ndata行nclass列的矩阵。每行数据表示样本所属于每个类别的概率。
    • “rank:pairwise” –set XGBoost to do ranking task by minimizing the pairwise loss
  • base_score [ default=0.5 ] 
    • the initial prediction score of all instances, global bias
  • eval_metric [ default according to objective ] 
    • 校验数据所需要的评价指标,不同的目标函数将会有缺省的评价指标(rmse for regression, and error for classification, mean average precision for ranking)
    • 用户可以添加多种评价指标,对于Python用户要以list传递参数对给程序,而不是map参数list参数不会覆盖’eval_metric’
    • The choices are listed below:
    • “rmse”: root mean square error
    • “logloss”: negative log-likelihood
    • “error”: Binary classification error rate. It is calculated as #(wrong cases)/#(all cases). For the predictions, the evaluation will regard the instances with prediction value larger than 0.5 as positive instances, and the others as negative instances.
    • “merror”: Multiclass classification error rate. It is calculated as #(wrong cases)/#(all cases).
    • “mlogloss”: Multiclass logloss
    • “auc”: Area under the curve for ranking evaluation.
    • “ndcg”:Normalized Discounted Cumulative Gain
    • “map”:Mean average precision
    • “ndcg@n”,”map@n”: n can be assigned as an integer to cut off the top positions in the lists for evaluation.
    • “ndcg-“,”map-“,”ndcg@n-“,”map@n-“: In XGBoost, NDCG and MAP will evaluate the score of a list without any positive samples as 1. By adding “-” in the evaluation metric XGBoost will evaluate these score as 0 to be consistent under some conditions. 
      training repeatively
  • seed [ default=0 ] 
    • 随机数的种子。缺省值为0
    • 可以用于产生可重复的结果(每次取一样的seed即可得到相同的随机划分)

Console Parameters

The following parameters are only used in the console version of xgboost 
* use_buffer [ default=1 ] 
- 是否为输入创建二进制的缓存文件,缓存文件可以加速计算。缺省值为1 
* num_round 
- boosting迭代计算次数。 
* data 
- 输入数据的路径 
* test:data 
- 测试数据的路径 
* save_period [default=0] 
- 表示保存第i*save_period次迭代的模型。例如save_period=10表示每隔10迭代计算XGBoost将会保存中间结果,设置为0表示每次计算的模型都要保持。 
* task [default=train] options: train, pred, eval, dump 
- train:训练模型
- pred:对测试数据进行预测 
- eval:通过eval[name]=filenam定义评价指标 
- dump:将学习模型保存成文本格式 
* model_in [default=NULL] 
- 指向模型的路径在test, eval, dump都会用到,如果在training中定义XGBoost将会接着输入模型继续训练 
* model_out [default=NULL] 
- 训练完成后模型的保存路径,如果没有定义则会输出类似0003.model这样的结果,0003是第三次训练的模型结果。 
* model_dir [default=models] 
- 输出模型所保存的路径。 
* fmap 
- feature map, used for dump model 
* name_dump [default=dump.txt] 
- name of model dump file 
* name_pred [default=pred.txt] 
- 预测结果文件 
* pred_margin [default=0] 
- 输出预测的边界,而不是转换后的概率


如果你比较习惯scikit-learn的参数形式,那么XGBoost的python 版本也提供了sklearn形式的接口 XGBClassifier。它使用sklearn形式的参数命名方式,对应关系如下:

  1. eta –> learning_rate
  2. lambda –> reg_lambda
  3. alpha –> reg_alpha


(二) 调优指南

 http://blog.csdn.net/u010414589/article/details/51153310


本节介绍三部分内容: 
- xgboost 基本方法和默认参数 
- 实战经验中调参方法 
- 基于实例具体分析

1.xgboost 基本方法和默认参数

在训练过程中主要用到两个方法:xgboost.train()和xgboost.cv().

#xgboost.train()APIxgboost.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)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
  • params 这是一个字典,里面包含着训练中的参数关键字和对应的值,形式是params = {‘booster’:’gbtree’,’eta’:0.1}
  • dtrain 训练的数据
  • num_boost_round 这是指提升迭代的个数
  • evals 这是一个列表,用于对训练过程中进行评估列表中的元素。形式是evals = [(dtrain,’train’),(dval,’val’)]或者是evals = [(dtrain,’train’)],对于第一种情况,它使得我们可以在训练过程中观察验证集的效果。
  • obj,自定义目的函数
  • feval,自定义评估函数
  • maximize ,是否对评估函数进行最大化
  • early_stopping_rounds,早期停止次数 ,假设为100,验证集的误差迭代到一定程度在100次内不能再继续降低,就停止迭代。这要求evals 里至少有 一个元素,如果有多个,按最后一个去执行。返回的是最后的迭代次数(不是最好的)。如果early_stopping_rounds 存在,则模型会生成三个属性,bst.best_score,bst.best_iteration,和bst.best_ntree_limit
  • evals_result 字典,存储在watchlist 中的元素的评估结果。
  • verbose_eval (可以输入布尔型或数值型),也要求evals 里至少有 一个元素。如果为True ,则对evals中元素的评估结果会输出在结果中;如果输入数字,假设为5,则每隔5个迭代输出一次。
  • learning_rates 每一次提升的学习率的列表,
  • xgb_model ,在训练之前用于加载的xgb model。

2.实战经验中调参方法

首先 parameters 设置如下:

params = {            'booster':'gbtree',            'objective':'binary:logistic',            'eta':0.1,            'max_depth':10,            'subsample':1.0,            'min_child_weight':5,            'colsample_bytree':0.2,            'scale_pos_weight':0.1,            'eval_metric':'auc',            'gamma':0.2,                        'lambda':300}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • colsample_bytree 要依据特征个数来判断
  • objective 目标函数的选择要根据问题确定,如果是回归问题 ,一般是 reg:linear , reg:logistic , count:poisson 如果是分类问题,一般是binary:logistic ,rank:pairwise

参数初步定之后划分20%为验证集,准备一个watchlist 给train和validation set ,设置num_round 足够大(比如100000),以至于你能发现每一个round 的验证集预测结果,如果在某一个round后 validation set 的预测误差上升了,你就可以停止掉正在运行的程序了。

watchlist = [(dtrain,'train'),(dval,'val')]model = xgb.train(params,dtrain,num_boost_round=100000,evals = watchlist)
  • 1
  • 2
  • 1
  • 2

然后开始逐个调参了。

  • 首先调整max_depth ,通常max_depth 这个参数与其他参数关系不大,初始值设置为10,找到一个最好的误差值,然后就可以调整参数与这个误差值进行对比。比如调整到8,如果此时最好的误差变高了,那么下次就调整到12;如果调整到12,误差值比10 的低,那么下次可以尝试调整到15.
  • 在找到了最优的max_depth之后,可以开始调整subsample,初始值设置为1,然后调整到0.8 如果误差值变高,下次就调整到0.9,如果还是变高,就保持为1.0
  • 接着开始调整min_child_weight , 方法与上面同理
  • 再接着调整colsample_bytree
  • 经过上面的调整,已经得到了一组参数,这时调整eta 到0.05,然后让程序运行来得到一个最佳的num_round,(在 误差值开始上升趋势的时候为最佳 )

 三 . 调参 

 参考: http://blog.csdn.net/q383700092/article/details/53763328

github:  https://github.com/dmlc/xgboost 
论文参考:http://www.kaggle.com/blobs/download/forum-message-attachment-files/4087/xgboost-paper.pdf

基本思路及优点

http://blog.csdn.net/q383700092/article/details/60954996 
参考http://dataunion.org/15787.html 
http://blog.csdn.net/china1000/article/details/51106856 
在有监督学习中,我们通常会构造一个目标函数和一个预测函数,使用训练样本对目标函数最小化学习到相关的参数,然后用预测函数和训练样本得到的参数来对未知的样本进行分类的标注或者数值的预测。 
1. Boosting Tree构造树来拟合残差,而Xgboost引入了二阶导来进行求解,并且引入了节点的数目、参数的L2正则来评估模型的复杂度,构造Xgboost的预测函数与目标函数。 
2. 在分裂点选择的时候也以目标函数最小化为目标。 
优点: 
1. 显示的把树模型复杂度作为正则项加到优化目标中。 
2. 公式推导中用到了二阶导数,用了二阶泰勒展开。(GBDT用牛顿法貌似也是二阶信息) 
3. 实现了分裂点寻找近似算法。 
4. 利用了特征的稀疏性。 
5. 数据事先排序并且以block形式存储,有利于并行计算。 
6. 基于分布式通信框架rabit,可以运行在MPI和yarn上。(最新已经不基于rabit了) 
7. 实现做了面向体系结构的优化,针对cache和内存做了性能优化。

原理推导及与GBDT区别

http://blog.csdn.net/q383700092/article/details/60954996 
参考http://dataunion.org/15787.html 
https://www.zhihu.com/question/41354392

参数说明

参考http://blog.csdn.net/han_xiaoyang/article/details/52665396 
参数 
booster:默认 gbtree效果好 (linear booster很少用到) 
gbtree:基于树的模型 
gbliner:线性模型 
silent[默认0] 
nthread[默认值为最大可能的线程数] 
eta[默认0.3] 学习率 典型值为0.01-0.2 
min_child_weight[默认 1 ] 决定最小叶子节点样本权重和 值较大,避免过拟合 值过高,会导致欠拟合 
max_depth[默认6] 
gamma[默认0] 指定了节点分裂所需的最小损失函数下降值。 这个参数的值越大,算法越保守 
subsample[默认1] 对于每棵树,随机采样的比例 减小,算法保守,避免过拟合。值设置得过小,它会导致欠拟合 典型值:0.5-1 
colsample_bytree[默认1] 每棵随机采样的列数的占比 
colsample_bylevel[默认1] 树的每一级的每一次分裂,对列数的采样的占比 
lambda[默认1] 权重的L2正则化项 
alpha[默认1] 权重的L1正则化项 
scale_pos_weight[默认1] 在各类别样本十分不平衡时,参数设定为一个正值,可以使算法更快收敛 
objective[默认reg:linear] 最小化的损失函数 
binary:logistic 二分类的逻辑回归,返回预测的概率(不是类别)。 multi:softmax 使用softmax的多分类器,返回预测的类别(不是概率)。 
在这种情况下,你还需要多设一个参数:num_class(类别数目)。 multi:softprob 和multi:softmax参数一样,但是返回的是每个数据属于各个类别的概率。 
eval_metric[默认值取决于objective参数的取值] 
对于回归问题,默认值是rmse,对于分类问题,默认值是error。 典型值有: 
rmse 均方根误差 mae 平均绝对误差 logloss 负对数似然函数值 
error 二分类错误率 merror 多分类错误率 mlogloss 多分类logloss损失函数 auc 曲线下面积 
seed(默认0) 随机数的种子 设置它可以复现随机数据的结果

sklearn包,XGBClassifier会改变的函数名 
eta ->learning_rate 
lambda->reg_lambda 
alpha->reg_alpha

常用调整参数:

第一步:确定学习速率和tree_based 参数调优的估计器数目

树的最大深度一般3-10 
max_depth = 5 
节点分裂所需的最小损失函数下降值0.1到0.2 
gamma = 0 
采样 
subsample= 0.8, 
colsample_bytree = 0.8 
比较小的值,适用极不平衡的分类问题 
min_child_weight = 1 
类别十分不平衡 
scale_pos_weight = 1

from xgboost import XGBClassifierxgb1 = XGBClassifier( learning_rate =0.1, n_estimators=1000, max_depth=5, min_child_weight=1, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

第二步: max_depth 和 min_weight 参数调优

grid_search参考 
http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html 
http://blog.csdn.net/abcjennifer/article/details/23884761 
网格搜索scoring=’roc_auc’只支持二分类,多分类需要修改scoring(默认支持多分类)

param_test1 = { 'max_depth':range(3,10,2), 'min_child_weight':range(1,6,2)}#param_test2 = { 'max_depth':[4,5,6], 'min_child_weight':[4,5,6]}from sklearn import svm, grid_search, datasetsfrom sklearn import grid_searchgsearch1 = grid_search.GridSearchCV(estimator = XGBClassifier(learning_rate =0.1,n_estimators=140, max_depth=5,min_child_weight=1,gamma=0,subsample=0.8,colsample_bytree=0.8,objective= 'binary:logistic',nthread=4,scale_pos_weight=1,seed=27),param_grid = param_test1,scoring='roc_auc',n_jobs=4,iid=False,cv=5)gsearch1.fit(train[predictors],train[target])gsearch1.grid_scores_, gsearch1.best_params_,gsearch1.best_score_#网格搜索scoring='roc_auc'只支持二分类,多分类需要修改scoring(默认支持多分类)
  • 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
  • 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

第三步:gamma参数调优

param_test3 = { 'gamma':[i/10.0 for i in range(0,5)]}gsearch3 = GridSearchCV(estimator = XGBClassifier( learning_rate =0.1, n_estimators=140, max_depth=4, min_child_weight=6, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1,seed=27), param_grid = param_test3, scoring='roc_auc',n_jobs=4,iid=False, cv=5)gsearch3.fit(train[predictors],train[target])gsearch3.grid_scores_, gsearch3.best_params_, gsearch3.best_score_
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

第四步:调整subsample 和 colsample_bytree 参数

#取0.6,0.7,0.8,0.9作为起始值param_test4 = { 'subsample':[i/10.0 for i in range(6,10)], 'colsample_bytree':[i/10.0 for i in range(6,10)]}gsearch4 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1,n_estimators=177,max_depth=3,min_child_weight=4,gamma=0.1,subsample=0.8,colsample_bytree=0.8,objective= 'binary:logistic',nthread=4,scale_pos_weight=1,seed=27),param_grid = param_test4,scoring='roc_auc',n_jobs=4,iid=False,cv=5)gsearch4.fit(train[predictors],train[target])gsearch4.grid_scores_, gsearch4.best_params_, gsearch4.best_score_
  • 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
  • 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

第五步:正则化参数调优

param_test6 = { 'reg_alpha':[1e-5, 1e-2, 0.1, 1, 100]}gsearch6 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1,n_estimators=177,max_depth=4,min_child_weight=6,gamma=0.1,subsample=0.8,colsample_bytree=0.8,objective= 'binary:logistic',nthread=4,scale_pos_weight=1,seed=27),param_grid = param_test6,scoring='roc_auc',n_jobs=4,iid=False,cv=5)gsearch6.fit(train[predictors],train[target])gsearch6.grid_scores_, gsearch6.best_params_, gsearch6.best_score_
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

第六步:降低学习速率

xgb4 = XGBClassifier( learning_rate =0.01, n_estimators=5000, max_depth=4, min_child_weight=6, gamma=0, subsample=0.8, colsample_bytree=0.8, reg_alpha=0.005, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27)modelfit(xgb4, train, predictors)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

python示例

import xgboost as xgbimport pandas as pd#获取数据from sklearn import cross_validationfrom sklearn.datasets import load_irisiris = load_iris()#切分数据集X_train, X_test, y_train, y_test = cross_validation.train_test_split(iris.data, iris.target, test_size=0.33, random_state=42)#设置参数m_class = xgb.XGBClassifier( learning_rate =0.1, n_estimators=1000, max_depth=5, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, seed=27)#训练m_class.fit(X_train, y_train)test_21 = m_class.predict(X_test)print "Accuracy : %.2f" % metrics.accuracy_score(y_test, test_21)#预测概率#test_2 = m_class.predict_proba(X_test)#查看AUC评价标准from sklearn import metricsprint "Accuracy : %.2f" % metrics.accuracy_score(y_test, test_21)##必须二分类才能计算##print "AUC Score (Train): %f" % metrics.roc_auc_score(y_test, test_2)#查看重要程度feat_imp = pd.Series(m_class.booster().get_fscore()).sort_values(ascending=False)feat_imp.plot(kind='bar', title='Feature Importances')import matplotlib.pyplot as pltplt.show()#回归#m_regress = xgb.XGBRegressor(n_estimators=1000,seed=0)#m_regress.fit(X_train, y_train)#test_1 = m_regress.predict(X_test)
  • 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
  • 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

整理

xgb原始

from sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom  sklearn.datasets  import  make_hastie_10_2import xgboost as xgb#记录程序运行时间import time start_time = time.time()X, y = make_hastie_10_2(random_state=0)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)##test_size测试集合所占比例#xgb矩阵赋值xgb_train = xgb.DMatrix(X_train, label=y_train)xgb_test = xgb.DMatrix(X_test,label=y_test)##参数params={'booster':'gbtree','silent':1 ,#设置成1则没有运行信息输出,最好是设置为0.#'nthread':7,# cpu 线程数 默认最大'eta': 0.007, # 如同学习率'min_child_weight':3, # 这个参数默认是 1,是每个叶子里面 h 的和至少是多少,对正负样本不均衡时的 0-1 分类而言#,假设 h 在 0.01 附近,min_child_weight 为 1 意味着叶子节点中最少需要包含 100 个样本。#这个参数非常影响结果,控制叶子节点中二阶导的和的最小值,该参数值越小,越容易 overfitting。'max_depth':6, # 构建树的深度,越大越容易过拟合'gamma':0.1,  # 树的叶子节点上作进一步分区所需的最小损失减少,越大越保守,一般0.1、0.2这样子。'subsample':0.7, # 随机采样训练样本'colsample_bytree':0.7, # 生成树时进行的列采样 'lambda':2,  # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。#'alpha':0, # L1 正则项参数#'scale_pos_weight':1, #如果取值大于0的话,在类别样本不平衡的情况下有助于快速收敛。#'objective': 'multi:softmax', #多分类的问题#'num_class':10, # 类别数,多分类与 multisoftmax 并用'seed':1000, #随机种子#'eval_metric': 'auc'}plst = list(params.items())num_rounds = 100 # 迭代次数watchlist = [(xgb_train, 'train'),(xgb_test, 'val')]#训练模型并保存# early_stopping_rounds 当设置的迭代次数较大时,early_stopping_rounds 可在一定的迭代次数内准确率没有提升就停止训练model = xgb.train(plst, xgb_train, num_rounds, watchlist,early_stopping_rounds=100,pred_margin=1)#model.save_model('./model/xgb.model') # 用于存储训练出的模型print "best best_ntree_limit",model.best_ntree_limit y_pred = model.predict(xgb_test,ntree_limit=model.best_ntree_limit)print ('error=%f' % (  sum(1 for i in range(len(y_pred)) if int(y_pred[i]>0.5)!=y_test[i]) /float(len(y_pred))))  #输出运行时长cost_time = time.time()-start_timeprint "xgboost success!",'\n',"cost time:",cost_time,"(s)......"
  • 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
  • 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

xgb使用sklearn接口(推荐)

官方 
会改变的函数名是: 
eta -> learning_rate 
lambda -> reg_lambda 
alpha -> reg_alpha

from sklearn.model_selection import train_test_splitfrom sklearn import metricsfrom  sklearn.datasets  import  make_hastie_10_2from xgboost.sklearn import XGBClassifierX, y = make_hastie_10_2(random_state=0)X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)##test_size测试集合所占比例clf = XGBClassifier(silent=0 ,#设置成1则没有运行信息输出,最好是设置为0.是否在运行升级时打印消息。#nthread=4,# cpu 线程数 默认最大learning_rate= 0.3, # 如同学习率min_child_weight=1, # 这个参数默认是 1,是每个叶子里面 h 的和至少是多少,对正负样本不均衡时的 0-1 分类而言#,假设 h 在 0.01 附近,min_child_weight 为 1 意味着叶子节点中最少需要包含 100 个样本。#这个参数非常影响结果,控制叶子节点中二阶导的和的最小值,该参数值越小,越容易 overfitting。max_depth=6, # 构建树的深度,越大越容易过拟合gamma=0,  # 树的叶子节点上作进一步分区所需的最小损失减少,越大越保守,一般0.1、0.2这样子。subsample=1, # 随机采样训练样本 训练实例的子采样比max_delta_step=0,#最大增量步长,我们允许每个树的权重估计。colsample_bytree=1, # 生成树时进行的列采样 reg_lambda=1,  # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。#reg_alpha=0, # L1 正则项参数#scale_pos_weight=1, #如果取值大于0的话,在类别样本不平衡的情况下有助于快速收敛。平衡正负权重#objective= 'multi:softmax', #多分类的问题 指定学习任务和相应的学习目标#num_class=10, # 类别数,多分类与 multisoftmax 并用n_estimators=100, #树的个数seed=1000 #随机种子#eval_metric= 'auc')clf.fit(X_train,y_train,eval_metric='auc')#设置验证集合 verbose=False不打印过程clf.fit(X_train, y_train,eval_set=[(X_train, y_train), (X_val, y_val)],eval_metric='auc',verbose=False)#获取验证集合结果evals_result = clf.evals_result()y_true, y_pred = y_test, clf.predict(X_test)print"Accuracy : %.4g" % metrics.accuracy_score(y_true, y_pred)#回归#m_regress = xgb.XGBRegressor(n_estimators=1000,seed=0)
  • 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
  • 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

网格搜索

可以先固定一个参数 最优化后继续调整 
第一步:确定学习速率和tree_based 给个常见初始值 根据是否类别不平衡调节 
max_depth,min_child_weight,gamma,subsample,scale_pos_weight 
max_depth=3 起始值在4-6之间都是不错的选择。 
min_child_weight比较小的值解决极不平衡的分类问题eg:1 
subsample, colsample_bytree = 0.8: 这个是最常见的初始值了 
scale_pos_weight = 1: 这个值是因为类别十分不平衡。 
第二步: max_depth 和 min_weight 对最终结果有很大的影响 
‘max_depth’:range(3,10,2), 
‘min_child_weight’:range(1,6,2) 
先大范围地粗调参数,然后再小范围地微调。 
第三步:gamma参数调优 
‘gamma’:[i/10.0 for i in range(0,5)] 
第四步:调整subsample 和 colsample_bytree 参数 
‘subsample’:[i/100.0 for i in range(75,90,5)], 
‘colsample_bytree’:[i/100.0 for i in range(75,90,5)] 
第五步:正则化参数调优 
‘reg_alpha’:[1e-5, 1e-2, 0.1, 1, 100] 
‘reg_lambda’ 
第六步:降低学习速率 
learning_rate =0.01,

from sklearn.model_selection import GridSearchCVtuned_parameters= [{'n_estimators':[100,200,500],                  'max_depth':[3,5,7], ##range(3,10,2)                  'learning_rate':[0.5, 1.0],                  'subsample':[0.75,0.8,0.85,0.9]                  }]tuned_parameters= [{'n_estimators':[100,200,500,1000]                  }]clf = GridSearchCV(XGBClassifier(silent=0,nthread=4,learning_rate= 0.5,min_child_weight=1, max_depth=3,gamma=0,subsample=1,colsample_bytree=1,reg_lambda=1,seed=1000), param_grid=tuned_parameters,scoring='roc_auc',n_jobs=4,iid=False,cv=5)  clf.fit(X_train, y_train)##clf.grid_scores_, clf.best_params_, clf.best_score_print(clf.best_params_)y_true, y_pred = y_test, clf.predict(X_test)print"Accuracy : %.4g" % metrics.accuracy_score(y_true, y_pred) y_proba=clf.predict_proba(X_test)[:,1]print "AUC Score (Train): %f" % metrics.roc_auc_score(y_true, y_proba)               
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
from sklearn.model_selection import GridSearchCVparameters= [{'learning_rate':[0.01,0.1,0.3],'n_estimators':[1000,1200,1500,2000,2500]}]clf = GridSearchCV(XGBClassifier(             max_depth=3,             min_child_weight=1,             gamma=0.5,             subsample=0.6,             colsample_bytree=0.6,             objective= 'binary:logistic', #逻辑回归损失函数             scale_pos_weight=1,             reg_alpha=0,             reg_lambda=1,             seed=27            ),             param_grid=parameters,scoring='roc_auc')  clf.fit(X_train, y_train)print(clf.best_params_)  y_pre= clf.predict(X_test)y_pro= clf.predict_proba(X_test)[:,1] print "AUC Score : %f" % metrics.roc_auc_score(y_test, y_pro) print"Accuracy : %.4g" % metrics.accuracy_score(y_test, y_pre) 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

输出特征重要性

import pandas as pdimport matplotlib.pylab as pltfeat_imp = pd.Series(clf.booster().get_fscore()).sort_values(ascending=False)feat_imp.plot(kind='bar', title='Feature Importances')plt.ylabel('Feature Importance Score')plt.show()

优势

http://skyhigh233.com/blog/2016/12/03/para-tune-xgboost/

1.The XGBoost Advantage

我总是向往这个算法在预测模型里的提升能力。当我在探索它的表现和高准确率下的科学原理的时候,我发现了它的很多优点:

正则化
  • 标准的梯度提升机器(GBM)的实现没有像XGBoost那样的正则项,因此它能够在过拟合方面有所帮助。
  • 实际上,XGBoost也被认为是一种“正则提升”技术。
并行处理
  • XGBoost实现了并行处理,和GBM比起来非常快。
  • 但是我们也知道提升是一个序列处理过程,因此如何才能做到并行化?我们知道每一棵树能够只根据之前的那一颗来建立,那么是什么阻碍了我们并行化建树?可以查看这个链接来深入探索:Parallel Gradient Boosting Decision Trees
  • XGBoost可以在Hadoop上实现。
高自由度
  • XGBoost允许用户自定义优化目标和评估标准。
  • 这增加了模型的一个全新的维度,并且并不会限制我们所能做的东西。
处理缺失值
  • XGBoost有内建的方法来处理缺失值。
  • 用户只需要提供一个不同值,而不是观察并将其作为一个参数。XGBoost在遇到缺失值的时候总是尝试着寻找不同的方式并学习如何去填充缺失值。
树剪枝
  • 当在分割的过程中遇到负损失时,GBM会停止从一个节点产生分支。因此这更像是一种贪婪算法。
  • 而XGBoost先产生分支直到最大深度,之后再开始回溯剪枝,并移除哪些不能够获得正收益的分割。
  • 另一个这么做的优点是当我们遇到一个负损失分割的时候,比如-2,那么如果接下来的划分为+10。如果是GBM,则是会在遇到-2的时候停止产生分支。但是XGBoost则会继续产生分支,这会使得最终的总分支得分为+8,从而保留这个分支。
内建交叉验证
  • XGBoost允许用户在每次提升的迭代过程中跑一次交叉验证,因此这很容易在跑一次的过程中得到最优的提升迭代次数。
  • 这不像GBM一样跑一个grid search并且只有固定的值能够被测试到。
可以衔接到已存在的模型上
  • 用户从它之前一次运行的最后一步迭代中开始训练XGBoost模型。这在某类具体的应用中有非常显著的优势。
  • sklearn里的GBM的实现同样有这个特性,因此在这一点上GBM和XGBoost一致。

                      
原创粉丝点击