用 Python 做 XGBoost 实战:分类与回归
一、前言
XGBoost(Extreme Gradient Boosting)是一种基于梯度提升树(Gradient Boosting Tree)的高效机器学习算法:
-
在 Kaggle 和数据竞赛中广泛使用
-
相比随机森林更快、更准确
-
可用于分类和回归任务
XGBoost 支持并行计算、正则化、防止过拟合,非常适合大规模数据分析。
二、XGBoost 简介
XGBoost 核心特点:
-
梯度提升:每棵树学习前一棵树的残差
-
正则化:控制模型复杂度,防止过拟合
-
支持缺失值处理
-
高效并行
常用参数:
-
n_estimators:树的数量 -
max_depth:树的最大深度 -
learning_rate:步长缩减 -
subsample:随机采样比例 -
colsample_bytree:每棵树随机选取特征比例
三、准备数据
以 Titanic 数据集进行分类任务示例:
import pandas as pd import seaborn as sns df = sns.load_dataset('titanic') df = df[['survived','pclass','age','sex','fare']].dropna() df['sex'] = df['sex'].map({'male':0, 'female':1}) X = df[['pclass','age','sex','fare']] y = df['survived']
-
survived为目标分类变量 -
pclass,age,sex,fare为特征
四、训练 XGBoost 分类模型
from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, confusion_matrix, classification_report X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) xgb_clf = XGBClassifier(n_estimators=100, max_depth=4, learning_rate=0.1, random_state=42) xgb_clf.fit(X_train, y_train) y_pred = xgb_clf.predict(X_test) print("Accuracy:", accuracy_score(y_test, y_pred)) print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))
-
输出分类准确率和混淆矩阵
-
支持概率预测和分类预测
五、特征重要性分析
import matplotlib.pyplot as plt from xgboost import plot_importance plt.figure(figsize=(8,6)) plot_importance(xgb_clf, max_num_features=5) plt.title('XGBoost Feature Importance') plt.show()
-
可直观判断哪些特征对生存预测最关键
六、XGBoost 回归示例
以波士顿房价预测为例:
from xgboost import XGBRegressor from sklearn.datasets import load_boston from sklearn.metrics import mean_squared_error import numpy as np boston = load_boston() X = pd.DataFrame(boston.data, columns=boston.feature_names) y = boston.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) xgb_reg = XGBRegressor(n_estimators=200, max_depth=5, learning_rate=0.05, random_state=42) xgb_reg.fit(X_train, y_train) y_pred = xgb_reg.predict(X_test) rmse = np.sqrt(mean_squared_error(y_test, y_pred)) print(f'RMSE: {rmse:.2f}')
-
XGBoost 回归可捕捉复杂非线性关系
-
调节
learning_rate与n_estimators提升模型精度
七、实际应用场景
-
🏦 金融风控:贷款违约预测、信用评分
-
🛍️ 用户行为预测:购买意向、流失概率
-
🏠 房价预测:回归建模
-
⚙️ 生产监控:分类或回归预测设备状态
XGBoost 在精度、速度和可解释性上都有优势,是实际业务与数据竞赛的利器。
更多推荐


所有评论(0)