【机器学习第四期(Python)】LightGBM 方法原理详解
LightGBM 概述
- 一、LightGBM 简介
- 二、LightGBM 原理详解
- ⚙️ 核心原理
- 🧠 LightGBM 的主要特点
- 三、LightGBM 实现步骤(Python)
- 🧪 可调参数推荐
- 完整案例代码(回归任务 + 可视化)
- 参考
LightGBM 是由微软开源的 基于梯度提升框架(GBDT) 的机器学习算法,专为高性能、高效率设计,适用于大规模数据处理任务。它在准确率、训练速度和资源使用上都优于传统 GBDT 实现(如 XGBoost)。
一、LightGBM 简介
二、LightGBM 原理详解
⚙️ 核心原理
LightGBM 本质上是 Gradient Boosting Decision Tree(GBDT) 的一种高效实现。但它有两个关键创新:
1. 基于直方图的决策树算法(Histogram-based Algorithm)
将连续特征离散成固定数量的桶(bins),减少计算复杂度和内存占用。
计算增益时不再遍历所有可能的切分点,而是只在桶边界上寻找。
2. 叶子优先生长策略(Leaf-wise Tree Growth)
传统 GBDT 使用 Level-wise(按层生长) 方法。
LightGBM 使用 Leaf-wise(按叶节点增益最大优先扩展) 策略:
- 每次选择增益最大的叶子节点扩展,导致更深的树。
- 收敛更快,但可能更容易过拟合(需用 max_depth 控制)。
🧠 LightGBM 的主要特点
特性 | 描述 |
---|---|
高效率 | 训练速度远快于 XGBoost 和传统 GBDT |
内存占用低 | 使用直方图压缩数据 |
支持类别特征 | 无需独热编码,直接处理类别型特征 |
可扩展性强 | 支持大数据、分布式训练 |
数据支持 | 支持稀疏数据、缺失值自动处理 |
三、LightGBM 实现步骤(Python)
🧪 可调参数推荐
参数名 | 含义 | 说明 |
---|---|---|
num_leaves | 树的最大叶子数 | 值越大越容易过拟合 |
max_depth | 树的最大深度 | 控制模型复杂度 |
learning_rate | 学习率 | 越小越稳,但需要更多迭代 |
feature_fraction | 特征抽样率 | 防止过拟合 |
bagging_fraction | 数据抽样率 | 类似随机森林中的 bootstrap |
lambda_l1 / lambda_l2 | 正则项 | 控制模型复杂度 |
完整案例代码(回归任务 + 可视化)
绘制的效果图如下:
左图:拟合效果:拟合曲线很好地捕捉了数据的非线性趋势。
- 蓝点:训练数据
- 红点:测试数据
- 绿线:GBDT 拟合曲线
右图:残差图:残差应随机分布在 y=0 附近,没有明显模式,表明模型拟合良好。
输出结果为:
LightGBM Train MSE: 0.0581
LightGBM Test MSE: 0.0570
完整Python实现代码如下:
import numpy as np
import matplotlib.pyplot as plt
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error# 设置字体
plt.rcParams['font.family'] = 'Times New Roman'# 1. 生成数据
np.random.seed(42)
X = np.linspace(0, 10, 200).reshape(-1, 1)
y = np.sin(X).ravel() + np.random.normal(0, 0.2, X.shape[0])# 2. 划分训练/测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 3. 构造 LightGBM 数据集对象
train_dataset = lgb.Dataset(X_train, label=y_train)
test_dataset = lgb.Dataset(X_test, label=y_test, reference=train_dataset)# 4. 设置参数
params = {'objective': 'regression','metric': 'rmse','learning_rate': 0.1,'num_leaves': 15,'max_depth': 3,'verbose': -1,'seed': 42
}# 5. 训练 LightGBM 模型
model = lgb.train(params,train_dataset,num_boost_round=100,valid_sets=[train_dataset, test_dataset],valid_names=['train', 'test'],
)# 6. 预测与评估
y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)train_mse = mean_squared_error(y_train, y_train_pred)
test_mse = mean_squared_error(y_test, y_test_pred)print(f"LightGBM Train MSE: {train_mse:.4f}")
print(f"LightGBM Test MSE: {test_mse:.4f}")# 7. 可视化
plt.figure(figsize=(12, 6))# 7.1 拟合曲线图
plt.subplot(1, 2, 1)
plt.scatter(X_train, y_train, color='lightblue', label='Train Data', alpha=0.6)
plt.scatter(X_test, y_test, color='lightcoral', label='Test Data', alpha=0.6)X_all = np.linspace(0, 10, 1000).reshape(-1, 1)
y_all_pred = model.predict(X_all)
plt.plot(X_all, y_all_pred, color='green', label='LightGBM Prediction', linewidth=2)plt.title("LightGBM Model Fit", fontsize=15)
plt.xlabel("X", fontsize=14)
plt.ylabel("y", fontsize=14)
plt.legend()
plt.grid(True)# 7.2 残差图
plt.subplot(1, 2, 2)
train_residuals = y_train - y_train_pred
test_residuals = y_test - y_test_predplt.scatter(y_train_pred, train_residuals, color='blue', alpha=0.6, label='Train Residuals')
plt.scatter(y_test_pred, test_residuals, color='red', alpha=0.6, label='Test Residuals')
plt.axhline(y=0, color='black', linestyle='--')
plt.xlabel("Predicted y", fontsize=14)
plt.ylabel("Residuals", fontsize=14)
plt.title("Residual Plot", fontsize=15)
plt.legend()
plt.grid(True)plt.tight_layout()
plt.show()