Machine Learning from Scratch – Day 18: Understanding LightGBM and CatBoost
Understanding LightGBM and CatBoost
Series: Machine Learning From Scratch (18 articles)
- …
- 18Machine Learning from Scratch – Day 18: Understanding LightGBM and CatBoost This article
In our previous articles, we explored Gradient Boosting and XGBoost.
We learned how multiple decision trees can work together sequentially to improve predictions.
But XGBoost isn't the only powerful gradient boosting framework.
Today, we'll explore two more popular algorithms:
- LightGBM (Light Gradient Boosting Machine)
- CatBoost (Categorical Boosting)
Both are designed to make gradient boosting more efficient and effective, but they approach certain challenges differently.
Let's understand them from scratch!
1. Why Do We Need LightGBM and CatBoost?
Imagine an e-commerce company with millions of customer records.
Its dataset contains:
- Customer age
- Purchase history
- Product category
- Location
- Payment method
- Total spending
- Customer membership type
Training a powerful machine learning model on this dataset can be challenging.
Some common problems include:
- Large datasets require significant computational resources.
- Categorical features need appropriate encoding in many algorithms.
- Training time can become expensive.
- Complex datasets require careful model tuning.
This is where LightGBM and CatBoost become useful.
Both are gradient boosting frameworks that use decision trees, but they introduce different techniques to improve training and prediction.
2. What is LightGBM?
LightGBM stands for Light Gradient Boosting Machine.
It is a gradient boosting framework developed by Microsoft.
Its main goal is to train gradient boosting models efficiently, particularly on large and high-dimensional datasets.
One of its important characteristics is its tree-growing strategy.
Understanding Leaf-Wise Tree Growth
Traditional tree-building approaches often grow trees level by level.
LightGBM generally uses a leaf-wise strategy.
Instead of expanding every node at the same depth, it selects the leaf that provides the greatest improvement in the objective function and splits that leaf.
Let's understand the difference.
Level-Wise Growth
- Splits nodes level by level.
- Produces a more balanced tree.
- Can be easier to control.
Leaf-Wise Growth
- Selects the leaf with the highest potential gain.
- Can reduce loss efficiently.
- May create deeper and less balanced trees.
This strategy can improve predictive performance, but it can also increase overfitting risk, especially with smaller datasets.
Parameters such as
max_depth and num_leaves help control tree complexity.Important Features of LightGBM
1. Histogram-Based Learning
LightGBM groups continuous feature values into discrete bins.
Instead of evaluating every possible split using all individual values, it evaluates candidate splits using these bins.
This can reduce memory usage and improve training speed.
2. Leaf-Wise Growth
It selects the leaf that provides the greatest improvement rather than expanding all leaves equally.
3. Gradient-Based One-Side Sampling (GOSS)
GOSS prioritizes training examples with larger gradient magnitudes while sampling some examples with smaller gradients.
The idea is to retain more information from examples where the model is making larger errors.
4. Exclusive Feature Bundling (EFB)
EFB combines certain mutually exclusive sparse features to reduce the effective number of features.
This can be particularly useful for high-dimensional sparse datasets.
3. What is CatBoost?
CatBoost stands for Categorical Boosting.
It is a gradient boosting library developed by Yandex.
Its major strength is handling categorical features effectively.
What are categorical features?
They are variables that represent categories rather than continuous numerical measurements.
For example:
Customer | Age | City | Membership |
|---|---|---|---|
A | 22 | Hyderabad | Gold |
B | 30 | Chennai | Silver |
C | 25 | Bengaluru | Gold |
D | 35 | Mumbai | Bronze |
Here,
City and Membership are categorical features.Many machine learning algorithms require categorical values to be converted into numerical representations.
Common techniques include:
- Label Encoding
- One-Hot Encoding
- Target Encoding
CatBoost provides native support for categorical features, reducing the need for manual encoding in many cases.
Important Features of CatBoost
1. Categorical Feature Handling
CatBoost can process categorical features directly when they are correctly identified.
It uses techniques such as ordered target statistics to create useful numerical representations.
2. Ordered Boosting
Traditional boosting can suffer from prediction shift caused by certain forms of target leakage during training.
CatBoost introduces ordered boosting techniques designed to reduce this problem.
3. Symmetric Trees
CatBoost commonly uses symmetric, or oblivious, trees.
At each depth, the same splitting condition is applied across all nodes at that level.
This produces a structured tree architecture that can make prediction efficient.
4. Reduced Preprocessing
Because CatBoost handles categorical features internally, it can simplify preprocessing pipelines.
However, missing-value handling, data cleaning and correct feature identification are still important.
4. LightGBM vs CatBoost vs XGBoost
Now let's compare the three gradient boosting frameworks.
Feature | XGBoost | LightGBM | CatBoost |
|---|---|---|---|
Main strength | Optimization and regularization | Efficient training | Categorical feature handling |
Tree growth | Typically level-wise | Leaf-wise | Commonly symmetric trees |
Categorical features | Requires appropriate encoding or supported categorical handling | Supports categorical features | Native categorical handling |
Large datasets | Efficient | Often particularly efficient | Can also handle large datasets |
Overfitting control | Regularization and tree constraints | Tree constraints and regularization | Ordered techniques and regularization |
There is no universally best algorithm.
For example:
- LightGBM can be a strong choice for large datasets.
- CatBoost can be convenient when datasets contain many categorical features.
- XGBoost offers extensive optimization and tuning options.
The best model should be selected through validation and experimentation.
5. Implementing LightGBM Using Python
Let's start with LightGBM.
Step 1: Install the libraries
pip install lightgbm catboost scikit-learnStep 2: Import the required libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom lightgbm import LGBMClassifierStep 3: Load the dataset
We'll use the Iris dataset again to maintain consistency with our previous implementations.
iris = load_iris()X = iris.datay = iris.targetStep 4: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)Step 5: Create the model
model = LGBMClassifier( n_estimators=100, learning_rate=0.05, max_depth=5, num_leaves=15, verbosity=-1, random_state=42)Step 6: Train the model
model.fit(X_train, y_train)Step 7: Make predictions
y_pred = model.predict(X_test)Step 8: Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))We have now trained a LightGBM classification model.
6. Implementing CatBoost Using Python
Now let's implement CatBoost.
Step 1: Import the libraries
from catboost import CatBoostClassifierfrom sklearn.metrics import accuracy_scoreWe'll reuse the Iris dataset and train/test split created earlier.
Step 2: Create the model
model = CatBoostClassifier( iterations=100, learning_rate=0.05, depth=5, loss_function="MultiClass", verbose=False, random_seed=42)Step 3: Train the model
model.fit(X_train, y_train)Step 4: Make predictions
y_pred = model.predict(X_test).ravel()Step 5: Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))That's it!
We have successfully implemented CatBoost using Python.
Important observation: Iris contains numerical features, so this example demonstrates basic CatBoost classification rather than its main categorical-feature advantage.
To experience that advantage, try a dataset containing features such as city, product category or payment method, and pass their column indices through CatBoost's
cat_features parameter.7. Advantages and Limitations
LightGBM
Advantages
- Efficient training on many large datasets.
- Histogram-based learning can reduce memory usage.
- Leaf-wise growth can improve predictive performance.
- Supports categorical features.
- Useful for high-dimensional datasets.
Limitations
- Leaf-wise growth can overfit if not controlled.
- Requires careful tuning of
num_leavesand tree depth.
- May be less convenient for very small datasets in some situations.
CatBoost
Advantages
- Handles categorical features effectively.
- Reduces the need for manual categorical encoding.
- Uses ordered boosting techniques.
- Supports classification and regression.
- Provides useful feature importance information.
Limitations
- Training can be slower than some alternatives depending on the dataset and configuration.
- Has several hyperparameters to understand.
- Can require more computational resources for certain workloads.
8. Real-World Applications
These frameworks are used in several industries.
LightGBM
- Financial risk prediction
- Customer churn analysis
- Fraud detection
- Sales forecasting
- Large-scale recommendation-related tasks
CatBoost
- Customer purchase prediction
- Credit scoring
- Marketing campaign prediction
- Insurance risk assessment
- Customer segmentation-related prediction tasks
Both are especially useful when working with structured or tabular datasets.
9. What Should You Remember?
Let's summarize today's learning:
- LightGBM and CatBoost are gradient boosting frameworks.
- LightGBM uses histogram-based learning and leaf-wise tree growth.
- LightGBM also uses techniques such as GOSS and EFB.
- CatBoost is designed to handle categorical features effectively.
- CatBoost uses ordered boosting and commonly symmetric trees.
- Both support classification and regression.
- Model selection should depend on the dataset and validation performance.
Key takeaway: XGBoost, LightGBM and CatBoost all build on gradient boosting, but their different optimization strategies make them useful for different machine learning problems.
What's Next? Day 19
We've now explored several popular machine learning algorithms.
But how do we actually know whether a model is performing well?
Is accuracy enough to judge a machine learning model?
In Day 19, we'll explore Model Evaluation Metrics:
- Accuracy
- Precision
- Recall
- F1-score
- Confusion Matrix
- ROC Curve and AUC
Understanding these metrics is essential because a model with high accuracy isn't necessarily a good model.
Series: Machine Learning From Scratch (18 articles)
- …
- 18Machine Learning from Scratch – Day 18: Understanding LightGBM and CatBoost This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article