导航

xgboost的sklearn接口和原生接口参数详细说明及调参指点

Posted on 2018-10-22 17:21  wzd321  阅读(6411)  评论(1编辑  收藏  举报
from xgboost import XGBClassifier
XGBClassifier(max_depth=3,learning_rate=0.1,n_estimators=100,silent=True,objective='binary:logistic',
        booster='gbtree',n_jobs=1,nthread=None,gamma=0,min_child_weight=1, max_delta_step=0, subsample=1,
         colsample_bytree=1, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, random_state=0, 
         seed=None, missing=None, **kwargs)

1.模型参数

max_depth:int |每个基本学习器树的最大深度,可以用来控制过拟合。典型值是3-10

learning_rate=0.1:

  即是eta,为了防止过拟合,更新过程中用到的收缩步长,使得模型更加健壮。每次提升计算之后,算法会直接获得新特征的权重,eta通过缩减特征的权重使提升计算过程更加保守,缺省值为0.3 取值范围为:[0,1]。典型值一般设置为:0.01-0.2。

n_estimators=100,估计器的数量

silent:boolean|是否打印信息

objective:定义学习任务及相应的学习目标,可选目标函数如下:

  “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

booster: default="gbtree",

  可选gbtree和gblinear,gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算

n_jobs:线程数目

nthread:废弃

gamma:0,损失阈值,在树的一个叶节点上进行进一步分裂所需的最小损失减少量,越大,算法越保守。取值范围为:[0,∞]。在节点分裂时,只有分裂后损失函数的值下降了,才会分裂这个节点。Gamma指定了节点分裂所需的最小损失函数下降值。这个参数的值越大,算法越保守。这个参数的值和损失函数息息相关,所以是需要调整的。

 

min_child_weight=1,

  拆分节点权重和阈值,如果节点的样本权重和小于该阈值,就不再进行拆分。在现行回归模型中,这个是指建立每个模型所需要的最小样本数。越大,算法越保守,可以用来减少过拟合。 取值范围为:[0,∞]

max_delta_step=0,

  每棵树的最大权重估计。如果它的值被设置为0,意味着没有约束;如果它被设置为一个正值,它能够使得更新的步骤更加保守。通常这个参数是没有必要的,但是如果在逻辑回归中类别极其不平衡这时候他有可能会起到帮助作用。把它范围设置为1-10之间也许能控制更新。 取值范围为:[0,∞]

subsample=1,   

  随机选取一定比例的样本来训练树。设置为0.5,则意味着XGBoost将从整个样本集合中随机的抽取出50%子样本建立树模型,这能够防止过拟合。 取值范围为:(0,1]。典型值0.5-1     

colsample_bytree=1,

  选取构造树的特征比例。缺省值为1 取值范围为:(0,1] 。典型值0.5-1

colsample_bylevel=1,

   Subsample ratio of columns for each split, in each level. 每个层分裂的节点数,这个一般很少用。用来控制树的每一级的每一次分裂,对列数的采样的占比。

 

reg_alpha=0,

  L1 regularization term on weights,这个主要是用在数据维度很高的情况下,可以提高运行速度。

reg_lambda=1,

  L2 regularization term on weights,这个其实用的很少

scale_pos_weight=1,

  用来控制正负样本的比例,平衡正负样本权重,处理样本不平衡。在类别高度不平衡的情况下,将参数设置大于0,可以加快收敛。

 

base_score=0.5,

   The initial prediction score of all instances, global bias.

random_state=0,     

seed=None,废弃

missing=None,

  在数据中,标注为缺失值的表示。如果为None,则默认为np.nan

**kwargs:

 

  tree_method: string,[default=’auto’],xgboost构建树的算法,‘auto’,‘exact’,‘approx’,‘hist’  

  lambda_bias: 在偏置上的L2正则  

  sketch_eps: [default=0.03],只在approximate greedy algorithm上使用  

  updater: [default=’grow_colmaker,prune’],提供模块化的方式来构建树,一般不需要由用户设置

  refresh_leaf: [default=1],刷新参数,如果为1,刷新叶子和树节点,否则只刷新树节点

  process_type: [default=’default’],提升的方式  

  grow_policy: string [default=’depthwise’],控制新增节点的方式,‘depthwise’,分裂离根节点最近的节点,‘lossguide’,分裂损失函数变化最大的节点

  max_leaves: [default=0],增加的最大节点数,只和lossguide’ grow policy相关

  max_bins: [default=256],只和tree_method的‘hist’相关

调参关键参数:

 xgboost的调参建议采用单参数调整的方法

 

过拟合控制参数:

直接控制模型的复杂度 

max_depth, min_child_weight, gamma

增大产生树的随机性 

subsample, colsample_bytree

eta, num_round

 

 

 

 

 

处理不平衡的数据集 :

预测的排序(AUC) 

scale_pos_weight

预测可靠性 

max_delta_step

 

 

 

 

判断过拟合的一般方法:

clf = xgb.XGBClassifier()
clf.fit(X_train,y_train,eval_set
=[(X_train, y_train),(X_test, y_test)],eval_metric='logloss', verbose=True)

#
'validation_0':(X_train, y_train),'validation_1':(X_test, y_test)

evals_result = clf.evals_result()
#{'validation_0': {'logloss': ['0.604835', '0.531479']},
# 'validation_1': {'logloss': ['0.41965', '0.17686']}}

 xgboost如何判断特征重要性:

weight  - 该特征在所有树中被用作分割样本的特征的次数;

gain      - 在所有树中的平均增益;

cover    - the average coverage of the feature when it is used in trees。

 https://blog.csdn.net/lz_peter/article/details/85010931

2.方法列表

fit(X,y,sample_weight=None,eval_set=None,eval_metric=None,early_stopping_rounds=None,verbose=True, xgb_model=None, sample_weight_eval_set=None, callbacks=None)

sample_weight:每个样本的权重,设置方法:sample_weight=np.where(y==1,len(y)-sum(y),sum(y))

eval_set=None,A list of (X, y) 

  用作提早停止的验证集

eval_metric=None,  

  [默认和objective相关],校验数据所需要的评价指标,不同的目标函数将会有缺省的评价指标(rmse for regression, and error for classification, mean average precision for ranking),用户可以添加多种评价指标,对于Python用户要以list传递参数对给程序,而不是map参数list参数不会覆盖 ,’eval_metric’的可选参数如下:
  “rmse”: root mean square error,均方根误差
  “logloss”: negative log-likelihood,对数似然
  “error”: Binary classification error rate,二值误差率,计算方法为误分样本/总样本
  “merror”: Multiclass classification error rate,多分类误差率,计算方法同上
  “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.  

early_stopping_rounds=None,intoptional  

verbose=True,可视化

xgb_model=None,str

  file name of stored xgb model or ‘Booster’ instance Xgb model to be loaded before training (allows training continuation).

 

sample_weight_eval_set=None,

callbacks=None,

predict(data, output_margin=False, ntree_limit=None, validate_features=True)

 ntree_limit :int

  Limit number of trees in the prediction; defaults to best_ntree_limit if defined (i.e. it has been trained with early stopping), otherwise 0 (use all trees). 

 

predict_proba(data, ntree_limit=None, validate_features=True)

 

apply(X, ntree_limit=0)

Return the predicted leaf every tree for each sample.

array_like, shape=[n_samples, n_trees]

evals_result()

Return the evaluation results.

  If eval_set is passed to the fit function, you can call evals_result() to get evaluation results for all passed eval_sets. When eval_metric is also passed to the fit function, the evals_result will contain the eval_metrics passed to the fit function.

Return type:dictionary

 案例:

xgboost原理性

https://blog.csdn.net/a1b2c3d4123456/article/details/52849091

非常好的原理解释https://blog.csdn.net/sb19931201/article/details/52557382