1.首先导入包

import xgboost as xgb

2.使用以下的函数实现交叉验证训练xgboost。

bst_cvl = xgb.cv(xgb_params, dtrain, num_boost_round=50,
           nfold=3, seed=0, feval=xg_eval_mae, maximize=False, early_stopping_rounds=10)

3.cv参数说明:函数cv的第一个参数是对xgboost训练器的参数的设置,具体见以下

xgb_params = {
'seed': 0,
'eta': 0.1,
'colsample_bytree': 0.5,
'silent': 1,
'subsample': 0.5,
'objective': 'reg:linear',
'max_depth': 5,
'min_child_weight': 3
}

参数说明如下:

Xgboost参数

  • 'booster':'gbtree',
  • 'objective': 'multi:softmax', 多分类的问题
  • 'num_class':10, 类别数,与 multisoftmax 并用
  • 'gamma':损失下降多少才进行分裂,gammar越大越不容易过拟合。
  • 'max_depth':树的最大深度。增加这个值会使模型更加复杂,也容易出现过拟合,深度3-10是合理的。
  • 'lambda':2, 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
  • 'subsample':0.7, 随机采样训练样本
  • 'colsample_bytree':0.7, 生成树时进行的列采样
  • 'min_child_weight':正则化参数. 如果树分区中的实例权重小于定义的总和,则停止树构建过程。
  • 'silent':0 ,设置成1则没有运行信息输出,最好是设置为0.
  • 'eta': 0.007, 如同学习率
  • 'seed':1000,
  • 'nthread':7, cpu 线程数

4.cv参数说明:dtrain是使用下面的函数DMatrix得到的训练集

dtrain = xgb.DMatrix(train_x, train_y)

5.cv参数说明:feval参数是自定义的误差函数

def xg_eval_mae(yhat, dtrain):
y = dtrain.get_label()
return 'mae', mean_absolute_error(np.exp(y), np.exp(yhat))

6.cv参数说明:nfold是交叉验证的折数, early_stopping_round是多少次模型没有提升后就结束, num_boost_round是加入的决策树的数目。

7. bst_cv是cv返回的结果,是一个DataFram的类型,其列为以下列组成

8.自定义评价函数:具体见这个博客:https://blog.csdn.net/wl_ss/article/details/78685984

 def customedscore(preds, dtrain):
label = dtrain.get_label()
pred = [int(i>=0.5) for i in preds]
confusion_matrixs = confusion_matrix(label, pred)
recall =float(confusion_matrixs[0][0]) / float(confusion_matrixs[0][1]+confusion_matrixs[0][0])
precision = float(confusion_matrixs[0][0]) / float(confusion_matrixs[1][0]+confusion_matrixs[0][0])
F = 5*precision* recall/(2*precision+3*recall)*100
return 'FSCORE',float(F)

这种自定义的评价函数可以用于XGboost的cv函数或者train函数中的feval参数

还有一种定义评价函数的方式,如下

  

def mae_score(y_ture, y_pred):
return mean_absolute_error(y_true=np.exp(y_ture), y_pred=np.exp(y_pred))

这种定义的函数可以用于gridSearchCV函数的scorning参数中。

xgboost调参步骤

第一步:确定n_estimators参数

首先初始化参数的值

xgb1 = XGBClassifier(max_depth=3,
learning_rate=0.1,
n_estimators=5000,
silent=False,
objective='binary:logistic',
booster='gbtree',
n_jobs=4,
gamma=0,
min_child_weight=1,
subsample=0.8,
colsample_bytree=0.8,
seed=7)

用cv函数求得参数n_estimators的最优值。

cv_result = xgb.cv(xgb1.get_xgb_params(),
dtrain,
num_boost_round=xgb1.get_xgb_params()['n_estimators'],
nfold=5,
metrics='auc',
early_stopping_rounds=50,
callbacks=[xgb.callback.early_stop(50),
xgb.callback.print_evaluation(period=1,show_stdv=True)])

第二步、确定max_depth和min_weight参数

param_grid = {'max_depth':[1,2,3,4,5],
'min_child_weight':[1,2,3,4,5]}
grid_search = GridSearchCV(xgb1,param_grid,scoring='roc_auc',iid=False,cv=5) grid_search.fit(train[feature_name],train['label']) print('best_params:',grid_search.best_params_)
print('best_score:',grid_search.best_score_)

第三步、gamma参数调优

首先将上面调好的参数设置好,如下所示

xgb1 = XGBClassifier(max_depth=2,
learning_rate=0.1,
n_estimators=33,
silent=False,
objective='binary:logistic',
booster='gbtree',
n_jobs=4,
gamma=0,
min_child_weight=9,
subsample=0.8,
colsample_bytree=0.8,
seed=7)

然后继续网格调参

param_grid = {'gamma':[1,2,3,4,5,6,7,8,9]}
grid_search = GridSearchCV(xgb1,param_grid,scoring='roc_auc',iid=False,cv=5) grid_search.fit(train[feature_name],train['label'])
print('best_params:',grid_search.best_params_)
print('best_score:',grid_search.best_score_)

第四步、调整subsample与colsample_bytree参数

param_grid = {'subsample':[i/10.0 for i in range(5,11)],
'colsample_bytree':[i/10.0 for i in range(5,11)]}
grid_search = GridSearchCV(xgb1,param_grid,scoring='roc_auc',iid=False,cv=5) grid_search.fit(train[feature_name],train['label'])
print('best_params:',grid_search.best_params_)
print('best_score:',grid_search.best_score_)

第五步、调整正则化参数

param_grid = {'reg_lambda':[i/10.0 for i in range(1,11)]}
grid_search = GridSearchCV(xgb1,param_grid,scoring='roc_auc',iid=False,cv=5) grid_search.fit(train[feature_name],train['label'])
print('best_params:',grid_search.best_params_)
print('best_score:',grid_search.best_score_)

最后我们使用较低的学习率以及使用更多的决策树,可以用CV来实现这一步骤

xgb1 = XGBClassifier(max_depth=2,
learning_rate=0.01,
n_estimators=5000,
silent=False,
objective='binary:logistic',
booster='gbtree',
n_jobs=4,
gamma=2.1,
min_child_weight=9,
subsample=0.8,
colsample_bytree=0.8,
seed=7,
)
  1. 仅仅靠参数的调整和模型的小幅优化,想要让模型的表现有个大幅度提升是不可能的。
  2. 要想让模型的表现有一个质的飞跃,需要依靠其他的手段,诸如,特征工程(feature egineering) ,模型组合(ensemble of model),以及堆叠(stacking)等

具体的关于调参的知识请看以下链接:

https://www.cnblogs.com/TimVerion/p/11436001.html

http://www.pianshen.com/article/3311175716/

xgboost的使用的更多相关文章

  1. 搭建 windows(7)下Xgboost(0.4)环境 (python,java)以及使用介绍及参数调优

    摘要: 1.所需工具 2.详细过程 3.验证 4.使用指南 5.参数调优 内容: 1.所需工具 我用到了git(内含git bash),Visual Studio 2012(10及以上就可以),xgb ...

  2. 在Windows10 64位 Anaconda4 Python3.5下安装XGBoost

    系统环境: Windows10 64bit Anaconda4 Python3.5.1 软件安装: Git for Windows MINGW 在安装的时候要改一个选择(Architecture选择x ...

  3. 【原创】xgboost 特征评分的计算原理

    xgboost是基于GBDT原理进行改进的算法,效率高,并且可以进行并行化运算: 而且可以在训练的过程中给出各个特征的评分,从而表明每个特征对模型训练的重要性, 调用的源码就不准备详述,本文主要侧重的 ...

  4. Ubuntu: ImportError: No module named xgboost

    ImportError: No module named xgboost 解决办法: git clone --recursive https://github.com/dmlc/xgboost cd ...

  5. windows下安装xgboost

    Note that as of the most recent release the Microsoft Visual Studio instructions no longer seem to a ...

  6. xgboost原理及应用

    1.背景 关于xgboost的原理网络上的资源很少,大多数还停留在应用层面,本文通过学习陈天奇博士的PPT 地址和xgboost导读和实战 地址,希望对xgboost原理进行深入理解. 2.xgboo ...

  7. xgboost

    xgboost后面加了一个树的复杂度 对loss函数进行2阶泰勒展开,求得最小值, 参考链接:https://homes.cs.washington.edu/~tqchen/pdf/BoostedTr ...

  8. 【转】XGBoost参数调优完全指南(附Python代码)

    xgboost入门非常经典的材料,虽然读起来比较吃力,但是会有很大的帮助: 英文原文链接:https://www.analyticsvidhya.com/blog/2016/03/complete-g ...

  9. 【原创】Mac os 10.10.3 安装xgboost

    大家用的比较多的是Linux和windows,基于Mac os的安装教程不多, 所以在安装的过程中遇到很多问题,经过较长时间的尝试,可以正常安装和使用, [说在前面]由于新版本的Os操作系统不支持op ...

  10. 机器学习(四)--- 从gbdt到xgboost

    gbdt(又称Gradient Boosted Decision Tree/Grdient Boosted Regression Tree),是一种迭代的决策树算法,该算法由多个决策树组成.它最早见于 ...

随机推荐

  1. ESP8266烧录选项中的QIO 和 DIO解释

    https://blog.csdn.net/recclay/article/details/78956580 看到的由烧录引起的QIO和DIO问题探索.. 所以一般选择DIO QIO -> Qu ...

  2. __slots__节约空间

    1.为什么要使用__slots__ Python 使用 dicts(hash table)缓存大量的静态资源(属性). 我们最近在Image类中,用仅仅一行__slots__代码,改变成使用tuple ...

  3. pytorch 图片处理.md

    本篇所有代码位置链接

  4. 彻底卸载干净docker并且安装docker 指定版本

    yum remove docker \ docker-client \ docker-client-latest \ docker-common \ docker-latest \ docker-la ...

  5. 20190716NOIP模拟赛T1 礼物(概率dp+状压)

    题目描述 夏川的生日就要到了.作为夏川形式上的男朋友,季堂打算给夏川买一些生 日礼物. 商店里一共有种礼物.夏川每得到一种礼物,就会获得相应喜悦值Wi(每种 礼物的喜悦值不能重复获得). 每次,店员会 ...

  6. Xpath中text(),string(),data()的区别

    摘要: 在XPath中,经常使用text()和string(),而我一般都是想到哪个用哪个,究竟他们之间有什么不同,没有在意过. 本质区别 text()是一个node test,而string()是一 ...

  7. Oracle-sql*plus

    连接命令 (1)conn[ect] 用法: conn 用户名/密码@网络服务名 [as sysdba/sysoper] 当用特权用户身份连接时,必须带上 as sysdba 或是 as sysoper ...

  8. ssh不输入密码

    要通过跳转机器远程其他的机器 不方便使用秘钥 每次都要输入密码也很烦 使用sshpass可以复制一行命令就直接登录了 我的跳板机是Centos7安装sshpass很简单 直接如下搞定 yum inst ...

  9. 一、初识Spring Boot框架

    一.搭建Spring Boot环境 1.选择Project,选择Spring Initializr 2.选择Sdk与默认url 3.点击 Next 4.修改一下Group信息和Artifacet,Ne ...

  10. JS字符串转换为JSON的方法

    1.jQuery插件支持的转换方式:  示例: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象 2.浏览 ...