LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile
Vergleichen Sie LightGBM auf einem großen Datensatz mit XGBoost, verstehen Sie blattweises und ebenenweises Baumwachstum und nutzen Sie die Unterstützung kategorialer Features.
LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile ist eine kostenlose Machine Learning Academy-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Machine Learning Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Machine Learning Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile“ kostenlos?
Ja — der vollständige Text von „LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Machine Learning Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Machine Learning Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile“?
Vergleichen Sie LightGBM auf einem großen Datensatz mit XGBoost, verstehen Sie blattweises und ebenenweises Baumwachstum und nutzen Sie die Unterstützung kategorialer Features. Du übst Machine Learning Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Machine Learning Academy zu starten?
Keine Vorkenntnisse erforderlich. Machine Learning Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Machine Learning Academy-Lektion Code schreiben und ausführen?
Ja. Jede Machine Learning Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Boosting-Intuition: Fehlerkorrektur in Sequenzen
- XGBoost: Regularisierung, Early Stopping und Feature-Wichtigkeit
- LightGBM: Blattweises Wachstum und Geschwindigkeitsvorteile
- Wichtige Hyperparameter: Learning Rate, n_estimators und max_depth