XGBoost模型的python实现


作者:李雪茸

函数介绍

实现 XGBoost 分类算法使用的是 xgboost 库的 XGBClassifier,具体参数如下:

  • 1、max_depth:给定树的深度,默认为3

  • 2、learning_rate:每一步迭代的步长,很重要。太大了运行准确率不高,太小了运行速度慢。我们一般使用比默认值小一点,0.1左右就好

  • 3、n_estimators:这是生成的最大树的数目,默认为100

  • 4、objective:给定损失函数,常用的有:
    – reg:linear– 线性回归
    – reg:logistic – 逻辑回归
    – binary:logistic – 二分类逻辑回归
    – binary:logitraw – 二分类逻辑回归
    – count:poisson – 计数问题的poisson回归

  • 5、booster:给定模型的求解方式,默认为:gbtree;可选参数:gbtree、gblinear,gbtree是采用树的结构来运行数据,而gblinear是基于线性模型

  • 6、gamma:指定了节点分裂所需的最小损失函数下降值。这个参数的值越大,算法越保守。范围: [0,∞]

  • 7、alpha:L1正则项的权重,推荐的候选值为:[0, 0.01~0.1, 1]

  • 8、lambda:L2正则项的权重,推荐的候选值为:[0, 0.1, 0.5, 1]

  • 9、num_class:用于设置多分类问题的类别个数

  • 10、min_child_weight:指定子节点中最小的样本权重和,如果一个叶子节点的样本权重和小于min_child_weight则拆分过程结束,默认值为1。

  • 11、subsample:默认值1,指定采样出 subsample * n_samples 个样本用于训练弱学习器。取值在(0, 1)之间,设置为1表示使用所有数据训练弱学习器。

  • 12、colsample_bytree:构建弱学习器时,对特征随机采样的比例,默认值为1

实例

from xgboost import XGBClassifier
from sklearn.datasets import load_iris
from sklearn.datasets import load_breast_cancer
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_curve, auc
import matplotlib.pyplot as plt

二分类问题

# 举例(二分类)
cancer = load_breast_cancer()
x = cancer.data
y = cancer.target
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.333, random_state=0)  # 分训练集和验证集
model = XGBClassifier(max_depth=10,
                        learning_rate=0.01,
                        n_estimators=2000,
                        objective='binary:logistic',
                        nthread=-1,
                        gamma=0,
                        min_child_weight=1,
                        max_delta_step=0,
                        subsample=0.85,
                        colsample_bytree=0.7,
                        colsample_bylevel=1,
                        reg_alpha=0,
                        reg_lambda=1,
                        scale_pos_weight=1,
                        seed=1440)
model.fit(x_train, y_train,eval_metric='auc')# 'rmse’:用于回归任务 ;'mlogloss’,用于多分类任务;
                                             # 'error’,用于二分类任务; 'auc’,用于二分类任务
# 对测试集进行预测
y_pred = model.predict(x_test)
predictions = [round(value) for value in y_pred]
#计算准确率
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
print(f"\nXGBoost模型混淆矩阵为:\n{metrics.confusion_matrix(y_test,y_pred)}")

####绘制ROC曲线
fpr1,tpr1,threshold1 = roc_curve(y_test,y_pred)
roc_auc1 = auc(fpr1, tpr1)
lw = 2
plt.figure(figsize=(8, 5))
plt.plot(fpr1, tpr1, color='darkorange',
lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) 
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('XGBoost ROC')
plt.legend(loc="lower right")
plt.show()
print(f"\nXGBoost模型AUC值为:\n{roc_auc_score(y_test,y_pred)}")

在这里插入图片描述
在这里插入图片描述

多分类问题

###举例 (多分类)
# 加载样本数据集
iris = load_iris()
X,y = iris.data,iris.target
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=12343)
 
model = XGBClassifier(
    max_depth=3,
    learning_rate=0.1,
    n_estimators=100, # 使用多少个弱分类器
    num_class=3,
    booster='gbtree',
    gamma=0,
    min_child_weight=1,
    max_delta_step=0,
    subsample=1,
    colsample_bytree=1,
    reg_alpha=0,
    reg_lambda=1,
    seed=0 # 随机数种子
)
model.fit(X_train,y_train,eval_metric='mlogloss')# 'rmse’:用于回归任务 ;'mlogloss’,用于多分类任务;
                                                 # 'error’,用于二分类任务; 'auc’,用于二分类任务
 
# 对测试集进行预测
y_pred = model.predict(X_test)
predictions = [round(value) for value in y_pred]
#计算准确率
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
print(f"\nXGBoost模型混淆矩阵为:\n{metrics.confusion_matrix(y_test,y_pred)}")

在这里插入图片描述

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
xgboost模型python实战中,我们可以使用xgboost库来构建和训练模型。首先,我们需要定义一个目标函数(objective)来评估模型的性能。在该目标函数中,我们可以指定待优化的函数并设定参/超参数的范围。接下来,我们可以使用单次试验(trial)来执行目标函数,并记录试验结果。最后,我们可以使用研究(study)来管理优化过程,决定优化的方式,包括试验次数和结果记录等功能。通过使用xgboost模型,我们可以根据输入的特征,如房屋总面积、总房间数、浴室数量等,来预测房屋的总价值。这样的模型可以帮助我们更好地理解房屋价值的影响因素,并提供更精确的房屋价格预测。123 #### 引用[.reference_title] - *1* [【项目实战】基于Python实现xgboost回归模型(XGBRegressor)项目实战](https://blog.csdn.net/weixin_42163563/article/details/121110926)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *2* [Python实现基于Optuna超参数自动优化的xgboost回归模型(XGBRegressor算法)项目实战](https://blog.csdn.net/weixin_42163563/article/details/128068041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *3* [【项目实战】Python实现xgboost分类模型(XGBClassifier算法)项目实战](https://blog.csdn.net/weixin_42163563/article/details/121154223)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值