将之前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 data
alg.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)
特征决定上限,调参只是帮助我们逼近这个上限而已