from http://blog.csdn.net/zc02051126/article/details/46771793

在Python中使用XGBoost

下面将介绍XGBoost的Python模块,内容如下: 
编译及导入Python模块 
数据接口 
参数设置 
训练模型l 
提前终止程序 
预测

walk through python example for UCI Mushroom dataset is provided.

安装

首先安装XGBoost的C++版本,然后进入源文件的根目录下的 wrappers文件夹执行如下脚本安装Python模块

python setup.py install

安装完成后按照如下方式导入XGBoost的Python模块

import xgboost as xgb

数据接口

XGBoost可以加载libsvm格式的文本数据,加载的数据格式可以为Numpy的二维数组和XGBoost的二进制的缓存文件。加载的数据存储在对象DMatrix中。

  • 加载libsvm格式的数据和二进制的缓存文件时可以使用如下方式
dtrain = xgb.DMatrix('train.svm.txt')
dtest = xgb.DMatrix('test.svm.buffer')
  • 加载numpy的数组到DMatrix对象时,可以用如下方式
data = np.random.rand(5,10) # 5 entities, each contains 10 features
label = np.random.randint(2, size=5) # binary target
dtrain = xgb.DMatrix( data, label=label)
  • scipy.sparse格式的数据转化为 DMatrix格式时,可以使用如下方式
csr = scipy.sparse.csr_matrix( (dat, (row,col)) )
dtrain = xgb.DMatrix( csr )
  • 将 DMatrix 格式的数据保存成XGBoost的二进制格式,在下次加载时可以提高加载速度,使用方式如下
dtrain = xgb.DMatrix('train.svm.txt')
dtrain.save_binary("train.buffer")
  • 可以用如下方式处理 DMatrix中的缺失值:
dtrain = xgb.DMatrix( data, label=label, missing = -999.0)
  • 当需要给样本设置权重时,可以用如下方式
w = np.random.rand(5,1)
dtrain = xgb.DMatrix( data, label=label, missing = -999.0, weight=w)

参数设置

XGBoost使用key-value格式保存参数. Eg 
* Booster(基本学习器)参数

param = {'bst:max_depth':2, 'bst:eta':1, 'silent':1, 'objective':'binary:logistic' }
param['nthread'] = 4
plst = param.items()
plst += [('eval_metric', 'auc')] # Multiple evals can be handled in this way
plst += [('eval_metric', 'ams@0')]
  • 还可以定义验证数据集,验证算法的性能
evallist  = [(dtest,'eval'), (dtrain,'train')]

训练模型

有了参数列表和数据就可以训练模型了 
* 训练

num_round = 10
bst = xgb.train( plst, dtrain, num_round, evallist )
  • 保存模型
    在训练完成之后可以将模型保存下来,也可以查看模型内部的结构
bst.save_model('0001.model')
  • Dump Model and Feature Map 
    You can dump the model to txt and review the meaning of model
# dump model
bst.dump_model('dump.raw.txt')
# dump model with feature map
bst.dump_model('dump.raw.txt','featmap.txt')
  • 加载模型 
    通过如下方式可以加载模型
bst = xgb.Booster({'nthread':4}) #init model
bst.load_model("model.bin") # load data

提前终止程序

如果有评价数据,可以提前终止程序,这样可以找到最优的迭代次数。如果要提前终止程序必须至少有一个评价数据在参数evals中。 If there’s more than one, it will use the last.

train(..., evals=evals, early_stopping_rounds=10)

The model will train until the validation score stops improving. Validation error needs to decrease at least every early_stopping_rounds to continue training.

If early stopping occurs, the model will have two additional fields: bst.best_score and bst.best_iteration. Note that train() will return a model from the last iteration, not the best one.

This works with both metrics to minimize (RMSE, log loss, etc.) and to maximize (MAP, NDCG, AUC).

=

Prediction

After you training/loading a model and preparing the data, you can start to do prediction.

data = np.random.rand(7,10) # 7 entities, each contains 10 features
dtest = xgb.DMatrix( data, missing = -999.0 )
ypred = bst.predict( xgmat )

If early stopping is enabled during training, you can predict with the best iteration.

ypred = bst.predict(xgmat,ntree_limit=bst.best_iteration)

xgboost使用细节的更多相关文章

  1. Ubuntu: ImportError: No module named xgboost

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

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

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

  3. XGBoost、LightGBM的详细对比介绍

    sklearn集成方法 集成方法的目的是结合一些基于某些算法训练得到的基学习器来改进其泛化能力和鲁棒性(相对单个的基学习器而言)主流的两种做法分别是: bagging 基本思想 独立的训练一些基学习器 ...

  4. R语言︱XGBoost极端梯度上升以及forecastxgb(预测)+xgboost(回归)双案例解读

    XGBoost不仅仅可以用来做分类还可以做时间序列方面的预测,而且已经有人做的很好,可以见最后的案例. 应用一:XGBoost用来做预测 ------------------------------- ...

  5. 1.XGBOOST算法推导

    最近因为实习的缘故,所以开始复习各种算法推导~~~就先拿这个xgboost练练手吧. (参考原作者ppt 链接:https://pan.baidu.com/s/1MN2eR-4BMY-jA5SIm6W ...

  6. 机器学习 GBDT+xgboost 决策树提升

    目录 xgboost CART(Classify and Regression Tree) GBDT(Gradient Boosting Desicion Tree) GB思想(Gradient Bo ...

  7. xgboost 参数调优指南

    一.XGBoost的优势 XGBoost算法可以给预测模型带来能力的提升.当我对它的表现有更多了解的时候,当我对它的高准确率背后的原理有更多了解的时候,我发现它具有很多优势: 1 正则化 标准GBDT ...

  8. Xgboost总结

    从决策树.随机森林.GBDT最终到XGBoost,每个热门算法都不是孤立存在的,而是基于一系列算法的改进与优化.决策树算法简单易懂可解释性强,但是过拟合风险很大,应用场景有限:随机森林采用Baggin ...

  9. xgboost原理

    出处http://blog.csdn.net/a819825294 1.序 距离上一次编辑将近10个月,幸得爱可可老师(微博)推荐,访问量陡增.最近毕业论文与xgboost相关,于是重新写一下这篇文章 ...

随机推荐

  1. java:CSS(定位,组合选择符,边距,Float,Table的样式,显示和隐藏,换行,盒子模型,iframe和frameset框架)

    1.绝对定位,相对定位,fixed定位(指浏览器窗口定位): <!DOCTYPE html> <html> <head> <meta charset=&quo ...

  2. window10安装Elasticsearch及可视化工具es header

    1.下载es(选择windows版本) https://www.elastic.co/cn/downloads/elasticsearch 2.解压安装包,到bin目录下,运行elasticsearc ...

  3. 【机器学习】HK算法(LMSE算法) LMS算法改进保证线性可分时均方误差标准能够找到线性可分的超平面

    1.其实HK算法思想很朴实,就是在最小均方误差准则下求得权矢量. 他相对于感知器算法的优点在于,他适用于线性可分和非线性可分得情况,对于线性可分的情况,给出最优权矢量,对于非线性可分得情况,能够判别出 ...

  4. selenium-模拟鼠标

    需要导入的包: from selenium.webdriver import ActionChains 一.模拟鼠标右键 ActionChains(self.driver).context_click ...

  5. SpringBoot如何使用PUT、DELETE请求方式

    SpringBoot 2.2.X默认不支持put,delete等请求方式的. 首先需要在配置文件中打开他们,代码如下: spring.mvc.hiddenmethod.filter.enabled=t ...

  6. [转帖]关于Ubuntu与Debian的关系,了解!

    关于Ubuntu与Debian的关系,了解! https://blog.csdn.net/guyue35/article/details/47286193 了解一下区别..   饮水思源:Ubuntu ...

  7. [转帖].NET Core 项目指定SDK版本

    .NET Core 项目指定SDK版本 https://www.cnblogs.com/stulzq/p/9503121.html 一. 版本里的坑 自从 .NET Core 2.1.0版本发布以后, ...

  8. Python的入门(day1)

    一:Python的起源 Python的创始人为Guido van Rossum.1989年圣诞节期间,在阿姆斯特丹,Guido为了打发圣诞节的无趣,决心开发一个新的脚本解释程序,做为ABC 语言的一种 ...

  9. mysql 官网下载太慢了,来这里!!!

    RT.去官网下载mysql简直是折磨,太慢了!!! 但我还是坚持住了,下载下来了,我自己下载的是 MAC 5.7.27版本,网盘分享下,有需要的自提吧: 链接:https://pan.baidu.co ...

  10. P4962 朋也与光玉题解

    题目链接 光坂小镇是一个由 n 个点(编号为 1 ~ n),m 条有向边构成的图,每个节点上都有一个光玉,光玉共有 k 种,编号为 0 ~ k−1. 为了使一切改变,朋也需要找齐全部的 k种光玉.他可 ...