kaggle比赛必备算法XGBoost入门及实战

时间:2019-02-19
本文章向大家介绍kaggle比赛必备算法XGBoost入门及实战,主要包括kaggle比赛必备算法XGBoost入门及实战使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

xgboost一直在kaggle竞赛江湖里被传为神器,它在对结构化或表格数据的应用占据主导地位,是目前开源的最快最好的工具包,与其常见的工具包算法速度提高了10倍以上!

XGBoost is an implementation of gradient boosted decision trees (GBDT) designed for speed and performance.

xgboost 是对梯度增强决策树(GBDT)的一种实现,具有更高的性能以及速度,本文将尽量用通俗易懂的方式进行介绍并给出实战案例。

1.什么是XGBoost?

xgboost 是 eXtreme Gradient Boosting的简写。

The name xgboost, though, actually refers to the engineering goal to push the limit of computations resources for boosted tree algorithms. Which is the reason why many people use xgboost.

以上是xgboost作者陈天奇在Quora(类似国内的知乎)上对名字的解释。

xgboost是一个软件包,可以通过各种API接口访问使用:

  • Command Line Interface (CLI).命令行
  • C++
  • Java
  • R
  • python 和 scikit-learn
  • Julia
  • Scala

xgboost 的底层实现在我看来还是比较复杂的,想深入理解可以查看陈博士的Paper (XGBoost: A Scalable Tree Boosting System) ,它针对传统GBDT算法做了很多细节改进,包括损失函数、正则化、稀疏感知算法、并行化算法设计等等。

2.XGBoost的特性

说到Xgboost,不得不先从GBDT(Gradient Boosting Decision Tree)说起。因为xgboost本质上还是一个GBDT,但是力争把速度和效率发挥到极致,所以叫X (Extreme) GBoosted,两者都是boosting方法。

那什么是GBDT??我们看一张图:

GBDT的原理很简单,我们反复循环构建新的模型并将它们组合成一个集成模型的,从初始Naive模型开始,我们从计算数据集中每个观测的误差,然后下一个树去拟合误差函数对预测值的残差(残差就是预测值与真实值之间的误差),如图所示:Y = Y1 + Y2 + Y3。

Parallelization并行处理

XGBoost工具支持并行处理。Boosting不是一种串行的结构吗?怎么并行的?注意XGBoost的并行不是 tree 粒度的并行,XGBoost 也是一次迭代完才能进行下一次迭代的。

XGBoost的并行是在特征粒度上的,决策树的学习最耗时的一个步骤就是对特征的值进行排序,XGBoost在训练之前,预先对数据进行了排序,然后保存为block结构,后面的迭代中重复地使用这个结构,大大减小计算量。这个block结构也使得并行成为了可能,在进行节点的分裂时,需要计算每个特征的增益,最终选增益最大的那个特征去做分裂,那么各个特征的增益计算就可以开多线程进行。

正则化

XGBoost 在代价函数里加入了正则项,用于控制模型的复杂度。正则项里包含了树的叶子节点个数、每个叶子节点上输出的 score 的L2模的平方和。从Bias-variance tradeoff 角度来讲,正则项降低了模型的 variance,使学习出来的模型更加简单,防止过拟合,这也是xgboost优于传统GBDT的一个特性。

缺失值处理

对于特征的值有缺失的样本,xgboost可以自动学习出它的分裂方向。

损失函数

传统GBDT在优化时只用到一阶导数信息,xgboost则对代价函数进行了二阶泰勒展开,同时用到了一阶和二阶导数。

分布式计算

XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way.

3.实战示例

官方指导文档:
https://xgboost.readthedocs.io/en/latest/index.html

github 示例文档:
https://github.com/dmlc/xgboost/tree/master/demo/guide-python

本文将继续使用kaggle竞赛平台上的房价预测的数据,具体数据请移步kaggle实战之房价预测,了解一下?

准备数据

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Imputer

data = pd.read_csv('../input/train.csv')
data.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = data.SalePrice
X = data.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object'])
train_X, test_X, train_y, test_y = train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25)

my_imputer = Imputer()
train_X = my_imputer.fit_transform(train_X)
test_X = my_imputer.transform(test_X)

构建模型

from xgboost import XGBRegressor

my_model = XGBRegressor()
# Add silent=True to avoid printing out updates with each cycle
my_model.fit(train_X, train_y, verbose=False)

评估及预测

# make predictions
predictions = my_model.predict(test_X)

from sklearn.metrics import mean_absolute_error
print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y)))

模型调参

xgboost模型参数有几十种,以上我们只是使用的默认的参数进行训练预测,参数详解请参照:
Parameters (official guide)

XGBoost有几个参数会显著影响模型的准确性和训练速度,你应该需要特别关注,并适当的进行调参:

#1. n_estimators

n_estimators指定通过建模周期的次数,可以理解成迭代次数,值太大会导致过度拟合,这是对训练数据的准确预测,但对新数据的预测偏差很大。一般的范围在100-1000之间。

#2.early_stopping_rounds

这个参数 early_stopping_rounds 提供了一种自动查找理想值的方法,试验证分数停止改进时停止迭代。

我们可以为 n_estimators 设置一个较高值,然后使用 early_stopping_rounds来找到停止迭代的最佳时间。

my_model = XGBRegressor(n_estimators=1000)
my_model.fit(train_X, train_y, early_stopping_rounds=5, 
             eval_set=[(test_X, test_y)], verbose=False)
             
# XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1,
#        colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0,
#        max_depth=3, min_child_weight=1, missing=None, n_estimators=1000,
#        n_jobs=1, nthread=None, objective='reg:linear', random_state=0,
#        reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,
#        silent=True, subsample=1)

当使用 early_stopping_rounds 参数时,您需要留出一些数据来检查要使用的轮数,从以上实例代码可以看出 n_estimators=1000 为停止迭代次数。

#3.learning_rate

以下是一个微妙但重要的技巧,可用于更好的xgboost模型:

一般来说,一个小的 learning_rate(和大的 n_estimators )将产生更精确的xgboost 模型,由于该模型在整个循环中进行了更多的迭代,因此它也需要更长的时间来训练。

my_model = XGBRegressor(n_estimators=1000, learning_rate=0.05)
my_model.fit(train_X, train_y, early_stopping_rounds=5, 
             eval_set=[(test_X, test_y)], verbose=False)

#4.n_jobs

在运行时的较大数据集上,可以使用并行性更快地构建模型,通常将参数n_jobs设置为机器上的CPU的数量。对于较小的数据集,这个参数没有任何作用。

4.参考资料

1.xgboost作者讲义PPT:https://homes.cs.washington.edu/~tqchen/pdf/BoostedTree.pdf
2.xgboost入门与实战(原理篇):https://blog.csdn.net/sb19931201/article/details/52557382
3.史上最详细的XGBoost实战:https://zhuanlan.zhihu.com/p/31182879
4.一文读懂机器学习大杀器XGBOOST原理