0Pricing
Machine Learning Academy · Ders

LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları

LightGBM'yi büyük bir veri kümesinde XGBoost ile karşılaştırmalı olarak ölçün, yaprak bazlı ve seviye bazlı ağaç büyümesini anlayın ve kategorik özellik desteğini kullanın.

LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları, CoddyKit'te ücretsiz bir Machine Learning Academy dersidir. Bu, 4 dersinin 3. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Machine Learning Academy öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Machine Learning Academy kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları” dersi ücretsiz mi?

Evet — “LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Machine Learning Academy kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Machine Learning Academy kursu toplamda 4 dersten oluşur.

“LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları” dersinde ne öğreneceğim?

LightGBM'yi büyük bir veri kümesinde XGBoost ile karşılaştırmalı olarak ölçün, yaprak bazlı ve seviye bazlı ağaç büyümesini anlayın ve kategorik özellik desteğini kullanın. Machine Learning Academy ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Machine Learning Academy öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Machine Learning Academy, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 3. dersidir.

“LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Machine Learning Academy dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Machine Learning Academy dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Boosting Sezgisi: Sıralı Hata Düzeltme
  2. XGBoost: Düzenlileştirme, Erken Durdurma ve Özellik Önem Derecesi
  3. LightGBM: Yaprak Bazlı Büyüme ve Hız Avantajları
  4. Temel Hiperparametreler: Öğrenme Oranı, n_estimators ve max_depth
← Machine Learning Academy Sayfasına Dön