【机器学习】加速并提升 XGBoost 模型性能的 3 种方法
【精选优质专栏推荐】
- 《AI 技术前沿》 —— 紧跟 AI 最新趋势与应用
- 《网络安全新手快速入门(附漏洞挖掘案例)》 —— 零基础安全入门必看
- 《BurpSuite 入门教程(附实战图文)》 —— 渗透测试必备工具详解
- 《网安渗透工具使用教程(全)》 —— 一站式工具手册
- 《CTF 新手入门实战教程》 —— 从题目讲解到实战技巧
- 《前后端项目开发(新手必知必会)》 —— 实战驱动快速上手
每个专栏均配有案例与图文讲解,循序渐进,适合新手与进阶学习者,欢迎订阅。
文章目录

引言
极端梯度提升(XGBoost)是当前最流行的机器学习技术之一,不仅广泛用于实验和数据分析,也在工业中的预测性解决方案中得到实际应用。XGBoost 集成模型通过组合多个模型来完成分类、回归或预测等任务。其训练方式为序列化训练多棵决策树,通过不断修正前一棵树产生的误差,逐步提升预测结果的准确性。
本文将从实用角度出发,介绍三种提升 XGBoost 性能和加速训练的方法。
初始设置
为了说明提升与加速 XGBoost 模型的三种策略,我们使用一个包含员工人口统计和财务属性的数据集。该数据集在此仓库公开提供。
以下代码用于加载数据集、移除缺失值实例,并将“income”设为预测目标变量,同时将其与特征分离:
import pandas as pd
url = 'https://raw.githubusercontent.com/gakudo-ai/open-datasets/main/employees_dataset_with_missing.csv'
df = pd.read_csv(url).dropna()
X = df.drop(columns=['income'])
y = df['income']
1. 使用清洗数据进行提前停止(Early Stopping)
虽然提前停止常用于复杂神经网络模型,但在 XGBoost 等集成方法中也很有效,可在效率与准确性之间取得平衡。提前停止指在验证集性能稳定且改进有限时,中断迭代训练过程。这样不仅节省在大数据集上训练大规模集成模型的成本,还能降低过拟合风险。
此示例首先导入必要库,并对数据进行预处理以更适合 XGBoost,包括对分类特征进行编码(如存在)及将数值特征降精度以提升效率。随后,将数据集划分为训练集与验证集:
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pandas as pd
import numpy as np
X_enc = pd.get_dummies(X, drop_first=True, dtype="uint8")
num_cols = X_enc.select_dtypes(include=["float64", "int64"]).columns
X_enc[num_cols] = X_enc[num_cols].astype("float32")
X_train, X_val, y_train, y_val = train_test_split(
X_enc, y, test_size=0.2, random_state=42
)
接着训练并测试 XGBoost 模型。核心技巧是在初始化模型时使用 early_stopping_rounds 参数。该参数的值表示在多少轮训练未出现显著提升后应停止训练:
model = XGBRegressor(
tree_method="hist",
n_estimators=5000,
learning_rate=0.01,
eval_metric="rmse",
early_stopping_rounds=50,
random_state=42,
n_jobs=-1
)
model.fit(
X_train, y_train,
eval_set=[(X_val, y_val)],
verbose=False
)
y_pred = model.predict(X_val)
rmse = np.sqrt(mean_squared_error(y_val, y_pred))
print(f"Validation RMSE: {rmse:.4f}")
print(f"Best iteration (early-stopped): {model.best_iteration}")
2. 原生分类特征处理(Native Categorical Handling)
第二种策略适用于包含分类属性的数据集。由于员工数据集无分类特征,我们通过将现有“education_years”分箱生成一个模拟分类特征 education_level:
bins = [0, 12, 16, float('inf')] # 假设 <12 年为低,12-16 年为中,>16 年为高
labels = ['low', 'medium', 'high']
X['education_level'] = pd.cut(X['education_years'], bins=bins, labels=labels, right=False)
display(X.head(50))
该策略关键在于在训练过程中高效处理分类特征。XGBoost 模型构造函数中有一个较少被注意的参数设置:enable_categorical=True。启用后可避免传统的独热编码(One-Hot Encoding),尤其在多分类特征且每个特征类别较多时,可有效降低维度爆炸问题,从而提高效率。此外,原生分类处理可透明地学习最优类别分组,如“一对多”方式,而无需将所有类别单独处理。
将该策略应用于代码非常简单:
from sklearn.metrics import mean_absolute_error
for col in X.select_dtypes(include=['object', 'category']).columns:
X[col] = X[col].astype('category')
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
model = XGBRegressor(
tree_method='hist',
enable_categorical=True,
learning_rate=0.01,
early_stopping_rounds=30,
n_estimators=500
)
model.fit(
X_train, y_train,
eval_set=[(X_val, y_val)],
verbose=False
)
y_pred = model.predict(X_val)
print("Validation MAE:", mean_absolute_error(y_val, y_pred))
3. 使用 GPU 加速进行超参数调优(Hyperparameter Tuning with GPU Acceleration)
第三种策略在寻求效率方面可能显而易见,因为它与硬件相关,但对于诸如超参数调优等耗时流程,其显著价值值得强调。可以使用 device='cuda' 并将运行类型设置为 GPU(如果在如 Google Colab 的笔记本环境中操作,仅需一次点击即可完成),以加速 XGBoost 集成模型的微调流程,如下示例:
from sklearn.model_selection import GridSearchCV
base_model = XGBRegressor(
tree_method='hist',
device='cuda', # GPU 加速关键设置
enable_categorical=True,
eval_metric='rmse',
early_stopping_rounds=20,
random_state=42
)
# 超参数调优
param_grid = {
'max_depth': [4, 6],
'subsample': [0.8, 1.0],
'colsample_bytree': [0.8, 1.0],
'learning_rate': [0.01, 0.05]
}
grid_search = GridSearchCV(
estimator=base_model,
param_grid=param_grid,
scoring='neg_root_mean_squared_error',
cv=3,
verbose=1,
n_jobs=-1
)
grid_search.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)
# 获取最佳模型
best_model = grid_search.best_estimator_
y_pred = best_model.predict(X_val)
# 评估模型
rmse = np.sqrt(mean_squared_error(y_val, y_pred))
print(f"Best hyperparameters: {grid_search.best_params_}")
print(f"Validation RMSE: {rmse:.4f}")
print(f"Best iteration (early-stopped): {getattr(best_model, 'best_iteration', 'N/A')}")
总结
本文展示了三个实用示例,说明如何在 XGBoost 模型的不同建模环节提升效率。具体而言,我们学习了如何在训练过程中使用提前停止以应对误差稳定情况、如何原生处理分类特征而无需(有时繁琐的)独热编码,以及如何借助 GPU 优化本应耗费大量时间的流程,如模型微调。
更多推荐


所有评论(0)