0. 环境介绍
Python 版 本:3.6.2
操作系统 :Windows
集成开发环境:PyCharm
1. 安装Python环境
安装Python
首先,我们需要安装Python环境。本人选择的是64位版本的Python 3.6.2。去Python官网 https://www.python.org/ 选择相应的版本并下载。如下如所示:
接下来安装,并最终选择将Python加入环境变量中。
numpy-1.13.1+mkl-cp36-cp36m-win_amd64.whl
scipy-0.19.1-cp36-cp36m-win_amd64.whl
xgboost-0.6-cp36-cp36m-win_amd64.whl
假设上述三个包所在的目录为D:\Application,则运行Windows 命令行运行程序cmd,并将当前目录转到这两个文件所在的目录下。并依次执行如下操作安装这两个包:
>> pip install numpy-1.13.1+mkl-cp36-cp36m-win_amd64.whl
>> pip install scipy-0.19.1-cp36-cp36m-win_amd64.whl
>> pip install xgboost-0.6-cp36-cp36m-win_amd64.whl
安装Scikit-learn
众所周知,scikit-learn是Python机器学习最著名的开源库之一。因此,我们需要安装此库。执行如下命令安装scikit-learn机器学习库:
>> pip install -U scikit-learn
测试安装是否成功
>>> from sklearn import svm
>>> X = [[0, 0], [1, 1]]
>>> y = [0, 1]
>>> clf = svm.SVC()
>>> clf.fit(X, y)
>>> clf.predict([[2., 2.]])
array([1])
>>> import xgboost as xgb
注意:如果如上所述正确输出,则表示安装完成。否则就需要检查安装步骤是否出错,或者系统是否缺少必要的Windows依赖库。常用的一般情况会出现缺少VC++运行库,在Windows 7、8、10等版本中安装Visual C++ 2015基本上就能解决问题。
安装PyCharm
对于PyChram的下载,请点击 PyCharm官网 去下载,当然windows下软件的安装不用解释,傻瓜式的点击 下一步 就行了。
注意:PyCharm软件是基于Java开发的,所以安装该集成开发环境前请先安装JDK,建议安装JDK1.8。
经过上述步骤,基本上软件环境的问题全部解决了,接下来就是实际的XGBoost库实战了……
2. XGBoost详解
2.1 数据格式
XGBoost可以加载多种数据格式的训练数据:1)libsvm格式的文本数据;2)Numpy的二维数组;3)XGBoost的二进制的缓存文件。加载的数据存储在对象 DMatrix 中。
加载libsvm格式的数据
>>> dtrain1 = xgb.DMatrix('train.svm.txt')
加载二进制的缓存文件
>>> dtrain2 = xgb.DMatrix('train.svm.buffer')
加载numpy的数组
>>> 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)
2.2 参数设置
XGBoost使用key-value字典的方式存储参数:
params = {
'booster': 'gbtree',
'objective': 'multi:softmax', # 多分类的问题
'num_class': 10, # 类别数,与 multisoftmax 并用
'gamma': 0.1, # 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
'max_depth': 12, # 构建树的深度,越大越容易过拟合
'lambda': 2, # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.7, # 生成树时进行的列采样
'min_child_weight': 3,
'silent': 1, # 设置成1则没有运行信息输出,最好是设置为0.
'eta': 0.007, # 如同学习率
'seed': 1000,
'nthread': 4, # cpu 线程数
}
2.3 训练模型
有了参数列表和数据就可以训练模型了
num_round = 10
bst = xgb.train( plst, dtrain, num_round, evallist )
2.4 保存模型
在训练完成之后可以将模型保存下来,也可以查看模型内部的结构
bst.save_model('test.model')
导出模型和特征映射(Map)
你可以导出模型到txt文件并浏览模型的含义:
# dump model
bst.dump_model('dump.raw.txt')
# dump model with feature map
bst.dump_model('dump.raw.txt','featmap.txt')
2.5 加载模型
通过如下方式可以加载模型:
bst = xgb.Booster({'nthread':4}) # init model
bst.load_model("model.bin") # load data
3. XGBoost参数详解
在运行XGboost之前,必须设置三种类型成熟:general parameters,booster parameters和task parameters:
General parameters
该参数参数控制在提升(boosting)过程中使用哪种booster,常用的booster有树模型(tree)和线性模型(linear model)。
Booster parameters
这取决于使用哪种booster。
Task parameters
控制学习的场景,例如在回归问题中会使用不同的参数控制排序。
3.1 General Parameters
booster [default=gbtree]
有两中模型可以选择gbtree和gblinear。gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算。缺省值为gbtree
silent [default=0]
取0时表示打印出运行时信息,取1时表示以缄默方式运行,不打印运行时信息。缺省值为0
nthread
XGBoost运行时的线程数。缺省值是当前系统可以获得的最大线程数
num_pbuffer
预测缓冲区大小,通常设置为训练实例的数目。缓冲用于保存最后一步提升的预测结果,无需人为设置。
num_feature
Boosting过程中用到的特征维数,设置为特征个数。XGBoost会自动设置,无需人为设置。
3.2 Parameters for Tree Booster
eta [default=0.3]
为了防止过拟合,更新过程中用到的收缩步长。在每次提升计算之后,算法会直接获得新特征的权重。 eta通过缩减特征的权重使提升计算过程更加保守。缺省值为0.3
取值范围为:[0,1]
gamma [default=0]
minimum loss reduction required to make a further partition on a leaf node of the tree. the larger, the more conservative the algorithm will be.
取值范围为:[0,∞]
max_depth [default=6]
数的最大深度。缺省值为6
取值范围为:[1,∞]
min_child_weight [default=1]
孩子节点中最小的样本权重和。如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束。在现行回归模型中,这个参数是指建立每个模型所需要的最小样本数。该成熟越大算法越conservative
取值范围为:[0,∞]
max_delta_step [default=0]
我们允许每个树的权重被估计的值。如果它的值被设置为0,意味着没有约束;如果它被设置为一个正值,它能够使得更新的步骤更加保守。通常这个参数是没有必要的,但是如果在逻辑回归中类极其不平衡这时候他有可能会起到帮助作用。把它范围设置为1-10之间也许能控制更新。
取值范围为:[0,∞]
subsample [default=1]
用于训练模型的子样本占整个样本集合的比例。如果设置为0.5则意味着XGBoost将随机的从整个样本集合中随机的抽取出50%的子样本建立树模型,这能够防止过拟合。
取值范围为:(0,1]
colsample_bytree [default=1]
在建立树时对特征采样的比例。缺省值为1
取值范围为:(0,1]
3.3 Parameter for Linear Booster
lambda [default=0]
L2 正则的惩罚系数
alpha [default=0]
L1 正则的惩罚系数
lambda_bias
在偏置上的L2正则。缺省值为0(在L1上没有偏置项的正则,因为L1时偏置不重要)
3.3 Task Parameters
objective [ default=reg:linear ]
定义学习任务及相应的学习目标,可选的目标函数如下:
“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
base_score [ default=0.5 ]
所有实例的初始化预测分数,全局偏置;
为了足够的迭代次数,改变这个值将不会有太大的影响。
eval_metric [ default according to 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. It is calculated as #(wrong cases)/#(all cases). For the predictions, the evaluation will regard the instances with prediction value larger than 0.5 as positive instances, and the others as negative instances.
“merror”: Multiclass classification error rate. It is calculated as # ( w r o n c a s e s ) # ( a l l c a s e s ) .
“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. training repeatively
seed [ default=0 ]
随机数的种子。缺省值为0
持续更新中……