Ensemble Methods
In machine learning, you may have already mastered how to train a decision tree or a logistic regression model. The performance of a single model (which we call a base learner) sometimes reaches a bottleneck.
At this point, a powerful idea emerges:Ensemble Methods, which does not rely on creating an entirely new, more complex algorithm, but instead cleverly combines multiple relatively simple—or even mediocre—models to build a more powerful, more stable, and more accurate super-model.
In short, the core philosophy of ensemble learning is Two heads are better than one.。
Ensemble methods pool the collective wisdom of multiple models to compensate for the bias, variance, or random errors that a single model may have, thereby significantly improving overall predictive performance.
This article will systematically explain the principles, mainstream techniques, and engineering practices of ensemble methods.
The basic ideas and advantages of ensemble learning
Before diving into specific methods, we first need to understand why ensemble learning works and what benefits it brings.
Core idea: Reducing errors
The prediction error of a model can usually be decomposed into three parts:Bias、VarianceandIrreducible error。
- Bias: The systematic error caused by incorrect assumptions about the nature of the problem. High bias means the model underfits and cannot capture the fundamental relationships in the data.
- Variance: The sensitivity of the model to small fluctuations in the training data. High variance means the model overfits and pays too much attention to noise in the training data.
- Irreducible error: The inherent random noise in the data that cannot be eliminated by any model.
The core goal of ensemble methods is to combine multiple models in order toreduce the variance or bias of the overall model, thereby obtaining more robust (stable) and more accurate predictions.
Main advantages
- Improve accuracy: This is the most direct goal; ensemble models outperform the best single base learner in the vast majority of scenarios.
- Enhanced stability and robustness: Through averaging or voting, ensemble models are less sensitive to noisy data and outliers, reducing the risk of overfitting.
- Expanding the hypothesis space: Combining multiple models is equivalent to exploring a broader solution space, making it more likely to approach the optimal solution to the problem.
To understand more intuitively how ensemble methods work by combining multiple models, we can look at the following flowchart:

Detailed explanation of mainstream ensemble methods
According to how base learners are generated and combined, ensemble methods are mainly divided into three major categories:Bagging、Boosting and Stacking。
Bagging: The parallel approach, stability first
Bagging Its core idea is Bootstrap Aggregating。
- Bootstrap: From the original training set, performwith replacementrandom sampling to generate multiple different sub-training sets. Each subset may be the same size as the original set, but due to sampling with replacement, some samples are drawn repeatedly while others are never drawn.
- Parallel training: Using the same learning algorithm (usually a high-variance, low-bias model such as an unpruned decision tree), train a base learner independently on each sub-training set.
- Aggregating: For classification tasks, usevoting(majority rules) to decide the final class; for regression tasks, useAveraging Methodto compute the final value.
Representative algorithm: Random Forest Random Forest is an outstanding representative of the Bagging idea, and it goes a step further on this basis: when each decision tree performs node splitting, it not only randomly samples the data but alsorandomly selects a subset of featuresfor the optimal split. This "double randomness" further enhances the model's diversity and resistance to overfitting.
Example
Implementing Random Forest with Scikit-learn
from
sklearn.
ensemble
import
RandomForestClassifier
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
metrics
import
accuracy_score
Load data
iris
=
load_iris
(
)
X
,
y
=
iris.
data
,
iris.
target
Split into training and test sets
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
,
random_state
=
42
)
Create a random forest classifier
n_estimators: The number of trees in the forest, the number of base learners
max_depth: The maximum depth of the trees, controlling model complexity
random_state: The random seed, ensuring reproducible results
rf_clf
=
RandomForestClassifier
(
n_estimators
=
100
,
max_depth
=
5
,
random_state
=
42
)
Train the model
rf_clf.
fit
(
X_train
,
y_train
)
Predict and evaluate
y_pred
=
rf_clf.
predict
(
X_test
)
(
f
"Random Forest accuracy: {accuracy_score(y_test, y_pred):.4f}"
)
View the depth of a single tree (example)
(
f
"Depth of the first tree: {rf_clf.estimators_[0].get_depth()}"
)
Boosting: Sequential wisdom, focused on correcting errors
Boosting It adopts a completely different strategy.
- Sequential training: Base learners aresequentiallytrained, rather than in parallel.
- Focusing on errors: Each subsequent model pays more attention to thesamples misclassified by preceding models. This is usually achieved by adjusting the weights of training samples (giving higher weights to misclassified samples).
- Weighted combination: Combine all base learnersWeighted Sumto obtain the final model, with better-performing base learners given higher weights.
The core of Boosting is to continuously correct the errors of predecessors, elevating a group of "weak learners" (only slightly better than random guessing) into a powerful "strong learner."
Representative algorithms: AdaBoost and Gradient Boosting Decision Trees
- AdaBoost: One of the earliest Boosting algorithms. It forces subsequent models to focus on learning these "hard" samples by increasing the weights of misclassified samples.
- Gradient Boosting Decision Tree: Currently one of the most popular and powerful Boosting algorithms. Instead of adjusting sample weights, it treats the training process as angradient descentoptimization process. The goal of each new tree is to fit the error between the current model's predictions and the true labels, namely theresidual(negative gradient).
Example
Implementing a Gradient Boosting Classifier with Scikit-learn
from
sklearn.
ensemble
import
GradientBoostingClassifier
Create a gradient boosting classifier
n_estimators: The number of boosting stages (number of trees)
learning_rate: The learning rate, controlling how much each tree contributes to the final result (shrinkage coefficient)
max_depth: The maximum depth of each regression tree, usually small (3-5), representing a weak learner
gb_clf
=
GradientBoostingClassifier
(
n_estimators
=
100
,
learning_rate
=
0.1
,
max_depth
=
3
,
random_state
=
42
)
Train the model
gb_clf.
fit
(
X_train
,
y_train
)
Predict and evaluate
y_pred_gb
=
gb_clf.
predict
(
X_test
)
(
f
"Gradient Boosting Tree accuracy: {accuracy_score(y_test, y_pred_gb):.4f}"
)
View feature importance (ensemble methods can usually provide this)
(
"Feature importance:"
,
gb_clf.
feature_importances_
)
Output:
随机森林准确率: 1.0000
第一棵树的深度: 4
Stacking: Model stacking, a meta-learning strategy
Stacking is a more advanced ensemble technique that introduces the concept of a "meta-learner."
- Layer 1: Diverse base learners. UsingdistinctLearning algorithms (such as KNN, SVM, and decision trees) train multiple models on the original data.
- Generate new features: Use these first-layer models to make predictions on the training data (usually using cross-validation to avoid data leakage) and take their prediction results (class labels or probabilities) asnew features。
- Layer 2: Train the meta-learner. Taking these new features as input and the original labels as output, train a final model (such as logistic regression or linear regression). This meta-learner is responsible for learning how to best combine the outputs of the first-layer models.
Stacking has great potential, but it is computationally expensive and must be designed carefully to prevent overfitting.
Method comparison and engineering practice recommendations
After understanding the principles, how do you choose and apply these methods in real projects?
Comparison of the three major methods
| Feature | Bagging (e.g., Random Forest) | Boosting (e.g., GBDT, XGBoost) | Stacking |
|---|---|---|---|
| Core goal | Reduce variance, prevent overfitting | Reduce bias, improve predictive power | Optimize combination strategy |
| Training Method | Parallel, independent training | Sequential, depends on the previous round's results | Layered, base learners first then the meta-learner |
| Sample weights | Treated equally, bootstrap sampling | Dynamically adjusted, focused on errors | Usually equal |
| Base learner relationships | Mutually independent; diversity comes from data perturbation | Mutually dependent; jointly optimize the objective | Mutually independent; diversity comes from algorithm differences |
| Advantage | Stable, resistant to overfitting, easy to parallelize | Usually very high prediction accuracy | Theoretically can achieve the best performance |
| Disadvantages | Limited bias reduction, high computational resource consumption | Sensitive to noise, prone to overfitting, complex tuning | Very high computational cost, complex structure, prone to overfitting |
| Typical application | Random Forest, Extra-Trees | AdaBoost, GBDT, XGBoost, LightGBM, CatBoost | Common in machine learning competitions |
Engineering practice guide
Start with a baseline model: Don't use complex ensemble methods from the start. First establish a performance baseline with a simple model (such as logistic regression or a single decision tree).
Choose according to the problem:
- If your base model (such as a very deep decision tree)overfits severely (high variance), prioritize trying Bagging(Random Forest).
- If your base modelunderfits (high bias), or you are pursuing extremely high prediction accuracy, prioritize trying Boosting(such as XGBoost, LightGBM).
- inMachine learning competitionsor scenarios with extreme accuracy requirements, and when computational resources are sufficient, you can consider Stacking or Blending。
Leverage modern optimization libraries: In practice, directly use highly optimized libraries that implement state-of-the-art ensemble algorithms:
- Scikit-learn: provides
RandomForest,GradientBoostingand other excellent implementations, suitable for beginners and rapid prototyping. - XGBoost: Fast, accurate, and full-featured; a perennial winner in Kaggle competitions.
- LightGBM: Released by Microsoft, with faster training and lower memory consumption, especially suitable for large datasets.
- CatBoost: Released by Yandex, it handles categorical features well and performs well with default parameters.
Pay attention to tuning: Ensemble models have many hyperparameters. Key parameters to focus on include:
n_estimators: The number of base learners (more is better, but computational cost increases).learning_rate(Boosting): The learning rate, controlling the contribution of each step. It usually needs to be traded off withn_estimators(a small learning rate requires more trees).max_depth(Tree methods): The key to controlling model complexity and overfitting.- UseCross-validationandGrid search / random searchto tune parameters systematically.