Ensemble Learning
In the field of machine learning, ensemble learning is a technique that improves overall performance by combining the prediction results of multiple models.
The core idea of ensemble learning is captured by the proverb "Two heads are better than one" — that is, through the combination of multiple weak learners, a strong learner can be built.
The main goal of ensemble learning is to improve prediction accuracy and robustness by combining multiple models.
Common ensemble learning methods include:
- Bagging: Generate multiple training sets through bootstrap sampling, then train multiple models separately, and finally obtain the final result through voting or averaging.
- Boosting: Train multiple models iteratively, with each model trying to correct the errors of the previous one, and finally obtain the result through weighted voting.
- Stacking: Train several different models, then use the outputs of these models as new features, and train a meta-model for the final prediction.

1. Bagging(Bootstrap Aggregating)
Bagging aims to improve performance by reducing model variance and is suitable for high-variance models prone to overfitting. It achieves this through the following steps:
- Dataset Resampling: Perform multiple rounds of random sampling with replacement (bootstrap) on the training dataset, with each round producing a subset of the data.
- Train Multiple Models: Train a base learner on each subset (usually a model of the same type).
- Combine the Results: Combine the results of multiple base learners, usually through voting (for classification) or averaging (for regression).
Typical algorithms:
- Random Forest: Random forest is a classic implementation of Bagging; it builds multiple decision trees, each of which randomly selects features during training, thereby reducing the risk of overfitting.
Advantage:
- Can effectively reduce variance and improve model stability.
- Suitable for high-variance models, such as decision trees.
Disadvantages:
- The training process takes longer because multiple models need to be trained.
- The results are difficult to interpret because there is no single model.

2. Boosting
Boosting aims to improve performance by reducing model bias and is suitable for weak learners. The core idea of Boosting is to gradually adjust the weights of each model, emphasizing samples that were misclassified by the previous round. Boosting achieves this through the following steps:
- Sequential Training: Models are trained one after another, with each round of training adjusted according to the errors of the previous round.
- Weighted Voting: The final prediction is a weighted sum of the predictions of all weak learners, in which misclassified samples are assigned higher weights.
- Combine the Models: The weight of each model is determined by its performance during training.
Typical algorithms:
- AdaBoost(Adaptive Boosting): AdaBoost changes the weights of samples so that each subsequent classifier focuses more on the samples misclassified by the previous round.
- Gradient Boosting Trees (GBT): GBT gradually reduces bias by iteratively optimizing the objective function.
- XGBoost(Extreme Gradient Boosting): XGBoost is an efficient gradient boosting algorithm widely used in data science competitions, with strong performance and optimization.
- LightGBM(Light Gradient Boosting Machine): LightGBM is a framework based on gradient boosting trees; compared with XGBoost, it features faster training speed and lower memory usage.
Advantage:
- Suitable for models with high bias, effectively improving prediction accuracy.
- Strong performance, excelling in many practical applications.
Disadvantages:
- Relatively sensitive to noisy data, easily leading to overfitting.
- The training process is relatively slow, especially when the data volume is large.

3. Stacking(Stacked Generalization)
Stacking is a method that improves overall prediction accuracy by training different kinds of models and combining their predictions. Its core idea is:
- First Layer (Base Learners): Train multiple base learners of different types (e.g., decision trees, SVM, KNN, etc.) to make predictions on the data.
- Second Layer (Meta-Learner): Use the prediction results of the first-layer learners as input to train a meta-learner (usually logistic regression, linear regression, etc.) to make the final prediction.
Advantage:
- Can use different types of base learners to capture different patterns in the data.
- Theoretically, it can combine the advantages of multiple models to achieve stronger predictive power.
Disadvantages:
- The training process is complex: multiple models need to be trained, and the way they are combined must also be carefully designed.
- More complex than other ensemble methods such as Bagging and Boosting, and prone to overfitting.

Example Demonstration
Example
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 the dataset
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
rf
=
RandomForestClassifier
(
n_estimators
=
100
,
random_state
=
42
)
Train the model
rf.
fit
(
X_train
,
y_train
)
Predict
y_pred
=
rf.
predict
(
X_test
)
Compute accuracy
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
(
f
"Random forest accuracy: {accuracy:.2f}"
)
The output is as follows:
随机森林的准确率: 1.00
Code explanation:
- Load the dataset: We use the
load_iris()function to load the classic Iris dataset. - Split into training and test sets: When using
train_test_split()function splits the dataset into a training set and a test set. - Create a random forest classifier: When using
RandomForestClassifierclass to create a random forest classifier,n_estimators=100indicating the use of 100 decision trees. - Train the model: When using
fit()Method to train the model. - Predict: When using
predict()Method to make predictions on the test set. - Compute accuracy: When using
accuracy_score()Function to compute the model's accuracy.
Boosting:AdaBoost
**Algorithm principle: **The core idea of Boosting is to train multiple models iteratively, with each model trying to correct the errors of the previous one. AdaBoost (Adaptive Boosting) is the most classic type of Boosting algorithm.
Example
from
sklearn.
ensemble
import
AdaBoostClassifier
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
metrics
import
accuracy_score
from
sklearn.
tree
import
DecisionTreeClassifier
Load the dataset
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
)
Use the default weak learner (decision tree), and specify the use of the SAMME algorithm.
ada
=
AdaBoostClassifier
(
DecisionTreeClassifier
(
max_depth
=
1
)
,
n_estimators
=
50
,
random_state
=
42
,
algorithm
=
'SAMME'
)
Train the model
ada.
fit
(
X_train
,
y_train
)
Predict
y_pred
=
ada.
predict
(
X_test
)
Compute accuracy
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
(
f
"AdaBoost accuracy: {accuracy:.2f}"
)
The output is as follows:
AdaBoost的准确率: 1.00
Code Explanation:
- Load the dataset: When using
load_iris()Function to load the Iris dataset, containing feature dataXand label data.y。 - Split into training and test sets: When using
train_test_split()Function to split the dataset into a training set and a test set, with the test set accounting for 30% and the training set 70%. - Create a decision tree classifier: When using
DecisionTreeClassifier(max_depth=1)Create a decision tree classifier with depth 1 as the base learner for AdaBoost. - Create an AdaBoost classifier.: When using
AdaBoostClassifier()The class creates an AdaBoost classifier,n_estimators=50indicating the use of 50 weak learners,algorithm='SAMME'specifying the use of the SAMME algorithm. - Train the model: When using
fit()Method to train the AdaBoost model on the training data. - Predict: When using
predict()Method to make predictions on the test set, generating predicted labels.y_pred。 - Compute accuracy: When using
accuracy_score()Function to compute and output the model's prediction accuracy.
Stacking: Model Stacking
**Algorithm principle:** The core idea of Stacking is to train multiple different models, then use their outputs as new features, and train a meta-model (Meta-Model) to make the final prediction.
Example
from
sklearn.
ensemble
import
StackingClassifier
from
sklearn.
linear_model
import
LogisticRegression
from
sklearn.
tree
import
DecisionTreeClassifier
from
sklearn.
svm
import
SVC
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
metrics
import
accuracy_score
Load the dataset
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
)
Define the base learners.
estimators
=
[
(
'dt'
,
DecisionTreeClassifier
(
max_depth
=
1
)
)
,
(
'svc'
,
SVC
(
kernel
=
'linear'
,
probability
=
True
)
)
]
Create a Stacking classifier.
stacking
=
StackingClassifier
(
estimators
=
estimators
,
final_estimator
=
LogisticRegression
(
)
)
Train the model
stacking.
fit
(
X_train
,
y_train
)
Predict
y_pred
=
stacking.
predict
(
X_test
)
Compute accuracy
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
(
f
"Stacking accuracy: {accuracy:.2f}"
)
The output is as follows:
tacking的准确率: 1.00
Code Explanation:
- Load the dataset: Also use
load_iris()Function to load the Iris dataset. - Split into training and test sets: When using
train_test_split()function splits the dataset into a training set and a test set. - Define the base learners.: When using
DecisionTreeClassifierandSVCas the base learners. - Create a Stacking classifier.: When using
StackingClassifierThe class creates a Stacking classifier,final_estimator=LogisticRegression()indicating the use of logistic regression as the meta-model. - Train the model: When using
fit()Method to train the model. - Predict: When using
predict()Method to make predictions on the test set. - Compute accuracy: When using
accuracy_score()Function to compute the model's accuracy.