0Pricing
Machine Learning Academy · レッスン

LightGBM:Leaf-Wise成長と速度面の利点

大規模データセットでLightGBMとXGBoostの性能を比較し、Leaf-WiseとLevel-Wiseの木の成長方法を理解して、カテゴリ特徴量のサポートを利用します。

「LightGBM:Leaf-Wise成長と速度面の利点」はCoddyKit上の無料Machine Learning Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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:Leaf-Wise成長と速度面の利点」レッスンは無料ですか?

はい。「LightGBM:Leaf-Wise成長と速度面の利点」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Machine Learning Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Machine Learning Academyコースには全4レッスンが含まれています。

「LightGBM:Leaf-Wise成長と速度面の利点」で何を学びますか?

大規模データセットでLightGBMとXGBoostの性能を比較し、Leaf-WiseとLevel-Wiseの木の成長方法を理解して、カテゴリ特徴量のサポートを利用します。 ブラウザで直接実行するハンズオンコードでMachine Learning Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Machine Learning Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのMachine Learning Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「LightGBM:Leaf-Wise成長と速度面の利点」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このMachine Learning Academyレッスンでコードを書いて実行できますか?

はい。すべてのMachine Learning Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. Boostingの直感:逐次的な誤差修正
  2. XGBoost:正則化、早期停止、特徴量の重要度
  3. LightGBM:Leaf-Wise成長と速度面の利点
  4. 主要なハイパーパラメータ:Learning Rate、n_estimators、max_depth
← Machine Learning Academyに戻る