原文: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
  • 1

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

import xgboost as xgb
  • 1

=

数据接口

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

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

参数设置

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')]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 还可以定义验证数据集,验证算法的性能
evallist  = [(dtest,'eval'), (dtrain,'train')]
  • 1

=

训练模型

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

num_round = 10
bst = xgb.train( plst, dtrain, num_round, evallist )
  • 1
  • 2
  • 保存模型 
    在训练完成之后可以将模型保存下来,也可以查看模型内部的结构
bst.save_model('0001.model')
  • 1
  • 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')
  • 1
  • 2
  • 3
  • 4
  • 加载模型 
    通过如下方式可以加载模型
bst = xgb.Booster({'nthread':4}) #init model
bst.load_model("model.bin") # load data
  • 1
  • 2

=

提前终止程序

如果有评价数据,可以提前终止程序,这样可以找到最优的迭代次数。如果要提前终止程序必须至少有一个评价数据在参数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 )
  • 1
  • 2
  • 3

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

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

XGBoost:在Python中使用XGBoost的更多相关文章

  1. XGBoost中参数调整的完整指南(包含Python中的代码)

    (搬运)XGBoost中参数调整的完整指南(包含Python中的代码) AARSHAY JAIN, 2016年3月1日     介绍 如果事情不适合预测建模,请使用XGboost.XGBoost算法已 ...

  2. 机器学习——XGBoost大杀器,XGBoost模型原理,XGBoost参数含义

    0.随机森林的思考 随机森林的决策树是分别采样建立的,各个决策树之间是相对独立的.那么,在我们得到了第k-1棵决策树之后,能否通过现有的样本和决策树的信息, 对第m颗树的建立产生有益的影响呢?在随机森 ...

  3. 在Window平台下安装xgboost的Python版本

    原文:http://blog.csdn.net/pengyulong/article/details/50515916 原文修改了两个地方才安装成功,第3步可以不用,第2步重新生成所有的就行了. 第4 ...

  4. 一个完整的机器学习项目在Python中演练(四)

    大家往往会选择一本数据科学相关书籍或者完成一门在线课程来学习和掌握机器学习.但是,实际情况往往d是,学完之后反而并不清楚这些技术怎样才能被用在实际的项目流程中.就像你的脑海中已经有了一块块" ...

  5. 最新xgboost python32位下安装xgboost

    网上很多windows python下安装xgboost都是很简单的几步无非是visual studio2013以上版本编译,安装.但现在最新的xgboost已经移除了c++工程文件,找到旧版本的也多 ...

  6. rf, xgboost和GBDT对比;xgboost和lightGbm

    1. RF 随机森林基于Bagging的策略是Bagging的扩展变体,概括RF包括四个部分:1.随机选择样本(放回抽样):2.随机选择特征(相比普通通bagging多了特征采样):3.构建决策树:4 ...

  7. [转]Python中的str与unicode处理方法

    早上被python的编码搞得抓耳挠腮,在搜资料的时候感觉这篇博文很不错,所以收藏在此. python2.x中处理中文,是一件头疼的事情.网上写这方面的文章,测次不齐,而且都会有点错误,所以在这里打算自 ...

  8. python中的Ellipsis

    ...在python中居然是个常量 print(...) # Ellipsis 看别人怎么装逼 https://www.keakon.net/2014/12/05/Python%E8%A3%85%E9 ...

  9. python中的默认参数

    https://eastlakeside.gitbooks.io/interpy-zh/content/Mutation/ 看下面的代码 def add_to(num, target=[]): tar ...

随机推荐

  1. 拉格朗日乘子法以及KKT条件

    拉格朗日乘子法是一种优化算法,主要用来解决约束优化问题.他的主要思想是通过引入拉格朗日乘子来将含有n个变量和k个约束条件的约束优化问题转化为含有n+k个变量的无约束优化问题. 其中,利用拉格朗日乘子法 ...

  2. springboot配置多数据源mongodb

    参考大佬的文章 https://juejin.im/entry/5ab304dd51882555825241b3

  3. Codeforces.714D.Searching Rectangles(交互 二分)

    题目链接 \(Description\) 在一个\(n*n\)的二维平面中有两个不相交的整点矩形,每次可以询问两个矩形有几个完全在你给出的一个矩形中.200次询问内确定两个矩形坐标. \(Soluti ...

  4. Codeforces Round #461 (Div. 2)

    A - Cloning Toys /* 题目大意:给出两种机器,一种能将一种原件copy出额外一种原件和一个附件, 另一种可以把一种附件copy出额外两种附件,给你一个原件, 问能否恰好变出题目要求数 ...

  5. 本地文件包含漏洞(LFI漏洞)

    0x00 前言 本文的主要目的是分享在服务器遭受文件包含漏洞时,使用各种技术对Web服务器进行攻击的想法. 我们都知道LFI漏洞允许用户通过在URL中包括一个文件.在本文中,我使用了bWAPP和DVW ...

  6. BZOJ 1012: [JSOI2008]最大数maxnumber 单调队列/线段树/树状数组/乱搞

    1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec  Memory Limit: 162 MBSubmit: 4750  Solved: 2145[Submi ...

  7. MVC之Global.asax解析

    大家看到上面的代码了,Application_Start大家都知道这是应用程序启动入口. AreaRegistration.RegisterAllAreas是什么呢? 我们先看看微软官方的注解: 我们 ...

  8. document.all理解

    The all collection includes one element object for each valid HTML tag. If a valid tag has a matchin ...

  9. MVC扩展Filter,通过继承ActionFilterAttribute为登录密码加密

    与ActionFilter相关的接口有2个: □ IActionFilter 对action执行前后处理 void OnActionExecuting(ActionExecutingContext f ...

  10. MVC无限级分类02,增删改查

    继上一篇"MVC无限级分类01,分层架构,引入缓存,完成领域模型与视图模型的映射",本篇开始MVC无限级分类的增删改查部分,源码在github. 显示和查询 使用datagrid显 ...