Xgboost算法

Xgboost简介

Xgboost 是Boosting算法中的一种.
Boosting算法的思想是将许多弱分类器集成在一起,形成一个强分类器.
Xgboost是一种提升树模型,他可以将许多树模型集成在一起,形成一个很强的分类器.
Xgboost所用到的树模型是CART回归树模型
Xgboost一般和sklearn一起使用,但是sklearn中没有集成Xgboost,因此需要单独下载

检查是否安装了Xgboost

	pip show xgboost

Xgboost安装

	pip install xgboost
Xgboost优点
Xgboost算法可以给预测模型带来能力的提升
①正则化
Xgboost是以正则化提升技术而闻名的.
其在代价函数中添加了正则项,用于控制模型的复杂度.正则项包含了输的叶子节点个数,每个叶子节点上输出的score的L2模的平方和.
从Bias-variance tradeoff角度来讲,正则项降低了模型的variance,使学习出来的模型更加简单,防止过拟合.
②并行处理
Xgboost工具支持并行。众所周知,Boosting算法是顺序处理的,也是说Boosting不是一种串行的结构吗?怎么并行的?注意Xgboost的并行不是tree粒度的并行。Xgboost也是一次迭代完才能进行下一次迭代的(第t次迭代的代价函数里包含)。Xgboost的并行式在特征粒度上的,也就是说每一颗树的构造都依赖于前一颗树。

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

③灵活性

Xgboost支持用户自定义目标函数和评估函数,只要目标函数二阶可导就行。它对模型增加了一个全新的维度,所以我们的处理不会受到任何限制。

④缺失值处理

对于特征的值有缺失的样本,Xgboost可以自动学习出他的分裂方向。Xgboost内置处理缺失值的规则。用户需要提供一个和其他样本不同的值,然后把它作为一个参数穿进去,以此来作为缺失值的取值。Xgboost在不同节点遇到缺失值时采用不同的处理方法,并且会学习未来遇到缺失值时的处理方法。

⑤剪枝

Xgboost先从顶到底建立所有可以建立的子树,再从底到顶反向机芯剪枝,比起GBM,这样不容易陷入局部最优解

⑥内置交叉验证

Xgboost允许在每一轮Boosting迭代中使用交叉验证。因此可以方便的获得最优Boosting迭代次数,而GBM使用网格搜索,只能检测有限个值。

Xgboost参数

Xgboost使用k-v键值对的形式存储参数

	# xgboost模型
params = {
    'booster':'gbtree',
    'objective':'multi:softmax',   # 多分类问题
    'num_class':10,  # 类别数,与multi softmax并用
    'gamma':0.1,    # 用于控制是否后剪枝的参数,越大越保守,一般0.1 0.2的样子
    'max_depth':12,  # 构建树的深度,越大越容易过拟合
    'lambda':2,  # 控制模型复杂度的权重值的L2 正则化项参数,参数越大,模型越不容易过拟合
    'subsample':0.7, # 随机采样训练样本
    'colsample_bytree':3,# 这个参数默认为1,是每个叶子里面h的和至少是多少
    # 对于正负样本不均衡时的0-1分类而言,假设h在0.01附近,min_child_weight为1
    #意味着叶子节点中最少需要包含100个样本。这个参数非常影响结果,
    # 控制叶子节点中二阶导的和的最小值,该参数值越小,越容易过拟合
    'silent':0,  # 设置成1 则没有运行信息输入,最好是设置成0
    'eta':0.007,  # 如同学习率
    'seed':1000,
    'nthread':7,  #CPU线程数
    #'eval_metric':'auc'
}

在运行Xgboost之前,必须设置三种类型参数:general parameters,booster parameters和task parameters
①通用参数(General Parameters): 在提升过程中使用哪种booster,常用的booster有树模型(tree) 和线性模型(linear model)
②Booster参数(Booster Parameters): 这取决于使用哪种booster
③学习目标参数(Task Parameters): 控制学习场景

① 通用参数
booster [default=gbtree] 
有两种模型可以选择gbtree和gblinear。gbtree使用基于树的模型进行提升计算,gblinear使用线性模型进行提升计算。缺省值为gbtree
silent [default=0] 
	取0时表示打印出运行时信息,取1时表示以缄默方式运行,不打印运行时的信息。缺省值为0
	建议取0,过程中的输出数据有助于理解模型以及调参。另外实际上我设置其为1也通常无法缄默运行。。
nthread [default to maximum number of threads available if not set] 
	XGBoost运行时的线程数。缺省值是当前系统可以获得的最大线程数
	如果你希望以最大速度运行,建议不设置这个参数,模型将自动获得最大线程
num_pbuffer [set automatically by xgboost, no need to be set by user] 
	size of prediction buffer, normally set to number of training instances. The buffers are used to save the prediction results of last boosting step.
num_feature [set automatically by xgboost, no need to be set by user] 
	boosting过程中用到的特征维数,设置为特征个数。XGBoost会自动设置,不需要手工设置
②tree booster参数
eta [default=0.3] 
	为了防止过拟合,更新过程中用到的收缩步长。在每次提升计算之后,算法会直接获得新特征的权重。 eta通过缩减特征的权重使提升计算过程更加保守。
	缺省值为0.3
	取值范围为:[0,1]
	通常最后设置eta为0.01~0.2
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.
range: [0,∞]
	模型在默认情况下,对于一个节点的划分只有在其loss function 得到结果大于0的情况下才进行,而gamma 给定了所需的最低loss function的值
	gamma值使得算法更conservation,且其值依赖于loss function ,在模型中应该进行调参。
max_depth [default=6] 
	树的最大深度。缺省值为6
	取值范围为:[1,∞]
	指树的最大深度
	树的深度越大,则对数据的拟合程度越高(过拟合程度也越高)。即该参数也是控制过拟合
	建议通过交叉验证(xgb.cv ) 进行调参
	通常取值:3-10
min_child_weight [default=1] 
	孩子节点中最小的样本权重和。如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束。在现行回归模型中,这个参数是指建立每个模型所需要的最小样本数。该成熟越大算法越conservative。即调大这个参数能够控制过拟合。
	取值范围为: [0,∞]
max_delta_step [default=0] 
	Maximum delta step we allow each tree’s weight estimation to be. If the value is set to 0, it means there is no constraint. If it is set to a positive value, it can help making the update step more conservative. Usually this parameter is not needed, but it might help in logistic regression when class is extremely imbalanced. Set it to value of 1-10 might help control the update
	取值范围为:[0,∞]
	如果取值为0,那么意味着无限制。如果取为正数,则其使得xgboost更新过程更加保守。
	通常不需要设置这个值,但在使用logistics 回归时,若类别极度不平衡,则调整该参数可能有效果
subsample [default=1] 
	用于训练模型的子样本占整个样本集合的比例。如果设置为0.5则意味着XGBoost将随机的从整个样本集合中抽取出50%的子样本建立树模型,这能够防止过拟合。
	取值范围为:(0,1]
colsample_bytree [default=1] 
	在建立树时对特征随机采样的比例。缺省值为1
	取值范围:(0,1]
colsample_bylevel[default=1]
	决定每次节点划分时子样例的比例
	通常不使用,因为subsample和colsample_bytree已经可以起到相同的作用了
scale_pos_weight[default=0]
	A value greater than 0 can be used in case of high class imbalance as it helps in faster convergence.
	大于0的取值可以处理类别不平衡的情况。帮助模型更快收敛
③Linear Booster参数
lambda [default=0] 
	L2 正则的惩罚系数
	用于处理XGBoost的正则化部分。通常不使用,但可以用来降低过拟合
alpha [default=0] 
	L1 正则的惩罚系数
	当数据维度极高时可以使用,使得算法运行更快。
lambda_bias 
	在偏置上的L2正则。缺省值为0(在L1上没有偏置项的正则,因为L1时偏置不重要)
④学习目标参数
	这个参数是来控制理想的优化目标和每一步结果的度量方法。

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 ] 
	the initial prediction score of all instances, global bias
eval_metric [ default according to objective ] 
	校验数据所需要的评价指标,不同的目标函数将会有缺省的评价指标
	(rmse for regression, and error for classification, mean average precision for ranking)
	用户可以添加多种评价指标,对于Python用户要以list传递参数对给程序,而不是map参数list参数不会覆盖’eval_metric’
	The choices are listed below:
		“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 #(wrong cases)/#(all cases).
		“mlogloss”: Multiclass logloss
		“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
	可以用于产生可重复的结果(每次取一样的seed即可得到相同的随机划分)

Xgboost基本方法和默认参数
xgboost.train(params,dtrain,num_boost_round=10,evals(),obj=None,feval=None,maximize=False,early_stopping_rounds=None,
evals_result=None,verbose_eval=True,learning_rates=None,xgb_model=None)

parms:这是一个字典,里面包含着训练中的参数关键字和对应的值,形式是parms = {‘booster’:‘gbtree’,‘eta’:0.1}

dtrain:训练的数据

num_boost_round:这是指提升迭代的个数

evals:这是一个列表,用于对训练过程中进行评估列表中的元素。形式是evals = [(dtrain,‘train’),(dval,‘val’)] 或者是 evals =[(dtrain,‘train’)] ,对于第一种情况,它使得我们可以在训练过程中观察验证集的效果。

obj :自定义目的函数

feval:自定义评估函数

maximize:是否对评估函数进行最大化

early_stopping_rounds:早起停止次数,假设为100,验证集的误差迭代到一定程度在100次内不能再继续降低,就停止迭代。这要求evals里至少有一个元素,如果有多个,按照最后一个去执行。返回的是最后的迭代次数(不是最好的)。如果early_stopping_rounds存在,则模型会生成三个属性,bst.best_score ,bst.best_iteration和bst.best_ntree_limit

evals_result:字典,存储在watchlist中的元素的评估结果

verbose_eval(可以输入布尔型或者数值型):也要求evals里至少有一个元素,如果为True,则对evals中元素的评估结果会输出在结果中;如果输入数字,假设为5,则每隔5个迭代输出一次。

learning_rates:每一次提升的学习率的列表

xgb_model:在训练之前用于加载的xgb_model

使用:
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()
# 训练
my_model.fit(train_X, train_y, verbose=False)
# 预测
predictions = my_model.predict(test_x)

from sklearn.metrics import mean_absolute_error
print("平均绝对误差 : " + str(mean_absolute_error(predictions, test_y)))

n_estimators and early_stopping_rounds 参数调优 :
① n_estimators :指定完成上述建模周期的次数。
取值过小会导致欠拟合 取值过大会导致过拟合
一般取值范围 [100-1000]
② early_stopping_rounds : 模型不一定要到达n_estimators次迭代之后才停止,可以在确定了最佳值时停止迭代 这里就可以用到early_stopping_rounds ,这里的early_stopping_rounds 指的是最大容忍多大的变坏次数 一般可以设置为5

优化1:

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)

learning_rate 参数优化:

我们不是通过简单地将每个组件模型的预测相加来得到预测,而是将每个模型的预测乘以一个小数字,然后将它们相加。这意味着我们加入的每棵树对我们的帮助更少。在实践中,这减少了模型过度拟合的倾向。
因此,可以使用更高的n_estimators值,而不需要过度拟合。如果您使用early stop,则会自动设置适当的树的数量。
通常,一个小的学习率(和大量的估计器)将产生更精确的XGBoost模型,尽管它也将花费模型更长的时间来训练,因为它在周期中进行了更多的迭代。

优化2:

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)

n_job参数调优

在需要考虑运行时的大型数据集上,可以使用并行来更快地构建模型。通常将参数n_jobs设置为您机器上的核心数量。对于较小的数据集,这没有帮助。
这个参数不会对结果又影响,但是可以大大减轻大型数据集的训练时间

# 保存
my_model.save_model('my_model.model')
# 导出模型到文件
my_model.dump_model('dump.raw.txt')
# 导出模型和特征映射
my_model.dump_model('dump.raw.txt','featmap.txt')



#加载模型
my_model = Xgboost.Booster({'ntread':4} # init model
my_model.load_model('model.bin')# load data
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值