LightGBM: Leaf-Wise Growth and Speed Advantages
Learners will benchmark LightGBM against XGBoost on a large dataset, understand leaf-wise vs level-wise tree growth, and use categorical feature support.
LightGBM: Leaf-Wise Growth and Speed Advantages is a free Machine Learning Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Machine Learning Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Frequently asked questions
Is the “LightGBM: Leaf-Wise Growth and Speed Advantages” lesson free?
Yes — the full text of “LightGBM: Leaf-Wise Growth and Speed Advantages” is free to read here on the web, and the Machine Learning Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Machine Learning Academy course, upgrade to CoddyKit PRO.
What will I learn in “LightGBM: Leaf-Wise Growth and Speed Advantages”?
Learners will benchmark LightGBM against XGBoost on a large dataset, understand leaf-wise vs level-wise tree growth, and use categorical feature support. You practise Machine Learning Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Machine Learning Academy?
No prior experience is required. Machine Learning Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “LightGBM: Leaf-Wise Growth and Speed Advantages” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Machine Learning Academy lesson?
Yes. Every Machine Learning Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Boosting Intuition: Sequential Error Correction
- XGBoost: Regularisation, Early Stopping, and Feature Importance
- LightGBM: Leaf-Wise Growth and Speed Advantages
- Key Hyperparameters: Learning Rate, n_estimators, and max_depth