Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ensemble Methods

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。

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

  1. Improve accuracy: This is the most direct goal; ensemble models outperform the best single base learner in the vast majority of scenarios.
  2. Enhanced stability and robustness: Through averaging or voting, ensemble models are less sensitive to noisy data and outliers, reducing the risk of overfitting.
  3. 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。

  1. 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.
  2. 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.
  3. 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

)

print

(

f

"Random Forest accuracy: {accuracy_score(y_test, y_pred):.4f}"

)

View the depth of a single tree (example)

print

(

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.

  1. Sequential training: Base learners aresequentiallytrained, rather than in parallel.
  2. 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).
  3. 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

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

)

print

(

f

"Gradient Boosting Tree accuracy: {accuracy_score(y_test, y_pred_gb):.4f}"

)

View feature importance (ensemble methods can usually provide this)

print

(

"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."

  1. Layer 1: Diverse base learners. UsingdistinctLearning algorithms (such as KNN, SVM, and decision trees) train multiple models on the original data.
  2. 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。
  3. 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:

Leverage modern optimization libraries: In practice, directly use highly optimized libraries that implement state-of-the-art ensemble algorithms:

Pay attention to tuning: Ensemble models have many hyperparameters. Key parameters to focus on include: