Machine Learning-Ensemble Learning: Core Concepts and Operations

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

methodcore idearepresentative algorithm
BaggingTrain multiple models in parallel and aggregate predictionsBagging、Random Forest
BoostingTrain models sequentially to gradually improve predictionsAdaBoost、Gradient Boosting
VotingVote or average predictions from different modelsVotingClassifier
StackingUsing another model to combine predictions from a base modelStackingClassifier

This article mainly discusses Bagging and Boosting.

The difference between Bagging and Boosting

FeaturesBaggingBoosting
Training methodBase models can often be trained in parallelBase models are usually trained sequentially
Main mechanismResampling, model averagingOptimize losses or sample weights step by step
Typical effectsreduce varianceImprove fit, control bias and variance
Typical algorithmRandom ForestGBDT、XGBoost、LightGBM

2. Bagging:Bootstrap Aggregating

Bagging is the abbreviation of Bootstrap Aggregating.

Its basic process:

  1. Random sampling with replacement (Bootstrap) is performed from the original training set.
  2. Train multiple base models based on different sample subsets.
  3. 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:

parametersfunction
estimatorbase model
n_estimatorsNumber of basic models
max_samplesThe number or proportion of samples used by each model
max_featuresThe number or proportion of features used by each model
bootstrapIs there any replacement sampling?
n_jobsNumber 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

  1. Perform Bootstrap Sampling on the training samples.
  2. Train a tree Decision Tree for each sample subset.
  3. Only some candidate features are considered during each node partitioning.
  4. Aggregate the predictions of all decision trees.

Category:

y^=MajorityVote⁡(T1(x),…,TM(x))\hat y=\operatorname{MajorityVote}(T_1(x),\ldots,T_M(x))

Return:

y^=1M∑m=1MTm(x)\hat y=\frac{1}{M}\sum_{m=1}^{M}T_m(x)

Among them, TmT_m represents the mmth 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

parametersfunction
n_estimatorsnumber of trees
max_depthmaximum tree depth
min_samples_splitMinimum number of samples for node splitting
min_samples_leafMinimum number of samples for leaf nodes
max_featuresThe number of features considered for each split
bootstrapWhether to use Bootstrap
class_weightCategory 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:

  1. Initialize training sample weights.
  2. Train a weak classifier.
  3. Adjust sample weights based on classification results.
  4. Pay more attention to previously misclassified samples.
  5. 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:

Fm−1(x)F_{m-1}(x)

In round mm, a new model hm(x)h_m(x) is trained and then updated:

Fm(x)=Fm−1(x)+ηhm(x)F_m(x)=F_{m-1}(x)+\eta h_m(x)

Among them:

  • hm(x)h_m(x): Newly trained base model.
  • η\eta:Learning Rate。
  • Fm(x)F_m(x): Integrated model after round mm.

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 y−y^y-\hat y.

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

parametersfunction
n_estimatorsBoosting number of iteration rounds
learning_rateThe scaling factor contributed by the model in each round
max_depthThe maximum depth of the underlying decision tree
subsampleThe proportion of samples used in each round of training
min_samples_leafMinimum 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:

Obj=∑iL(yi,y^i)+∑mΩ(Tm)Obj=\sum_i L(y_i,\hat y_i)+\sum_m\Omega(T_m)

Among them:

  • LL: Prediction loss.
  • Ω(Tm)\Omega(T_m): 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

parametersfunction
n_estimatorsBoosting number of iteration rounds
max_depthmaximum tree depth
learning_rateLearning rate per round
subsampleRow sampling ratio per round
colsample_bytreeThe feature scale used by each tree
min_child_weightMinimum Hessian weight sum required to limit child nodes
gammaMinimum Loss Reduction required for node splitting
reg_alphaL1 regularization
reg_lambdaL2 regularization
tree_methodtree 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

parametersfunction
n_estimatorsBoosting round number
learning_ratelearning rate
num_leavesMaximum number of leaf nodes per tree
max_depthMaximum tree depth, -1 means this limit is not set
min_child_samplesMinimum number of samples for leaf nodes
min_split_gainNode split minimum gain
subsamplerow sampling ratio
subsample_freqLine sampling frequency
colsample_bytreeFeature sampling ratio
reg_alpha / reg_lambdaL1 / 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

FeaturesRandom ForestXGBoostLightGBM
Basic ideaBaggingGradient BoostingGradient Boosting
tree relationshiprelatively independentsequential trainingsequential training
Common tree growing strategiesOrdinary decision treeStrategies such as Depth-wiseMain Leaf-wise
Feature normalizationUsually not requiredUsually not requiredUsually not required
Missing value supportDepends on implementation and versionsupportsupport
Parameter adjustment difficultyrelatively lowhigherhigher
Overfitting controlTree depth, leaf nodes, feature samplingRegularization, sampling, Early StoppingLeaf node control, sampling, Early Stopping
Typical usesRobust tabular data baselineHigh performance tabular modelingLarge-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

  1. Build Baseline using a simple model.
  2. Select Metrics that matches your business goals.
  3. Cross-validation is performed within the training data.
  4. Adjust hyperparameters via Validation Set and Early Stopping.
  5. 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 pointsimportance
Ensemble Learningcore
Bagging / Bootstrapcore
Random Forestcore
Random Feature Selectioncore
Out-of-Bag Evaluationimportant
Boosting / AdaBoostimportant
Gradient Boosting / GBDTcore
Gradient / Learning Ratecore
Histogram-based GBDTimportant
XGBoost / Regularizationcore
LightGBM / Leaf-wisecore
Early Stoppingcore
Feature Importanceimportant
Voting / Stackingon demand

The five most important concepts of ensemble learning:

  1. Bagging: Reduce prediction variance and improve stability through Bootstrap Sampling and model aggregation.
  2. Random Forest: Introduce feature randomness on the basis of Bagging Decision Trees to reduce the correlation between trees.
  3. Boosting: Build models sequentially and gradually improve the predictions of existing integrated models.
  4. Gradient Boosting: Use the gradient information of the loss function to train a new model and optimize the overall goal round by round.
  5. XGBoost / LightGBM: Enhance the utility of GBDT through mechanisms such as efficient tree building, regularization, sampling and Early Stopping.

Reference documentation

Back to top