0Pricing
Machine Learning Academy · 课时

LightGBM:按叶节点生长与速度优势

您将基于大型数据集对 LightGBM 和 XGBoost 进行基准测试,理解按叶节点生长与按层级生长的区别,并使用分类特征支持

LightGBM:按叶节点生长与速度优势 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What Is LightGBM?

LightGBM (Light Gradient Boosting Machine) is a gradient boosting library developed by Microsoft in 2017. It was designed specifically to address XGBoost's speed and memory limitations on large datasets. LightGBM introduced two key algorithmic innovations: Gradient-based One-Side Sampling (GOSS) for reducing the number of data instances considered at each round, and Exclusive Feature Bundling (EFB) for reducing the number of features by bundling mutually exclusive sparse features. Together these make LightGBM significantly faster than XGBoost on large tabular datasets.

Level-Wise vs Leaf-Wise Tree Growth

Most gradient boosting implementations (including XGBoost by default) grow trees level-wise: all nodes at depth 1 are split before any node at depth 2. This ensures balanced trees but wastes computation on splits that reduce loss by very little. LightGBM grows trees leaf-wise: at each step, it finds the single leaf across the entire tree that would reduce loss the most and splits it, regardless of level. This produces unbalanced trees that reduce loss faster per split, requiring fewer splits to achieve the same accuracy.

Risk of Overfitting with Leaf-Wise Growth

Leaf-wise growth can overfit on small datasets because it aggressively pursues the largest loss reduction, potentially memorising individual examples in very deep leaves. The fix is the num_leaves parameter (maximum total leaves in one tree). Setting num_leaves appropriately limits tree complexity more precisely than max_depth alone. A common rule of thumb: num_leaves = 2^(max_depth) / 2. For a max_depth-equivalent of 6, try num_leaves around 32-50.

import lightgbm as lgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score

X, y = load_breast_cancer(return_X_y=True)
for nl in [8, 16, 31, 64, 128]:
    model = lgb.LGBMClassifier(n_estimators=100, num_leaves=nl, learning_rate=0.1,
                                random_state=42, verbose=-1)
    score = cross_val_score(model, X, y, cv=5).mean()
    print(f'num_leaves={nl:4d}: CV accuracy={score:.4f}')

Installing and Basic Usage of LightGBM

LightGBM is installed via pip install lightgbm. Like XGBoost, it provides a scikit-learn-compatible API through LGBMClassifier and LGBMRegressor. Set verbose=-1 to suppress the training output (LightGBM is chatty by default). The key hyperparameters are similar to XGBoost: n_estimators, learning_rate, num_leaves (instead of max_depth), and subsample.

# Install: pip install lightgbm
import lightgbm as lgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = lgb.LGBMClassifier(
    n_estimators=200,
    learning_rate=0.05,
    num_leaves=31,
    random_state=42,
    verbose=-1
)
model.fit(X_train, y_train)
print('LightGBM test accuracy:', model.score(X_test, y_test))

Speed Benchmark: LightGBM vs XGBoost

LightGBM is generally 5-10x faster than XGBoost on large datasets while achieving similar or better accuracy. The speed advantage comes from: (1) histogram-based split finding (groups continuous feature values into discrete bins, reducing split candidate computation from O(n) to O(bins)); (2) leaf-wise growth (fewer splits needed); (3) GOSS (trains only on high-gradient and randomly sampled low-gradient examples). The speed advantage is most pronounced for datasets with >100,000 rows or >1,000 features.

import lightgbm as lgb
import xgboost as xgb
from sklearn.datasets import fetch_california_housing
import time, numpy as np

X, y = fetch_california_housing(return_X_y=True)

lgb_model = lgb.LGBMRegressor(n_estimators=300, verbose=-1, random_state=42)
xgb_model = xgb.XGBRegressor(n_estimators=300, eval_metric='rmse', verbosity=0, random_state=42)

for name, m in [('LightGBM', lgb_model), ('XGBoost', xgb_model)]:
    start = time.time()
    m.fit(X, y)
    print(f'{name}: {round(time.time()-start, 2)}s')

Categorical Feature Support

One of LightGBM's practical advantages is native categorical feature support. Instead of requiring one-hot encoding, you can pass categorical column indices to the categorical_feature parameter. LightGBM learns optimal splits by testing all category groupings, which is more expressive than binary one-hot splits and avoids the high-cardinality blowup from one-hot encoding features with hundreds of categories. This is particularly useful for e-commerce datasets with product IDs or location codes.

import lightgbm as lgb
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

np.random.seed(42)
n = 1000
df = pd.DataFrame({'color': np.random.choice(['red', 'blue', 'green'], n),
                   'size': np.random.randint(1, 10, n),
                   'label': np.random.randint(0, 2, n)})
df['color'] = df['color'].astype('category')
X, y = df[['color', 'size']], df['label']
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2)
model = lgb.LGBMClassifier(n_estimators=50, verbose=-1)
model.fit(X_tr, y_tr, categorical_feature=['color'])
print('Accuracy with native categoricals:', round(model.score(X_te, y_te), 4))

Early Stopping in LightGBM

LightGBM supports early stopping through callbacks. Pass an early_stopping callback with the number of patience rounds and a log_evaluation callback to control verbosity. The best model state (best_iteration_) is automatically used for prediction. Like XGBoost, this allows you to set n_estimators very high and let early stopping find the sweet spot without overfitting.

import lightgbm as lgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

model = lgb.LGBMClassifier(n_estimators=1000, learning_rate=0.05, num_leaves=31, random_state=42)
model.fit(X_tr, y_tr,
          eval_set=[(X_val, y_val)],
          callbacks=[lgb.early_stopping(stopping_rounds=20), lgb.log_evaluation(0)])
print('Best iteration:', model.best_iteration_)
print('Val accuracy:', round(model.score(X_val, y_val), 4))

Key Hyperparameters in LightGBM

The most important LightGBM hyperparameters: num_leaves (controls complexity, primary regularisation lever), learning_rate (lower = more trees needed, better generalisation), min_child_samples (minimum examples per leaf, raises with num_leaves to prevent overfitting), subsample and colsample_bytree (stochastic regularisation), and reg_alpha/reg_lambda (L1/L2 penalties). Start with defaults and tune num_leaves and min_child_samples first.

LightGBM for Regression

LGBMRegressor works identically for regression tasks. It supports multiple loss functions via the objective parameter: 'regression' (L2), 'regression_l1' (MAE), 'huber' (robust to outliers), and 'quantile' (for prediction intervals). Quantile regression with LightGBM is especially useful in production: train one model for the 10th percentile and one for the 90th percentile to produce calibrated uncertainty bounds around predictions.

import lightgbm as lgb
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import cross_val_score
import numpy as np

X, y = fetch_california_housing(return_X_y=True)
model = lgb.LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=31,
                           verbose=-1, random_state=42)
rmse = np.sqrt(-cross_val_score(model, X, y, scoring='neg_mean_squared_error', cv=3).mean())
print('LightGBM Regression RMSE:', round(rmse, 4))

Choosing Between XGBoost and LightGBM

Both XGBoost and LightGBM are excellent. Practical guidance: use LightGBM when your dataset is large (>100K rows), you need fast iteration during exploration, or you have high-cardinality categorical features. Use XGBoost when your dataset is small-to-medium, you want more conservative level-wise growth that is harder to overfit on noisy data, or the team is already experienced with XGBoost. In competitions, both are tried and the better one on the validation set is chosen. CatBoost is a third strong alternative with even better categorical handling.

LightGBM Feature Importance

Like XGBoost, LightGBM provides feature importance accessible via model.feature_importances_ (uses split count by default in sklearn API) or model.booster_.feature_importance(importance_type='gain'). The gain type is usually more informative — it measures the average improvement in loss per split using that feature. LightGBM also supports SHAP values for model-agnostic explanations via model.predict(X, pred_contrib=True) in the native API, providing granular per-prediction feature attributions.

import lightgbm as lgb
import pandas as pd
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()
X, y = data.data, data.target

model = lgb.LGBMClassifier(n_estimators=100, verbose=-1, random_state=42)
model.fit(X, y)
importances = pd.Series(model.feature_importances_, index=data.feature_names)
print(importances.sort_values(ascending=False).head(5))

Quick Check

Test your understanding of LightGBM's growth strategy from this lesson.

Lesson Recap

In this lesson you learned: LightGBM's leaf-wise growth finds the best single leaf to split at each round, converging faster than level-wise growth, num_leaves is the primary complexity control replacing max_depth, and LightGBM's native categorical support avoids one-hot encoding overhead. Next up we explore the key hyperparameters learning rate, n_estimators, and max_depth in detail.

常见问题解答

「LightGBM:按叶节点生长与速度优势」课时是免费的吗?

是的 — 「LightGBM:按叶节点生长与速度优势」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。

「LightGBM:按叶节点生长与速度优势」这节课中我会学到什么?

您将基于大型数据集对 LightGBM 和 XGBoost 进行基准测试,理解按叶节点生长与按层级生长的区别,并使用分类特征支持 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Machine Learning Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「LightGBM:按叶节点生长与速度优势」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Machine Learning Academy 课中编写并运行代码吗?

能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 提升方法直觉:顺序误差修正
  2. XGBoost:正则化、提前停止与特征重要性
  3. LightGBM:按叶节点生长与速度优势
  4. 关键超参数:学习率、n_estimators 与 max_depth
← 返回 Machine Learning Academy