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

Ensemble Learning

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:

  1. Bagging: Generate multiple training sets through bootstrap sampling, then train multiple models separately, and finally obtain the final result through voting or averaging.
  2. 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.
  3. 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:

Typical algorithms:

Advantage:

Disadvantages:


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:

Typical algorithms:

Advantage:

Disadvantages:


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:

Advantage:

Disadvantages:


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

)

print

(

f

"Random forest accuracy: {accuracy:.2f}"

)

The output is as follows:



随机森林的准确率: 1.00

Code explanation:

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

)

print

(

f

"AdaBoost accuracy: {accuracy:.2f}"

)

The output is as follows:



AdaBoost的准确率: 1.00

Code Explanation:

  1. Load the dataset: When usingload_iris()Function to load the Iris dataset, containing feature dataXand label data.y。
  2. Split into training and test sets: When usingtrain_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%.
  3. Create a decision tree classifier: When usingDecisionTreeClassifier(max_depth=1)Create a decision tree classifier with depth 1 as the base learner for AdaBoost.
  4. Create an AdaBoost classifier.: When usingAdaBoostClassifier()The class creates an AdaBoost classifier,n_estimators=50indicating the use of 50 weak learners,algorithm='SAMME'specifying the use of the SAMME algorithm.
  5. Train the model: When usingfit()Method to train the AdaBoost model on the training data.
  6. Predict: When usingpredict()Method to make predictions on the test set, generating predicted labels.y_pred。
  7. Compute accuracy: When usingaccuracy_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

)

print

(

f

"Stacking accuracy: {accuracy:.2f}"

)

The output is as follows:



tacking的准确率: 1.00

Code Explanation:

  1. Load the dataset: Also useload_iris()Function to load the Iris dataset.
  2. Split into training and test sets: When usingtrain_test_split()function splits the dataset into a training set and a test set.
  3. Define the base learners.: When usingDecisionTreeClassifierandSVCas the base learners.
  4. Create a Stacking classifier.: When usingStackingClassifierThe class creates a Stacking classifier,final_estimator=LogisticRegression()indicating the use of logistic regression as the meta-model.
  5. Train the model: When usingfit()Method to train the model.
  6. Predict: When usingpredict()Method to make predictions on the test set.
  7. Compute accuracy: When usingaccuracy_score()Function to compute the model's accuracy.