集成学习5-Xgboost原理与调参

2023-11-02

github地址:DataScicence欢迎star
集成学习4-前向分步算法与GBDT-原理与案例
集成学习3-Boosting的原理和案例
集成学习2-bagging的原理与案例分析
集成学习1-投票法的原理和案例分析

XGBoost原理

Xgboost的大致原理与GBDT相似,但是在部分步骤中进行了改进

目标函数

xgboost与GBDT最大的不同就是目标函数

image-20210426100407643

上式中, y ^ i t − 1 \hat y_{i}^{t-1} y^it1表示前面t-1轮中生成的加权树模型的预测结果, Ω ( f i ) 表 示 正 则 项 Ω(f_i)表示正则项 Ω(fi)

接下来是重点,利用泰勒展开拟合目标函数

image-20210426101024758

前面t-1轮的训练误差是已知的,因此将上式改变为:

image-20210426101229206

函数g和h分别是1阶和2阶导数

定义树模型

f t ( x ) = w q ( x ) 每 个 节 点 的 权 重 f_t(x)=w_q(x) 每个节点的权重 ft(x)=wq(x)

q ( x ) 每 个 样 本 属 于 的 节 点 q(x)每个样本属于的节点 q(x)

I j = { i ∣ q ( x i ) = j } 每 个 节 点 的 样 本 集 合 I_{j}=\left\{i \mid q\left(\mathbf{x}_{i}\right)=j\right\}每个节点的样本集合 Ij={iq(xi)=j}
image-20210426102227348

如上图所示, q ( x 1 ) = 1 , q ( x 2 ) = 3 , q ( x 3 ) = 1 , q ( x 4 ) = 2 , q ( x 5 ) = 3 q(x_1) = 1,q(x_2) = 3,q(x_3) = 1,q(x_4) = 2,q(x_5) = 3 q(x1)=1,q(x2)=3,q(x3)=1,q(x4)=2,q(x5)=3 I 1 = { 1 , 3 } , I 2 = { 4 } , I 3 = { 2 , 5 } I_1 = \{1,3\},I_2 = \{4\},I_3 = \{2,5\} I1={1,3},I2={4},I3={2,5} w = ( 15 , 12 , 20 ) w = (15,12,20) w=(15,12,20)

重新定义树的复杂度:
Ω ( f K ) = γ T + 1 2 λ ∑ j = 1 T w j 2 \Omega\left(f_{K}\right) = \gamma T+\frac{1}{2} \lambda \sum_{j=1}^{T} w_{j}^{2} Ω(fK)=γT+21λj=1Twj2

重构目标函数

O b j ( t ) = ∑ i = 1 n [ g i f K ( x i ) + 1 2 h i f K 2 ( x i ) ] + γ T + 1 2 λ ∑ j = 1 T w j 2 = ∑ j = 1 T [ ( ∑ i ∈ I j g i ) w j + 1 2 ( ∑ i ∈ I j h i + λ ) w j 2 ] + γ T = [ G j w j + 1 2 ( H j + λ ) w j 2 ] + γ T \begin{aligned} Obj^{(t)} &=\sum_{i=1}^{n}\left[g_{i} f_{K}\left(\mathrm{x}_{i}\right)+\frac{1}{2} h_{i} f_{K}^{2}\left(\mathrm{x}_{i}\right)\right]+\gamma T+\frac{1}{2} \lambda \sum_{j=1}^{T} w_{j}^{2} \\ &=\sum_{j=1}^{T}\left[\left(\sum_{i \in I_{j}} g_{i}\right) w_{j}+\frac{1}{2}\left(\sum_{i \in I_{j}} h_{i}+\lambda\right) w_{j}^{2}\right]+\gamma T\\ &=[G_jw_j+\frac{1}{2}(H_j+λ)w^2_j]+γT \end{aligned} Obj(t)=i=1n[gifK(xi)+21hifK2(xi)]+γT+21λj=1Twj2=j=1TiIjgiwj+21iIjhi+λwj2+γT=[Gjwj+21(Hj+λ)wj2]+γT

式中:

image-20210426103512664

求解w和L:

找到令Obj最小的w:( a x 2 + b x + c ax^2+bx+c ax2+bx+c求解公式: x ∗ = − b 2 a x^*=-\frac{b}{2a} x=2ab)

image-20210426103950934

w j ∗ 代 入 O b j w_j^*代入Obj wjObj即可求得目标函数的值

所以分支后,目标函数的降低值为:

image-20210426105324266

寻找最佳分支

使用精确算法或近似算法,选择每一步中使Gain最大的分支方法

Xgboost案例

加载数据集

from sklearn.datasets import load_iris
import xgboost as xgb 
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,classification_report
iris = load_iris()
X,y = iris.data,iris.target
import pandas as pd 
X = pd.DataFrame(X,columns=iris.feature_names)
X.head()
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
0 5.1 3.5 1.4 0.2
1 4.9 3.0 1.4 0.2
2 4.7 3.2 1.3 0.2
3 4.6 3.1 1.5 0.2
4 5.0 3.6 1.4 0.2

训练模型

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3)
# 算法参数
params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 3,
    'gamma': 0.1,
    'max_depth': 6,
    'lambda': 2,
    'subsample': 0.7,
    'colsample_bytree': 0.75,
    'min_child_weight': 3,
    'eta': 0.1,
    'seed': 1,
    'nthread': 4,
}
dtrain = xgb.DMatrix(X_train,y_train)

model = xgb.XGBClassifier(**params)
model.fit(X_train,y_train)
y_pred = model.predict(X_test)
print(classification_report(y_test,y_pred))
[16:55:13] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.3.0/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       1.00      0.86      0.93        22
           2       0.77      1.00      0.87        10

    accuracy                           0.93        45
   macro avg       0.92      0.95      0.93        45
weighted avg       0.95      0.93      0.94        45

绘制特征重要性

xgb.plot_importance(model)
<matplotlib.axes._subplots.AxesSubplot at 0x2c2d525cc10>
image-20210426111824609

调参

常用参数:

参考:机器学习集成学习之XGBoost

from sklearn.model_selection import GridSearchCV
def Tuning(cv_params, other_params,x_train_array,y_train_):
    model2 = xgb.XGBClassifier(**other_params)
    optimized_GBM = GridSearchCV(estimator=model2, 
                                 param_grid=cv_params,
                                 scoring='accuracy',
                                 cv=5, 
                                 n_jobs=-1)
    optimized_GBM.fit(x_train_array, y_train_)
    evalute_result = optimized_GBM.cv_results_['mean_test_score']
    #print('每轮迭代运行结果:{0}'.format(evalute_result))
    print('参数的最佳取值:{0}'.format(optimized_GBM.best_params_))
    print('最佳模型得分:{0}'.format(optimized_GBM.best_score_))
    return optimized_GBM
other_params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 3
}
cv_params = {
    'learning_rate':[0.01, 0.02, 0.05, 0.1, 0.15],
}
opt = Tuning(cv_params,other_params,X_train,y_train)
[17:02:24] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.3.0/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
参数的最佳取值:{'learning_rate': 0.01}
最佳模型得分:0.9619047619047618
other_params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 3,
    'learning_rate':0.01,
}
cv_params = {
    'max_depth': [2,3,4,5],
    'min_child_weight': [0, 2, 5, 10, 20],
}
opt = Tuning(cv_params,other_params,X_train,y_train)
[17:03:16] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.3.0/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
参数的最佳取值:{'max_depth': 2, 'min_child_weight': 0}
最佳模型得分:0.9619047619047618


C:\Users\lipan\anaconda3\lib\site-packages\xgboost\sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].
  warnings.warn(label_encoder_deprecation_msg, UserWarning)
other_params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 3,
    'learning_rate':0.01,
    'max_depth': 2,
    'min_child_weight': 0,

}
cv_params = {
    'subsample': [0.6, 0.7, 0.8, 0.85, 0.95],
    'colsample_bytree': [0.5, 0.6, 0.7, 0.8, 0.9],
}
opt = Tuning(cv_params,other_params,X_train,y_train)
C:\Users\lipan\anaconda3\lib\site-packages\xgboost\sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].
  warnings.warn(label_encoder_deprecation_msg, UserWarning)


[17:04:37] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.3.0/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
参数的最佳取值:{'colsample_bytree': 0.5, 'subsample': 0.95}
最佳模型得分:0.9619047619047618
other_params = {
    'booster': 'gbtree',
    'objective': 'multi:softmax',
    'num_class': 3,
    'learning_rate':0.01,
    'max_depth': 2,
    'min_child_weight': 0,
    'subsample': 0.95,
    'colsample_bytree': 0.5
}
cv_params = {
    
    'reg_alpha': [0, 0.25, 0.5, 0.75, 1],
}
opt = Tuning(cv_params,other_params,X_train,y_train)
[17:06:08] WARNING: C:/Users/Administrator/workspace/xgboost-win64_release_1.3.0/src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'multi:softprob' was changed from 'merror' to 'mlogloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
参数的最佳取值:{'reg_alpha': 0}
最佳模型得分:0.9619047619047618


C:\Users\lipan\anaconda3\lib\site-packages\xgboost\sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].
  warnings.warn(label_encoder_deprecation_msg, UserWarning)
y_pred = opt.best_estimator_.predict(X_test)
print(classification_report(y_test,y_pred))
              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       1.00      0.86      0.93        22
           2       0.77      1.00      0.87        10

    accuracy                           0.93        45
   macro avg       0.92      0.95      0.93        45
weighted avg       0.95      0.93      0.94        45

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

集成学习5-Xgboost原理与调参 的相关文章

随机推荐

  • 支持STEM学习的九个方式

    随着STEM教育的兴起 一些国家把STEM教育提升到了国家战略层面 相继出台了促进STEM人才培养的政策措施 加大STEM教育的公共和私人投资 整合政府 大中小学 企业 科研机构 社区和家庭多方力量 共同促进STEM教育发展 接下来 格物斯
  • 如何在树莓派上使用Nginx搭建本地站点并通过内网穿透实现远程访问

    文章目录 1 Nginx安装 2 安装cpolar 3 配置域名访问Nginx 4 固定域名访问 5 配置静态站点 安装 Nginx 发音为 engine x 可以将您的树莓派变成一个强大的 Web 服务器 可以用于托管网站或 Web 应用
  • svg转换png,svg转png格式步骤

    svg转换png svg转png格式步骤 在过去一年多的工作经历中 我接触到了大量的图片 认识到了各种图片格式 每种格式图片拥有的属性是不一样的 就像我们每个人所具备的属性性格特点不同一个道理 比如SVG是一种图形文件格式 用户可以直接用代
  • 网络错误代码

    网络错误代码 又称ADSL错误代码 ADSL Asymmetric Digital Subscriber Line 非对称数字用户环路 是中国电信报提供的一种新的数据传输方式 它因为上行和下行带宽不对称 因此称为非对称数字用户线环路 它采用
  • 混淆矩阵的计算方式

    下图中有三个序列 L表示标签值 P表示预测值 n表示分类数 我们需要计算n L P来计算预测结果值 当L和P都取最大时 得出的结果就是其最大计算空间 例如下图 L 0 5 P 0 5 则n L P 0 35 然后我们将n L P映射到36维
  • Linux的环境配置文件----.bashrc文件

    bashrc文件主要保存个人的一些个性化设置 如命令别名 路径等 也即在同一个服务器上 只对某个用户的个性化设置相关 它是一个隐藏文件 需要使用ls a来查看 bash history 记录之前输入的命令 bash logout 当你退出时
  • 南大通用GBase8s 常用SQL语句(256)

    使用 FILE TO 选项 当您执行 SET EXPLAIN FILE TO 语句时 开启说明输出 SET EXPLAIN FILE TO 语句可更改说明输出的缺省的文件名称 直到会话结束为止 或直到发出另一 SET EXPLAIN 语句为
  • vue账号密码登录增加记住密码功能

    实现思路 刷新登录页面时查看cookie中是否存储用户名 密码 是否记住密码 如果有就将cookie中的用户名和密码回显到form表单中 如果没有则将用户输入的用户名和密码存入cookie html代码 只截取了部分账号密码功能部分代码 主
  • 1. 数学导论 - 概述

    文章目录 为什么需要数学 人类如何表示数字 计算机可以做什么 因为部分自媒体上无法显示公式 为了方便 有的地方我是直接整段截图 和文章字体不一致的部分还望见谅 Hi 大家好 又见面了 我是茶桁 这次我依然给大家带来的是基础部分 让我们进入
  • HTTP代理IP使爬虫轻松面对反爬虫

    在数据信息变的越发重要的时候 咱们可以从许多场所去取得数据源 不过要控制好数据抓取的方式 今天介绍一下数据抓取怎么样可以避免出现IP封停问题 先说一下爬虫的分类 爬虫一般分为三类 1 传统爬虫 从一个或若干初始网页的URL开始 取得初始网页
  • EBS销售订单挑库发放处理程序

    在EBS实施中 经常遇到从外部传进来一个被登记的销售订单 需要通过程序进行销售订单的挑库发放 下面是对SO挑库发放的实现步骤的详细实现 1 对销售订单的有效性验证 1 检查销售订单的行是否被完全传回客户化表 2 验证销售订单的关键字段 3
  • CTF之web安全

    web安全 CSRF 简介 CSRF 全名 Cross Site Request Forgery 跨站请求伪造 很容易将它与 XSS 混淆 对于 CSRF 其两个关键点是跨站点的请求与请求的伪造 由于目标站无 token 或 referer
  • 灰度斜坡intensity ramp和灰度台阶intensity step的区别

    在数字图像处理中 锐化处理关注的是灰度变化 discontinuities 的过渡部分 包括灰度台阶和灰度斜坡两种情况的突变 step and ramp discontinuities 那么这二者有什么区别呢 老猿理解 灰度斜坡 inten
  • 终于还是对闲鱼下手了。闲鱼爬虫,idlefish spider来了

    闲鱼目前最大的问题在于没有html请求口子了 闲鱼用了自家的app口子 而且还有spdy协议 拒绝使用代理 如果想采集闲鱼数据 并保存下来 做个对比分析之类的 传统的非传统的招数都已经凉了 怎么说呢 面对闲鱼 你想抓个包都不好抓了 所以 这
  • Win11注册表编辑器误删了如何恢复?

    注册表编辑器是一个用来更改系统注册表设置的高级工具 与资源管理器的界面很类似 近期有用户将注册表编辑器误删了 那么应该如何恢复呢 下面小编就给大家分享一下详细的恢复方法 遇到同样问题的用户注意了 更多重装系统教程尽在小白系统重装官网 1 首
  • 「量化」快乐:UC Berkeley 利用 AI 追踪多巴胺释放量及释放脑区

    内容一览 多巴胺是神经系统中重要的神经递质 与运动 记忆和奖赏系统息息相关 它是快乐的信使 当我们看到令人愉悦的东西时 体内就会分泌多巴胺 诱导我们向它追寻 然而 多巴胺的准确定量分析目前仍难以实现 借助机器学习 美国加利福尼亚大学伯克利分
  • mw325r 服务器无响应),水星(MERCURY)MW325R路由器连不上网怎么办?

    路由器换ip小助手 路由器换ip工具 是一款切换ip软件 专门适用于使用路由器上网的用户 有时候由于ip限制 需要更换上网ip地址 由于使用路由器上网 没有像拨号上网那样方便重新拨号就能换ip 每次需要重启路由器才可以 那这款专门给路由器用
  • SpringBoot+Mybatis多数据源配置

    SpringBoot Mybatis多数据源配置 Step1 在application properties配置两个数据源 数据源1 spring datasource one url jdbc mysql localhost 3306 s
  • Qt6 ffmpeg 音频和视频(非同步)推流到nginx-rtmp

    main cpp include
  • 集成学习5-Xgboost原理与调参

    github地址 DataScicence欢迎star 集成学习4 前向分步算法与GBDT 原理与案例 集成学习3 Boosting的原理和案例 集成学习2 bagging的原理与案例分析 集成学习1 投票法的原理和案例分析 Xgboost