将之前XGBoost的笔记整理在CSDN上。

一、通用参数

一、这些参数用来控制XGBoost的宏观功能。

1、booster[默认gbtree] 选择每次迭代的模型,有两种选择: gbtree:基于树的模型 gbliner:线性模型

2、silent[默认0] 当这个参数值为1时,静默模式开启,不会输出任何信息。 一般这个参数就保持默认的0,因为这样能帮我们更好地理解模型。

3、nthread[默认值为最大可能的线程数] 这个参数用来进行多线程控制,应当输入系统的核数。 如果你希望使用CPU全部的核,那就不要输入这个参数,算法会自动检测它。 还有两个参数,XGBoost会自动设置,目前你不用管它。接下来咱们一起看booster参数。

二、booster参数 尽管有两种booster可供选择,我这里只介绍tree booster,因为它的表现远远胜过linear booster,所以linear booster很少用到。

1、eta[默认0.3] 和GBM中的 learning rate 参数类似。 通过减少每一步的权重,可以提高模型的鲁棒性。 典型值为0.01-0.2。

2、min_child_weight[默认1] 决定最小叶子节点样本权重和。 和GBM的 min_child_leaf 参数类似,但不完全一样。XGBoost的这个参数是最小样本权重的和,而GBM参数是最小样本总数。 这个参数用于避免过拟合。当它的值较大时,可以避免模型学习到局部的特殊样本。 但是如果这个值过高,会导致欠拟合。这个参数需要使用CV来调整。

3、max_depth[默认6] 和GBM中的参数相同,这个值为树的最大深度。 这个值也是用来避免过拟合的。max_depth越大,模型会学到更具体更局部的样本。 需要使用CV函数来进行调优。 典型值:3-10

4、max_leaf_nodes 树上最大的节点或叶子的数量。 可以替代max_depth的作用。因为如果生成的是二叉树,一个深度为n的树最多生成n2个叶子。 如果定义了这个参数,GBM会忽略max_depth参数。

5、gamma[默认0] 在节点分裂时,只有分裂后损失函数的值下降了,才会分裂这个节点。Gamma指定了节点分裂所需的最小损失函数下降值。 这个参数的值越大,算法越保守。这个参数的值和损失函数息息相关,所以是需要调整的。

6、max_delta_step[默认0] 这参数限制每棵树权重改变的最大步长。如果这个参数的值为0,那就意味着没有约束。如果它被赋予了某个正值,那么它会让这个算法更加保守。 通常,这个参数不需要设置。但是当各类别的样本十分不平衡时,它对逻辑回归是很有帮助的。 这个参数一般用不到,但是你可以挖掘出来它更多的用处。

7、subsample[默认1] 和GBM中的subsample参数一模一样。这个参数控制对于每棵树,随机采样的比例。 减小这个参数的值,算法会更加保守,避免过拟合。但是,如果这个值设置得过小,它可能会导致欠拟合。 典型值:0.5-1

8、colsample_bytree[默认1] 和GBM里面的max_features参数类似。用来控制每棵随机采样的列数的占比(每一列是一个特征)。 典型值:0.5-1

9、colsample_bylevel[默认1] 用来控制树的每一级的每一次分裂,对列数的采样的占比。 我个人一般不太用这个参数,因为subsample参数和colsample_bytree参数可以起到相同的作用。但是如果感兴趣,可以挖掘这个参数更多的用处。

10、lambda[默认1] 权重的L2正则化项。(和Ridge regression类似)。 这个参数是用来控制XGBoost的正则化部分的。虽然大部分数据科学家很少用到这个参数,但是这个参数在减少过拟合上还是可以挖掘出更多用处的。

11、alpha[默认1] 权重的L1正则化项。(和Lasso regression类似)。 可以应用在很高维度的情况下,使得算法的速度更快。

12、scale_pos_weight[默认1] 在各类别样本十分不平衡时,把这个参数设定为一个正值,可以使算法更快收敛。

三、学习目标参数 这个参数用来控制理想的优化目标和每一步结果的度量方法。

1、objective[默认reg:linear] 这个参数定义需要被最小化的损失函数。最常用的值有: binary:logistic 二分类的逻辑回归,返回预测的概率(不是类别)。 multi:softmax 使用softmax的多分类器,返回预测的类别(不是概率)。 在这种情况下,你还需要多设一个参数:num_class(类别数目)。 multi:softprob 和multi:softmax参数一样,但是返回的是每个数据属于各个类别的概率。

2、eval_metric[默认值取决于objective参数的取值] 对于有效数据的度量方法。 对于回归问题,默认值是rmse,对于分类问题,默认值是error。 典型值有: rmse 均方根误差(∑Ni=1ϵ2N−−−−−√) mae 平均绝对误差(∑Ni=1|ϵ|N) logloss 负对数似然函数值 error 二分类错误率(阈值为0.5) merror 多分类错误率 mlogloss 多分类logloss损失函数 auc 曲线下面积

3、seed(默认0) 随机数的种子 设置它可以复现随机数据的结果,也可以用于调整参数

Python的XGBoost模块有一个sklearn包,XGBClassifier。这个包中的参数是按sklearn风格命名的。会改变的函数名是:

1、eta -> learning_rate

2、lambda -> reg_lambda

3、alpha -> reg_alpha

二、引入必要包

编译环境python2.7

import numpy as np
import pandas as pd
from xgboost.sklearn import XGBClassifier
from sklearn import  metrics
import xgboost as xgb
from sklearn.grid_search import GridSearchCV from sklearn.preprocessing import MinMaxScaler   #最大最小归一化
from sklearn.preprocessing import StandardScaler   #标准化
from sklearn.model_selection import train_test_split     #划分数据集
from sklearn.model_selection import cross_val_score
import matplotlib.pyplot as plt

三、读入文件并划分数据集

data=pd.read_csv('D:\data.csv',header=None)
#0-10列为特征
X=data.iloc[:,:11]
#第11列为标签
y=data.iloc[:,11]
params=[ 1, 4,  6, 7, 8, 9,10]
X=X[params]
mydict={5:0,6:1}
y=y.replace(mydict)
'''
data= pd.read_csv("G:/feature_code/wine_data.csv",header=None)
#0-10列为特征
X=data.iloc[:,:13]
#第11列为标签
y=data.iloc[:,13]
'''#划分训练集和测试集
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.3,random_state=0)
#此处采用最大最小归一化, 可以换成StandardScaler()归一化方法,如果用StandardScaler()方法的话,则不能使用MultinomialNB()模型
ss=MinMaxScaler()
#ss=StandardScaler()
X_train=ss.fit_transform(X_train)
X_test=ss.transform(X_test)

四、参数调优的一般方法

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

为了确定boosting参数,我们要先给其它参数一个初始值。咱们先按如下方法取值:

1、max_depth = 5 :这个参数的取值最好在3-10之间。我选的起始值为5,但是你也可以选择其它的值。起始值在4-6之间都是不错的选择。

2、min_child_weight = 1:在这里选了一个比较小的值,因为这是一个极不平衡的分类问题。因此,某些叶子节点下的值会比较小。

3、gamma = 0: 起始值也可以选其它比较小的值,在0.1到0.2之间就可以。这个参数后继也是要调整的。

4、subsample, colsample_bytree = 0.8: 这个是最常见的初始值了。典型值的范围在0.5-0.9之间。

5、scale_pos_weight = 1: 这个值是因为类别十分不平衡。

评分函数如下,cvresult.shape[0]是其中我们用的树的个数,cvresult的结果是一个DataFrame.

def tun_parameters(train_x,train_y):  #通过这个函数,确定树的个数xgb1 = 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',scale_pos_weight=1,seed=27)  modelfit(xgb1,train_x,train_y)  def modelfit(alg,X, y,useTrainCV=True, cv_folds=5, early_stopping_rounds=50):if useTrainCV:xgb_param = alg.get_xgb_params()xgtrain = xgb.DMatrix(X, label=y)cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds,metrics='auc', early_stopping_rounds=early_stopping_rounds)alg.set_params(n_estimators=cvresult.shape[0])#Fit the algorithm on the dataalg.fit(X, y,eval_metric='auc')#Predict training set:dtrain_predictions = alg.predict(X)dtrain_predprob = alg.predict_proba(X)[:,1]#Print model report:print "\nModel Report"print "Accuracy : %.4g" % metrics.accuracy_score(y, dtrain_predictions)print "AUC Score (Train): %f" % metrics.roc_auc_score(y, dtrain_predprob)feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)feat_imp.plot(kind='bar', title='Feature Importances')plt.ylabel('Feature Importance Score')plt.show()print ('n_estimators=',cvresult.shape[0])
tun_parameters(X_train,y_train)

得到的结果如下:

Model Report
Accuracy : 0.9932
AUC Score (Train): 0.999483

('n_estimators=', 149)

由以上可以得知,n_estimators在149附近得分较高,这里我们定为160。

第二步: max_depth 和 min_child_weight 参数调优

param_test1 = {'max_depth':range(3,10,1),'min_child_weight':range(1,6,1)
}
gsearch1 = GridSearchCV(estimator = XGBClassifier(learning_rate =0.1, n_estimators=160, max_depth=5,
min_child_weight=1, gamma=0, subsample=0.8,colsample_bytree=0.8,\objective= 'binary:logistic', nthread=8,scale_pos_weight=1, seed=27), param_grid = param_test1,scoring='roc_auc',n_jobs=-1,iid=False, cv=5)
gsearch1.fit(X_train,y_train)
gsearch1.grid_scores_, gsearch1.best_params_,     gsearch1.best_score_

输出结果:

([mean: 0.82976, std: 0.03871, params: {'max_depth': 3, 'min_child_weight': 1},mean: 0.82267, std: 0.03838, params: {'max_depth': 3, 'min_child_weight': 2},mean: 0.82381, std: 0.03256, params: {'max_depth': 3, 'min_child_weight': 3},mean: 0.82485, std: 0.03624, params: {'max_depth': 3, 'min_child_weight': 4},mean: 0.82675, std: 0.03886, params: {'max_depth': 3, 'min_child_weight': 5},mean: 0.83304, std: 0.03457, params: {'max_depth': 4, 'min_child_weight': 1},mean: 0.82880, std: 0.03161, params: {'max_depth': 4, 'min_child_weight': 2},mean: 0.82728, std: 0.03785, params: {'max_depth': 4, 'min_child_weight': 3},mean: 0.82573, std: 0.03456, params: {'max_depth': 4, 'min_child_weight': 4},mean: 0.82602, std: 0.03530, params: {'max_depth': 4, 'min_child_weight': 5},mean: 0.84278, std: 0.03508, params: {'max_depth': 5, 'min_child_weight': 1},mean: 0.83271, std: 0.03385, params: {'max_depth': 5, 'min_child_weight': 2},mean: 0.83704, std: 0.03842, params: {'max_depth': 5, 'min_child_weight': 3},mean: 0.83135, std: 0.03563, params: {'max_depth': 5, 'min_child_weight': 4},mean: 0.83296, std: 0.03596, params: {'max_depth': 5, 'min_child_weight': 5},mean: 0.84567, std: 0.03272, params: {'max_depth': 6, 'min_child_weight': 1},mean: 0.84004, std: 0.03596, params: {'max_depth': 6, 'min_child_weight': 2},mean: 0.84208, std: 0.03857, params: {'max_depth': 6, 'min_child_weight': 3},mean: 0.83590, std: 0.03457, params: {'max_depth': 6, 'min_child_weight': 4},mean: 0.83589, std: 0.03384, params: {'max_depth': 6, 'min_child_weight': 5},mean: 0.84671, std: 0.03359, params: {'max_depth': 7, 'min_child_weight': 1},mean: 0.84859, std: 0.03605, params: {'max_depth': 7, 'min_child_weight': 2},mean: 0.83874, std: 0.03580, params: {'max_depth': 7, 'min_child_weight': 3},mean: 0.83764, std: 0.03310, params: {'max_depth': 7, 'min_child_weight': 4},mean: 0.83819, std: 0.03368, params: {'max_depth': 7, 'min_child_weight': 5},mean: 0.85194, std: 0.02960, params: {'max_depth': 8, 'min_child_weight': 1},mean: 0.84527, std: 0.03501, params: {'max_depth': 8, 'min_child_weight': 2},mean: 0.84182, std: 0.03419, params: {'max_depth': 8, 'min_child_weight': 3},mean: 0.84404, std: 0.03891, params: {'max_depth': 8, 'min_child_weight': 4},mean: 0.83545, std: 0.03571, params: {'max_depth': 8, 'min_child_weight': 5},mean: 0.85286, std: 0.03072, params: {'max_depth': 9, 'min_child_weight': 1},mean: 0.84223, std: 0.03226, params: {'max_depth': 9, 'min_child_weight': 2},mean: 0.84194, std: 0.03670, params: {'max_depth': 9, 'min_child_weight': 3},mean: 0.83782, std: 0.03854, params: {'max_depth': 9, 'min_child_weight': 4},mean: 0.83986, std: 0.03436, params: {'max_depth': 9, 'min_child_weight': 5}],{'max_depth': 9, 'min_child_weight': 1},0.8528642989777853)

第三步:gamma参数调优

param_test3 = {  'gamma': [i / 10.0 for i in range(0, 5)]
}
gsearch3 = GridSearchCV(  estimator=XGBClassifier(learning_rate=0.1, n_estimators=160, max_depth=9, min_child_weight=1, gamma=0,  subsample=0.8, colsample_bytree=0.8, objective='binary:logistic', nthread=8,  scale_pos_weight=1, seed=27), param_grid=param_test3, scoring='roc_auc', n_jobs=-1,  iid=False, cv=5)
gsearch3.fit(X_train,y_train)
gsearch3.grid_scores_, gsearch3.best_params_, gsearch3.best_score_  
([mean: 0.85286, std: 0.03072, params: {'gamma': 0.0},mean: 0.85098, std: 0.03405, params: {'gamma': 0.1},mean: 0.84811, std: 0.03470, params: {'gamma': 0.2},mean: 0.84774, std: 0.03139, params: {'gamma': 0.3},mean: 0.85163, std: 0.03478, params: {'gamma': 0.4}],{'gamma': 0.0},0.8528642989777853)

第四步:调整subsample 和 colsample_bytree 参数

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=160, max_depth=9, min_child_weight=1, gamma=0.0,  subsample=0.8, colsample_bytree=0.8, objective='binary:logistic', nthread=8,  scale_pos_weight=1, seed=27), param_grid=param_test4, scoring='roc_auc', n_jobs=-1,  iid=False, cv=5)  gsearch4.fit(X_train,y_train)
gsearch4.grid_scores_, gsearch4.best_params_, gsearch4.best_score_  
([mean: 0.85143, std: 0.02386, params: {'subsample': 0.6, 'colsample_bytree': 0.6},mean: 0.84930, std: 0.03307, params: {'subsample': 0.7, 'colsample_bytree': 0.6},mean: 0.85171, std: 0.02794, params: {'subsample': 0.8, 'colsample_bytree': 0.6},mean: 0.84891, std: 0.03152, params: {'subsample': 0.9, 'colsample_bytree': 0.6},mean: 0.85143, std: 0.02386, params: {'subsample': 0.6, 'colsample_bytree': 0.7},mean: 0.84930, std: 0.03307, params: {'subsample': 0.7, 'colsample_bytree': 0.7},mean: 0.85171, std: 0.02794, params: {'subsample': 0.8, 'colsample_bytree': 0.7},mean: 0.84891, std: 0.03152, params: {'subsample': 0.9, 'colsample_bytree': 0.7},mean: 0.84747, std: 0.03242, params: {'subsample': 0.6, 'colsample_bytree': 0.8},mean: 0.85011, std: 0.03286, params: {'subsample': 0.7, 'colsample_bytree': 0.8},mean: 0.85286, std: 0.03072, params: {'subsample': 0.8, 'colsample_bytree': 0.8},mean: 0.85603, std: 0.03126, params: {'subsample': 0.9, 'colsample_bytree': 0.8},mean: 0.85209, std: 0.03343, params: {'subsample': 0.6, 'colsample_bytree': 0.9},mean: 0.84802, std: 0.03122, params: {'subsample': 0.7, 'colsample_bytree': 0.9},mean: 0.84961, std: 0.03265, params: {'subsample': 0.8, 'colsample_bytree': 0.9},mean: 0.85207, std: 0.03004, params: {'subsample': 0.9, 'colsample_bytree': 0.9}],{'colsample_bytree': 0.8, 'subsample': 0.9},0.856033966896773)

第五步:正则化参数调优 reg_alpha和reg_lambda(这里只调了reg_alpha)

param_test6 = {  'reg_alpha':[1e-5,1e-4,1e-3, 1e-2, 0.1, 1, 100]
}
gsearch6 = GridSearchCV(estimator = XGBClassifier( learning_rate =0.1, n_estimators=160, max_depth=9, min_child_weight=1, gamma=0.0, subsample=0.9, colsample_bytree=0.8, objective= 'binary:logistic', nthread=8, scale_pos_weight=1,seed=27), param_grid = param_test6, scoring='roc_auc',n_jobs=-1,iid=False, cv=5)
gsearch6.fit(X_train,y_train)
gsearch6.grid_scores_, gsearch6.best_params_, gsearch6.best_score_ 

上述训练过程中,可以针对具体参数进行更细致的调优。用以上调好的参数代入模型,并降低模型学习率learning_rate=0.01增大n_estimators=5000,如果计算能力允许的条件下,可以进一步降低学习率。训练好的模型的准确率和AUC得分相对于之前都有提高。

def tun_parameters2(train_x,train_y):  #通过这个函数,确定树的个数xgb1 = XGBClassifier(learning_rate =0.01, n_estimators=5000, max_depth=9, min_child_weight=1, gamma=0.0, subsample=0.9, colsample_bytree=0.8,reg_alpha= 1e-05, objective= 'binary:logistic', nthread=8,scale_pos_weight=1,seed=27)modelfit(xgb1,train_x,train_y)
tun_parameters2(X_train,y_train)
Model Report
Accuracy : 0.9989
AUC Score (Train): 0.999979

('n_estimators=', 630)

切记:

特征决定上限,调参只是帮助我们逼近这个上限而已

XGBoost调参笔记相关推荐

  1. 棋牌游戏用户流失预测——Xgboost调参

    一.项目介绍 本项目通过对棋牌游戏数据的探索,通过python数据处理以及可视化,最后进行数据建模预测,整个项目分为项目目的的确定.数据的预处理.对数据的分析和项目总结这五个部分. 二.项目流程 项目 ...

  2. xgboost调参指南

    python机器学习-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campa ...

  3. Xgboost调参小结

      XGBoost全称是eXtreme Gradient Boosting,由陈天奇所设计,和传统的梯度提升算法相比,XGBoost进行了许多改进,它能够比其他使用梯度提升的集成算法更加快速.关于xg ...

  4. XGBoost调参技巧(二)Titanic实战Top9%

    学习Kaggle的第一个比赛就是Titanic,断断续续的半年时间,从小白到杀入9%.XGBoost果真是Kaggle杀器,帮我在Titanic中进入9%.zillow进入22%. 简介 Titani ...

  5. 《南溪的目标检测学习笔记》——夏侯南溪的CNN调参笔记,加油

    1 致谢 感谢赵老师的教导! 感谢张老师的指导! 2 调参目标 在COCO数据集上获得mAP>=10.0的模型,现在PaddleDetection上的Anchor-Free模型[TTFNet]的 ...

  6. xgboost调参大法

    了解偏差-方差权衡(Bias-Variance Tradeoff) 在机器学习df或统计课程中,偏差方差权衡可能是最重要的概念之一.当我们允许模型变得更加复杂(例如,更大的深度)时,模型具有更好的适应 ...

  7. python xgboost调参_XGBoost从原理到调参

    承接上文挂枝儿:再从GBDT到XGBoost!​zhuanlan.zhihu.com 理解了原理,那么接下来就要开始学习怎么调参了,之前做模型的时候用xgboost比较简单粗暴跟着教程一顿乱fit,但 ...

  8. python xgboost调参_XGBoost完全调参指南(Python)

    花了三四天学习XGBoost,这篇文章教会了我如何调参.我把文章的主要内容作翻译和摘录,也算是为XGboost中文社区贡献一份资源. 前言 XGBoost中的算法已经成为了许多数据科学家的终极武器了! ...

  9. xgboost 调参经验

    本文介绍三部分内容: - xgboost 基本方法和默认参数 - 实战经验中调参方法 - 基于实例具体分析 1.xgboost 基本方法和默认参数 在训练过程中主要用到两个方法:xgboost.tra ...

最新文章

  1. 手机如何看python代码_python如何绘制iPhone手机图案?(代码示例)
  2. NEW关键字的三种用法
  3. 图片管理之更新SKU表数据
  4. 硬件Pythia:将现实世界桥接到区块链
  5. 60秒计时器的仿真电路_物联网应用基于Arm微控制器的低功耗定时关机计时器
  6. PHP对二维数组中的某个字段的值进行排序
  7. webpack打包jquery多页_Webpack打包与程序调试
  8. 有两个地方,用到了javabean对象和属性字符串值之间的转换
  9. 云原生时代,底层性能如何调优?
  10. C++开发环境搭建_需要学习的内容介绍_写第一个C++程序---C++语言工作笔记008
  11. 基于Visual studio+Opencv+Python的透视变换、图像处理(灰度化、二值化、Canny边缘检测)模型——以2015数学建模A题太阳影子定位为例
  12. 接入网+承载网+核心网
  13. 安卓学习笔记3.1 线性布局
  14. 怎么看电脑是32位还是64位?超级简单的方法!
  15. 双色汉诺塔算法的证明——数学归纳法
  16. 手机2020 QQ 群文件下载存储路径
  17. Datawhale零基础入门数据挖掘-Task5模型融合
  18. 看 阿里人的工作生活是怎样的|2017 阿里人影像纪录短片发布
  19. CCSV5菜单栏中没有Tools按钮,如何显示出来?
  20. 好东西为什么卖不动,店铺选址开店必读!

热门文章

  1. Linux应用编程-音频应用编程-语音转文字项目
  2. 数据链路层 PPP协议工作过程
  3. 【室内定位】常用的机器人定位导航技术及优缺点
  4. 将opera强制的搜狗转为百度搜索
  5. 用for循环输出俄文的“字母表”
  6. 因果推断—现代统计的思想飞跃:过去、现在到未来(伯克利丁鹏博士万字长文)...
  7. Linux下ps aux中进程状态为Ss,S+, Rs,Ds是什么意思?
  8. 《我国中小型连锁超市界定及发展方向探析》论文笔记(一)
  9. Linux修改文件时间或创建新文件:touch
  10. 不同开发语言之Python、Java、Golang对比