1. Ensemble Learning: Basic concepts of ensemble learning
The core idea of ensemble learning is:
combines the prediction results of multiple base models (Base Learners) to obtain more robust or accurate predictions than a single model.
For example, a single tree Decision Tree is prone to overfitting, while combining multiple trees can often improve generalization.
Main integration methods
| method | core idea | representative algorithm |
|---|---|---|
| Bagging | Train multiple models in parallel and aggregate predictions | Bagging、Random Forest |
| Boosting | Train models sequentially to gradually improve predictions | AdaBoost、Gradient Boosting |
| Voting | Vote or average predictions from different models | VotingClassifier |
| Stacking | Using another model to combine predictions from a base model | StackingClassifier |
This article mainly discusses Bagging and Boosting.
The difference between Bagging and Boosting
| Features | Bagging | Boosting |
|---|---|---|
| Training method | Base models can often be trained in parallel | Base models are usually trained sequentially |
| Main mechanism | Resampling, model averaging | Optimize losses or sample weights step by step |
| Typical effects | reduce variance | Improve fit, control bias and variance |
| Typical algorithm | Random Forest | GBDT、XGBoost、LightGBM |
2. Bagging:Bootstrap Aggregating
Bagging is the abbreviation of Bootstrap Aggregating.
Its basic process:
- Random sampling with replacement (Bootstrap) is performed from the original training set.
- Train multiple base models based on different sample subsets.
- Aggregate predictions from multiple models.
Classification problems typically use voting or averaging predicted probabilities; regression problems typically use averaging of predicted values.
Bootstrap Sampling
Assume the original data is:
[A, B, C, D, E]
Sampling with replacement may produce:
Sample 1: [A, B, B, D, E]
Sample 2: [A, A, C, D, D]
Sample 3: [B, C, C, D, E]
Because the base model receives different samples, there is some variation in the predictions.
Averaging multiple models can reduce some of the random errors.
scikit-learn implementation
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
model = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=100,
max_samples=0.8,
bootstrap=True,
random_state=42,
n_jobs=-1,
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Main parameters:
| parameters | function |
|---|---|
estimator | base model |
n_estimators | Number of basic models |
max_samples | The number or proportion of samples used by each model |
max_features | The number or proportion of features used by each model |
bootstrap | Is there any replacement sampling? |
n_jobs | Number of parallel tasks |
Bagging does not require that the underlying model be Decision Tree, but decision trees are a common choice.
Out-of-Bag(OOB)
After Bootstrap sampling, each base model usually has some original training samples that are not sampled.
These samples are called Out-of-Bag Samples.
You can use them to evaluate models:
model = BaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=100,
bootstrap=True,
oob_score=True,
random_state=42,
)
model.fit(X_train, y_train)
print(model.oob_score_)
OOB can provide additional estimates of generalization performance, but cannot completely replace an independent test set.
3. Random Forest: Random Forest
Random Forest is an important application of Bagging idea on decision trees.
Compared with the ordinary Bagging Decision Trees, a key feature of the Random Forest is:
When each node is split, usually only a randomly selected part of the features are considered.
This can reduce the correlation between different decision trees, making model averaging more efficient.
Random Forest’s workflow
- Perform Bootstrap Sampling on the training samples.
- Train a tree Decision Tree for each sample subset.
- Only some candidate features are considered during each node partitioning.
- Aggregate the predictions of all decision trees.
Category:
Return:
Among them, represents the th decision tree.
RandomForestClassifier
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(
n_estimators=200,
max_depth=10,
min_samples_leaf=2,
max_features="sqrt",
random_state=42,
n_jobs=-1,
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)
Return version:
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(
n_estimators=200,
max_depth=10,
random_state=42,
)
Important hyperparameters
| parameters | function |
|---|---|
n_estimators | number of trees |
max_depth | maximum tree depth |
min_samples_split | Minimum number of samples for node splitting |
min_samples_leaf | Minimum number of samples for leaf nodes |
max_features | The number of features considered for each split |
bootstrap | Whether to use Bootstrap |
class_weight | Category weights for classification tasks |
Overfitting control
- Add
n_estimators: Generally improves stability, but increases computational and memory costs. - Limit
max_depth: Prevents a single tree from being too deep. - Add
min_samples_leaf: Make leaf nodes smoother. - Adjust
max_features: Change the correlation between trees and the prediction ability of a single tree.
One characteristic of Random Forest is that increasing the number of trees usually does not directly cause significant overfitting like deepening a tree alone, but the benefits gradually decrease.
Advantages and Disadvantages of Random Forest
Advantages:
- Usually suitable for tabular data.
- Can handle nonlinear relationships and feature interactions.
- Feature normalization is usually not required.
- More stable than a single decision tree.
- Parameter tuning is relatively simple.
Limitations:
- Model size may be larger.
- Inference requires going through multiple trees.
- Less interpretable than a single decision tree.
- Limited ability to extrapolate to continuous targets outside the training range.
4. Boosting: Improvement method
Boosting is also a method of combining multiple base models, but unlike Bagging, it usually builds the models sequentially.
Core idea:
follow-up models focus on improving the unresolved problems of existing models.
However, different Boosting algorithms improve in different ways.
AdaBoost
AdaBoost (Adaptive Boosting) is the classic Boosting algorithm.
Among common classification forms:
- Initialize training sample weights.
- Train a weak classifier.
- Adjust sample weights based on classification results.
- Pay more attention to previously misclassified samples.
- Combining multiple weak classifiers.
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
model = AdaBoostClassifier(
estimator=DecisionTreeClassifier(max_depth=1),
n_estimators=100,
learning_rate=0.1,
random_state=42,
)
model.fit(X_train, y_train)
Here Decision Tree with depth 1 is often called Decision Stump.
AdaBoost may be sensitive to outliers and incorrect labels because some incorrect samples will continue to receive high attention.
In modern structured data tasks, Gradient Boosting, XGBoost, and LightGBM tend to be more commonly used as focus candidate models.
5. Gradient Boosting: Gradient Boosting
Gradient Boosting extends Boosting to a differentiable loss function to reduce the overall prediction loss by training new models incrementally.
In actual table tasks, Decision Tree is usually used as the base learner, forming Gradient Boosted Decision Trees (GBDT).
core idea
Assume that the current prediction model is:
In round , a new model is trained and then updated:
Among them:
- : Newly trained base model.
- :Learning Rate。
- : Integrated model after round .
More generally, the goal of training a new model is to fit the negative gradient (Pseudo-residual) of the current loss function with respect to the predicted value.
Intuitive example in regression
When using Squared Error, the negative gradient is proportional to the current residual.
Assumptions:
Actual: 100
Initial Prediction: 80
Residual: 20
The second tree learns how to correct the current prediction error.
Subsequent trees continue to learn the remaining errors, making the overall prediction progressively better.
Note that other loss functions (such as classification Log Loss) are not equivalent to simply fitting .
scikit-learn implementation
from sklearn.ensemble import GradientBoostingClassifier
model = GradientBoostingClassifier(
n_estimators=200,
learning_rate=0.05,
max_depth=3,
subsample=0.8,
random_state=42,
)
model.fit(X_train, y_train)
Return version:
from sklearn.ensemble import GradientBoostingRegressor
Important hyperparameters
| parameters | function |
|---|---|
n_estimators | Boosting number of iteration rounds |
learning_rate | The scaling factor contributed by the model in each round |
max_depth | The maximum depth of the underlying decision tree |
subsample | The proportion of samples used in each round of training |
min_samples_leaf | Minimum number of samples for leaf nodes |
Learning Rate and the number of iterations
There are usually certain trade-offs:
- Smaller Learning Rate: Each round of updates is more cautious and often requires more trees.
- Larger Learning Rate: Convergence may be faster, but more prone to overfitting or instability.
Smaller Learning Rate does not automatically guarantee better results and needs to be adjusted together with the number of trees.
6. Histogram-based Gradient Boosting
Traditional Gradient Boosting When the amount of data is large, it may be expensive to find the split points of continuous features.
Histogram-based Gradient Boosting first discretizes the continuous features into a limited number of Bins, and then finds the splitting points based on histogram statistics.
Continuous Feature Values
↓
Histogram Bins
↓
Split Evaluation
↓
Decision Tree
This method can reduce the computational cost of finding split points.
scikit-learn implementation
from sklearn.ensemble import HistGradientBoostingClassifier
model = HistGradientBoostingClassifier(
max_iter=200,
learning_rate=0.05,
max_leaf_nodes=31,
l2_regularization=1.0,
random_state=42,
)
model.fit(X_train, y_train)
Return version:
from sklearn.ensemble import HistGradientBoostingRegressor
Compared with the traditional GradientBoostingClassifier, the Histogram-based implementation is generally more suitable for larger tabular data, and supports missing values and native category feature processing under certain conditions.
It is also an important basis for understanding modern GBDT implementations such as XGBoost and LightGBM.
7. XGBoost:Extreme Gradient Boosting
XGBoost is a highly optimized Gradient Boosting framework, especially commonly used for classification and regression of structured tabular data.
Installation:
pip install xgboost
Core features
XGBoost builds on GBDT and provides:
- Optimize the objective using first-order gradient and second-order derivative information.
- Tree complexity regularization.
- Row sampling and column sampling.
- Efficient tree splitting algorithm.
- Missing value handling.
- Early Stopping。
- Multi-threading and partial hardware acceleration capabilities.
Second-order optimization ideas
XGBoost often uses a second-order Taylor approximation of the loss function to optimize the new trees added in each round.
The goals can be summarized as:
Among them:
- : Prediction loss.
- : Regularization of tree complexity.
Through the gradient (Gradient) and Hessian (second derivative), XGBoost can more effectively evaluate the objective function improvement of candidate splits.
XGBClassifier
from xgboost import XGBClassifier
model = XGBClassifier(
n_estimators=300,
max_depth=5,
learning_rate=0.05,
subsample=0.8,
colsample_bytree=0.8,
reg_lambda=1.0,
tree_method="hist",
eval_metric="logloss",
random_state=42,
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)
Return:
from xgboost import XGBRegressor
Important hyperparameters
| parameters | function |
|---|---|
n_estimators | Boosting number of iteration rounds |
max_depth | maximum tree depth |
learning_rate | Learning rate per round |
subsample | Row sampling ratio per round |
colsample_bytree | The feature scale used by each tree |
min_child_weight | Minimum Hessian weight sum required to limit child nodes |
gamma | Minimum Loss Reduction required for node splitting |
reg_alpha | L1 regularization |
reg_lambda | L2 regularization |
tree_method | tree construction method |
min_child_weight here is not a simple minimum number of samples, but related to the second-order derivative statistics of the loss function.
Early Stopping
If the validation set indicators do not improve for many consecutive rounds, you can stop training early:
model = XGBClassifier(
n_estimators=1000,
learning_rate=0.05,
max_depth=5,
tree_method="hist",
eval_metric="logloss",
early_stopping_rounds=30,
random_state=42,
)
model.fit(
X_train,
y_train,
eval_set=[(X_val, y_val)],
verbose=False,
)
print(model.best_iteration)
A separate Validation Set should be used to control Early Stopping, and the final Test Set cannot be used to repeatedly select the number of training rounds.
8. LightGBM:Light Gradient Boosting Machine
LightGBM is also an efficient GBDT framework, focusing on optimizing training efficiency and memory usage.
Installation:
pip install lightgbm
Core features
The key technologies of LightGBM include:
- Histogram-based Tree Learning。
- Leaf-wise Tree Growth。
- Gradient-based One-Side Sampling(GOSS)。
- Exclusive Feature Bundling(EFB)。
- Category feature support.
- Multi-threaded training with Early Stopping.
Note: GOSS and EFB do not mean that they will automatically produce the same performance gains on all configurations and data.
Leaf-wise vs Level-wise
This is an important difference between LightGBM and the common Level-wise tree growth strategy.
Level-wise
Usually the tree is expanded by layers:
Root
/ \
A B
/ \ / \
Leaf-wise
Prioritize expansion of leaf nodes that can bring the largest Loss Reduction:
Root
/ \
A B
/ \
C D
/ \
E F
Leaf-wise can achieve higher loss improvement under the same limit of the number of leaf nodes, but may also generate deeper, unbalanced trees, increasing the risk of overfitting.
LGBMClassifier
from lightgbm import LGBMClassifier
model = LGBMClassifier(
n_estimators=300,
learning_rate=0.05,
num_leaves=31,
max_depth=-1,
min_child_samples=20,
subsample=0.8,
colsample_bytree=0.8,
random_state=42,
verbosity=-1,
)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
Return version:
from lightgbm import LGBMRegressor
Important hyperparameters
| parameters | function |
|---|---|
n_estimators | Boosting round number |
learning_rate | learning rate |
num_leaves | Maximum number of leaf nodes per tree |
max_depth | Maximum tree depth, -1 means this limit is not set |
min_child_samples | Minimum number of samples for leaf nodes |
min_split_gain | Node split minimum gain |
subsample | row sampling ratio |
subsample_freq | Line sampling frequency |
colsample_bytree | Feature sampling ratio |
reg_alpha / reg_lambda | L1 / L2 regularization |
Note: In LightGBM, only setting subsample to less than 1 usually requires also configuring non-zero subsample_freq to enable corresponding Bagging line sampling.
Early Stopping
import lightgbm as lgb
model = LGBMClassifier(
n_estimators=1000,
learning_rate=0.05,
verbosity=-1,
)
model.fit(
X_train,
y_train,
eval_set=[(X_val, y_val)],
eval_metric="auc",
callbacks=[
lgb.early_stopping(stopping_rounds=30),
lgb.log_evaluation(period=0),
],
)
print(model.best_iteration_)
Category features
LightGBM can natively handle Categorical Features appropriately represented.
For example Pandas's category dtype:
df["city"] = df["city"].astype("category")
In this way, under the appropriate configuration, there is no need to always use One-Hot Encoding.
However, the processing of native category features depends on the data type and model API, and it cannot be simply understood that all string fields can be input directly.
9. The difference between Random Forest, XGBoost and LightGBM
| Features | Random Forest | XGBoost | LightGBM |
|---|---|---|---|
| Basic idea | Bagging | Gradient Boosting | Gradient Boosting |
| tree relationship | relatively independent | sequential training | sequential training |
| Common tree growing strategies | Ordinary decision tree | Strategies such as Depth-wise | Main Leaf-wise |
| Feature normalization | Usually not required | Usually not required | Usually not required |
| Missing value support | Depends on implementation and version | support | support |
| Parameter adjustment difficulty | relatively low | higher | higher |
| Overfitting control | Tree depth, leaf nodes, feature sampling | Regularization, sampling, Early Stopping | Leaf node control, sampling, Early Stopping |
| Typical uses | Robust tabular data baseline | High performance tabular modeling | Large-scale and efficient tabular modeling |
cannot simply think that LightGBM must be faster than XGBoost, or XGBoost must be more accurate than Random Forest.
Actual results are affected by data size, feature type, hyperparameters, hardware, and implementation version.
How to choose?
Random Forest
Suitable for:
- Hope to establish stable Baseline quickly.
- Don’t want to invest too much in hyperparameter tuning costs.
- The data has non-linear relationships and complex feature interactions.
XGBoost
Suitable for:
- Strong tabular data prediction performance is required.
- Want fine control over regularization and model complexity.
- You can invest more in parameter adjustment costs.
LightGBM
Suitable for:
- The data size is large.
- Hope to improve training efficiency.
- Contains more categorical features.
- It is necessary to flexibly control the leaf node structure of the tree.
10. Feature Importance: Feature importance
Tree models typically output Feature Importance.
model.feature_importances_
However, under different algorithms and configurations, the importance may be based on:
- Number of splits (Split Count).
- Reduced impurity (Impurity Reduction).
- Loss improvement (Gain).
- Other model internal statistics.
Therefore, of different models of feature_importances_ may not necessarily be directly comparable to.
Permutation Importance
A more general approach is to perturb a feature and observe how much the model score drops.
from sklearn.inspection import permutation_importance
result = permutation_importance(
model,
X_test,
y_test,
scoring="roc_auc",
n_repeats=10,
random_state=42,
)
If the model score drops significantly after disrupting a certain feature, it means that the model is more dependent on this feature on the current data.
But be careful:
- Highly related features may substitute for each other.
- Importance is not a causal influence.
- Test data should not be reused for model design.
If you need a more fine-grained explanation, you can learn more about SHAP, but you don't have to start with the basics of ensemble learning.
11. Model tuning participates in overfitting control
The parameter adjustment focus of Bagging and Boosting is slightly different.
Random Forest
Focus on:
n_estimators。max_depth。min_samples_leaf。max_features。
Gradient Boosting / XGBoost / LightGBM
Focus on:
learning_rate。n_estimators。- Tree depth or number of leaf nodes.
- Row sampling and column sampling.
- Regularization.
- Early Stopping。
Parameter adjustment principles
- Build Baseline using a simple model.
- Select Metrics that matches your business goals.
- Cross-validation is performed within the training data.
- Adjust hyperparameters via Validation Set and Early Stopping.
- Final evaluation done on standalone Test Set.
For example, classification is commonly used:
from sklearn.metrics import (
accuracy_score,
f1_score,
roc_auc_score,
log_loss,
)
Return to common use:
from sklearn.metrics import (
mean_absolute_error,
root_mean_squared_error,
r2_score,
)
For the problem of class imbalance, you should not only look at Accuracy, but should combine indicators such as Recall, Precision, F1, and PR-AUC.
12. Complete example: Comparing different ensemble models
The following uses the Breast Cancer data set of scikit-learn to compare the classification performance of Random Forest, Gradient Boosting, XGBoost and LightGBM.
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
accuracy_score,
f1_score,
roc_auc_score,
)
from sklearn.ensemble import (
RandomForestClassifier,
HistGradientBoostingClassifier,
)
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
# 1. Load data
dataset = load_breast_cancer()
X = dataset.data
y = dataset.target
# 2. Split training set and test set
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=42,
)
# 3. Define model
models = {
"Random Forest": RandomForestClassifier(
n_estimators=200,
random_state=42,
n_jobs=-1,
),
"HistGradientBoosting": HistGradientBoostingClassifier(
max_iter=200,
learning_rate=0.05,
random_state=42,
),
"XGBoost": XGBClassifier(
n_estimators=200,
learning_rate=0.05,
max_depth=4,
tree_method="hist",
random_state=42,
),
"LightGBM": LGBMClassifier(
n_estimators=200,
learning_rate=0.05,
num_leaves=15,
random_state=42,
verbosity=-1,
),
}
# 4. training and evaluation
results = []
for name, model in models.items():
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_proba = model.predict_proba(X_test)[:, 1]
results.append({
"Model": name,
"Accuracy": accuracy_score(y_test, y_pred),
"F1": f1_score(y_test, y_pred),
"ROC-AUC": roc_auc_score(y_test, y_proba),
})
# 5. Compare results
results_df = pd.DataFrame(results)
print(results_df.sort_values("ROC-AUC", ascending=False))
This code shows the unified evaluation interface, not a strict model performance benchmark.
In real tasks, parameters should be adjusted through cross-validation or independent validation sets. If necessary, the results of multiple runs should be compared, and then an independent test should be conducted on the final model.
13. Other integration methods: Voting and Stacking
In addition to Bagging and Boosting, there are two more common methods worth knowing about.
Voting
Combine the results of multiple different classifiers.
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
model = VotingClassifier(
estimators=[
("lr", LogisticRegression(max_iter=1000)),
("tree", DecisionTreeClassifier()),
],
voting="soft",
)
hard: Vote based on category.soft: Select the category after averaging the predicted probabilities.
Soft Voting usually requires the underlying classifier to support predict_proba(), and the probability quality affects the results.
Stacking
Use the predictions of multiple base models as new features to retrain Meta-model.
Original Features
↓
┌─────┼─────┐
Model A Model B Model C
└─────┼─────┘
↓
Out-of-fold Predictions
↓
Meta-model
↓
Final Prediction
scikit-learn offers:
from sklearn.ensemble import StackingClassifier
The key to Stacking is to avoid directly using the overfitting predictions of the base model on its own training samples to train Meta-model, usually Out-of-Fold Predictions.
For general data analysis and traditional machine learning tasks, first master Random Forest and Gradient Boosting, and then understand Voting and Stacking.
Summary
| Knowledge points | importance |
|---|---|
| Ensemble Learning | core |
| Bagging / Bootstrap | core |
| Random Forest | core |
| Random Feature Selection | core |
| Out-of-Bag Evaluation | important |
| Boosting / AdaBoost | important |
| Gradient Boosting / GBDT | core |
| Gradient / Learning Rate | core |
| Histogram-based GBDT | important |
| XGBoost / Regularization | core |
| LightGBM / Leaf-wise | core |
| Early Stopping | core |
| Feature Importance | important |
| Voting / Stacking | on demand |
The five most important concepts of ensemble learning:
- Bagging: Reduce prediction variance and improve stability through Bootstrap Sampling and model aggregation.
- Random Forest: Introduce feature randomness on the basis of Bagging Decision Trees to reduce the correlation between trees.
- Boosting: Build models sequentially and gradually improve the predictions of existing integrated models.
- Gradient Boosting: Use the gradient information of the loss function to train a new model and optimize the overall goal round by round.
- XGBoost / LightGBM: Enhance the utility of GBDT through mechanisms such as efficient tree building, regularization, sampling and Early Stopping.