The Wayback Machine - https://web.archive.org/web/20241127002138/https://www.geeksforgeeks.org/ml-bagging-classifier/
Open In App

ML | Bagging classifier

Last Updated : 12 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In machine learning, for building solid and reliable models, prediction accuracy is the key factor. Ensemble learning is a supervised machine-learning technique that combines multiple models to build a more powerful and robust model. The idea is that by combining the strengths of multiple models, we can create a model that is more robust and less likely to overfit the data. It can be used for both classification and regression tasks.

Ensemble learning techniques can be categorized in three ways:

  1. Bagging (Bootstrap Aggregating)
  2. Boosting
  3. Stacking (Stacked Generalization)

Bagging is a supervised machine-learning technique, and it can be used for both regression and classification tasks. In this article, we will discuss the bagging classifier.

Bagging Classifier

Bagging (or Bootstrap aggregating) is a type of ensemble learning in which multiple base models are trained independently and in parallel on different subsets of the training data. Each subset is generated using bootstrap sampling, in which data points are picked at random with replacement. In the case of the bagging classifier, the final prediction is made by aggregating the predictions of the all-base model using majority voting. In the models of regression, the final prediction is made by averaging the predictions of the all-base model, and that is known as bagging regression.

Bagging classifier-Geeksforgeeks

Bagging Classifier

Bagging helps improve accuracy and reduce overfitting, especially in models that have high variance.

How does Bagging Classifier Work?

The basic steps of how a bagging classifier works are as follows:

  • Bootstrap Sampling: In Bootstrap Sampling randomly ‘n’ subsets of original training data are sampled with replacement. This step ensures that the base models are trained on diverse subsets of the data, as some samples may appear multiple times in the new subset, while others may be omitted. It reduces the risks of overfitting and improves the accuracy of the model.
 Let's break it down step by step:
Original training dataset: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Resampled training set 1: [2, 3, 3, 5, 6, 1, 8, 10, 9, 1]
Resampled training set 2: [1, 1, 5, 6, 3, 8, 9, 10, 2, 7]
Resampled training set 3: [1, 5, 8, 9, 2, 10, 9, 7, 5, 4]
  • Base Model Training: In bagging, multiple base models are used. After the Bootstrap Sampling, each base model is independently trained using a specific learning algorithm, such as decision trees, support vector machines, or neural networks on a different bootstrapped subset of data. These models are typically called “Weak learners” because they may not be highly accurate on their own. Since the base model is trained independently of different subsets of data. To make the model computationally efficient and less time-consuming, the base models can be trained in parallel.
  • Aggregation: Once all the base models are trained, it is used to make predictions on the unseen data i.e. the subset of data on which that base model is not trained. In the bagging classifier, the predicted class label for the given instance is chosen based on the majority voting. The class which has the majority voting is the prediction of the model.
  • Out-of-Bag (OOB) Evaluation: Some samples are excluded from the training subset of particular base models during the bootstrapping method. These “out-of-bag” samples can be used to estimate the model’s performance without the need for cross-validation.
  • Final Prediction: After aggregating the predictions from all the base models, Bagging produces a final prediction for each instance.

Algorithm for the Bagging classifier:

Classifier generation:
Let N be the size of the training set.
for each of t iterations:
sample N instances with replacement from the original training set.
apply the learning algorithm to the sample.
store the resulting classifier.
Classification:
for each of the t classifiers:
predict class of instance using classifier.
return class that was predicted most often.

Python implementation of the Bagging classifier algorithm: 

BaggingClassifier

Define the BaggingClassifier class with the base_classifier and n_estimators as input parameters for the constructor.

Step 1: Initialize the class attributes base_classifier, n_estimators, and an empty list classifiers to store the trained classifiers.

Step 2: Define the fit method to train the bagging classifiers:

For each iteration from 0 to n_estimators – 1:

  • Perform bootstrap sampling with replacement by randomly selecting len(X) indices from the range of len(X) with replacement.
    • Create new subsets X_sampled and y_sampled by using the selected indices.
  • Create a new instance of the base_classifier to create a new classifier model for this iteration.
  • Train the classifier on the sampled data X_sampled and y_sampled.
  • Append the trained classifier to the list classifiers.
    • Return the list of trained classifiers.

Step 3: Define the predict method to make predictions using the ensemble of classifiers:

  • For each classifier in the classifiers list:
    • Use the trained classifier to predict the classes of the input data X.
      • Aggregate the predictions using majority voting to get the final predictions.
  • Return the final predictions.

Python3




class BaggingClassifier:
    def __init__(self, base_classifier, n_estimators):
        self.base_classifier = base_classifier
        self.n_estimators = n_estimators
        self.classifiers = []
         
    def fit(self, X, y):
          for _ in range(self.n_estimators):
              # Bootstrap sampling with replacement
              indices = np.random.choice(len(X), len(X), replace=True)
              X_sampled = X[indices]
              y_sampled = y[indices]
 
              # Create a new base classifier and train it on the sampled data
              classifier = self.base_classifier.__class__()
              classifier.fit(X_sampled, y_sampled)
 
              # Store the trained classifier in the list of classifiers
              self.classifiers.append(classifier)
          return self.classifiers
    def predict(self, X):
        # Make predictions using all the base classifiers
        predictions = [classifier.predict(X) for classifier in self.classifiers]
        # Aggregate predictions using majority voting
        majority_votes = np.apply_along_axis(lambda x: np.bincount(x).argmax(), axis=0, arr=predictions)
 
        return majority_votes


Importing Necessary Libraries

Python3




from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier


Load the dataset

Python3




# Load the dataset
digit = load_digits()
X, y = digit.data, digit.target
 
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# Create the base classifier
dc = DecisionTreeClassifier()
model = BaggingClassifier(base_classifier=dc, n_estimators=10)
classifiers = model.fit(X_train, y_train)
 
# Make predictions on the test set
y_pred = model.predict(X_test)
 
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)


Output:

Accuracy: 0.9472222222222222

Let’s check the result of each classifier individually,

Python3




for i, clf in enumerate(classifiers):
    y_pred = clf.predict(X_test)
    # Calculate accuracy
    accuracy = accuracy_score(y_test, y_pred)
    print("Accuracy:"+str(i+1),':', accuracy)


Output:

Accuracy:1 : 0.8833333333333333
Accuracy:2 : 0.8361111111111111
Accuracy:3 : 0.85
Accuracy:4 : 0.85
Accuracy:5 : 0.8388888888888889
Accuracy:6 : 0.8388888888888889
Accuracy:7 : 0.8472222222222222
Accuracy:8 : 0.8222222222222222
Accuracy:9 : 0.8527777777777777
Accuracy:10 : 0.8111111111111111

Bagging classifier using Sklearn Library

Python3




from sklearn.ensemble import BaggingClassifier
 
# Load the dataset
digit = load_digits()
X, y = digit.data, digit.target
 
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# Create the base classifier
base_classifier = DecisionTreeClassifier()
 
# Number of base models (iterations)
n_estimators = 10
 
# Create the Bagging classifier
bagging_classifier = BaggingClassifier(base_estimator=base_classifier, n_estimators=n_estimators)
 
# Train the Bagging classifier
bagging_classifier.fit(X_train, y_train)
 
# Make predictions on the test set
y_pred = bagging_classifier.predict(X_test)
 
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)


Output:

Accuracy: 0.9361111111111111

Advantages of Bagging Classifier

The advantages of using a Bagging Classifier are as follows:

  1. Improved Predictive Performance: Bagging Classifier often outperforms single classifiers by reducing overfitting and increasing predictive accuracy. By combining multiple base models, it can better generalize to unseen data.
  2. Robustness: Bagging reduces the impact of outliers and noise in the data by aggregating predictions from multiple models. This enhances the overall stability and robustness of the model.
  3. Reduced Variance: Since each base model is trained on different subsets of the data, the aggregated model’s variance is significantly reduced compared to an individual model.
  4. Parallelization: Bagging allows for parallel processing, as each base model can be trained independently. This makes it computationally efficient, especially for large datasets.
  5. Flexibility: Bagging Classifier is a versatile technique that can be applied to a wide range of machine learning algorithms, including decision trees, random forests, and support vector machines.

Disadvantages of Bagging :

  1. Loss of Interpretability:
    • Bagging involves aggregating predictions from multiple models, making it harder to interpret the individual contributions of each base model. This can limit the ability to derive precise business insights from the ensemble.
  2. Computationally Expensive:
    • As the number of iterations (bootstrap samples) increases, the computational cost of bagging also grows. This makes it less suitable for real-time applications where efficiency and speed are crucial. Efficient parallel processing or distributed systems are often required for handling large datasets and numerous iterations.
  3. Less Flexible:
    • Bagging is most effective when applied to algorithms that are less stable or more prone to overfitting. Algorithms that are already stable or exhibit low bias might not benefit significantly from bagging, as there is less variance to be reduced within the ensemble.

Applications of Bagging Classifier

Bagging Classifier can be applied in various real-world tasks:

  1. Fraud Detection: Bagging Classifier can be used to detect fraudulent transactions by aggregating predictions from multiple fraud detection models.
  2. Spam filtering: Bagging classifier can be used to filter spam emails by aggregating predictions from multiple spam filters trained on different subsets of the spam emails.
  3. Credit scoring: Bagging classifier can be used to improve the accuracy of credit scoring models by combining the predictions of multiple models trained on different subsets of the credit data.
  4. Image Classification: Bagging classifier can be used to improve the accuracy of image classification tasks by combining the predictions of multiple classifiers trained on different subsets of the training images.
  5. Natural language processing: In NLP tasks, the bagging classifier can combine predictions from multiple language models to achieve better text classification results.

Conclusion

Bagging Classifier, as an ensemble learning technique, offers a powerful solution for improving predictive performance and model robustness. Bagging Classifier avoids overfitting, improves generalisation, and gives solid predictions for a wide range of applications by using the collective wisdom of numerous base models.



Similar Reads

Perform Bagging in R
We only utilize one training dataset when building a decision tree for a certain dataset. However, adopting a single decision tree has the drawback of having a high variance. That is, the outcomes could be very different if we divided the dataset in half and used the decision tree on each half. Bagging, also known as bootstrap aggregating, is a tec
4 min read
Bagging vs Dropout in Deep Neural Networks
Answer: Bagging involves training multiple models on different subsets of the training data, while dropout randomly drops units (along with their connections) from the neural network during training.Bagging (Bootstrap Aggregating):Bagging is an ensemble learning technique that involves training multiple models independently on different subsets of
3 min read
Bagging and Random Forest for Imbalanced Classification
Ensemble learning techniques like bagging and random forests have gained prominence for their effectiveness in handling imbalanced classification problems. In this article, we will delve into these techniques and explore their applications in mitigating the impact of class imbalance. Classification problems are fundamental to machine learning and f
8 min read
Bagging vs Boosting in Machine Learning
As we know, Ensemble learning helps improve machine learning results by combining several models. This approach allows the production of better predictive performance compared to a single model. Basic idea is to learn a set of classifiers (experts) and to allow them to vote. Bagging and Boosting are two types of Ensemble Learning. These two decreas
5 min read
What are Some Popular Ensemble Methods Apart from Bagging and Boosting?
Answer: Determining the optimal number of clusters in a dataset is crucial for effective cluster analysis in unsupervised learning, especially in methods like K-means. Common techniques include the Elbow Method, the Silhouette Score, and the Gap Statistic, each providing different insights to guide the selection of the most appropriate cluster coun
3 min read
NLP | Classifier-based Chunking | Set 2
Using the data from the treebank_chunk corpus let us evaluate the chunkers (prepared in the previous article). Code #1 : C/C++ Code # loading libraries from chunkers import ClassifierChunker from nltk.corpus import treebank_chunk train_data = treebank_chunk.chunked_sents()[:3000] test_data = treebank_chunk.chunked_sents()[3000:] # initializing chun
2 min read
Calculate Efficiency Of Binary Classifier
Prerequisite: Getting started with Classification In this article, we will discuss a method to calculate the efficiency of a Binary classifier. Let's assume there is a problem where we have to classify a product that belongs to either class A or class B. Let us define few statistical parameters : TP (True Positive) = number of Class A products, whi
3 min read
NLP | Classifier-based tagging
ClassifierBasedPOSTagger class: It is a subclass of ClassifierBasedTagger that uses classification technique to do part-of-speech tagging. From the words, features are extracted and then passed to an internal classifier. It classifies the features and returns a label i.e. a part-of-speech tag. The feature detector finds multiple length suffixes, do
2 min read
NLP | Classifier-based Chunking | Set 1
The ClassifierBasedTagger class learns from the features, unlike most part-of-speech taggers. ClassifierChunker class can be created such that it can learn from both the words and part-of-speech tags, instead of just from the part-of-speech tags as the TagChunker class does. The (word, pos, iob) 3-tuples is converted into ((word, pos), iob) 2-tuple
2 min read
Ensemble Classifier | Data Mining
Ensemble learning helps improve machine learning results by combining several models. This approach allows the production of better predictive performance compared to a single model. Basic idea is to learn a set of classifiers (experts) and to allow them to vote. Advantage : Improvement in predictive accuracy. Disadvantage : It is difficult to unde
3 min read
ML | Implementation of KNN classifier using Sklearn
Prerequisite: K-Nearest Neighbours Algorithm K-Nearest Neighbors is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection. It is widely disposable in real-life scenarios since it is non-
2 min read
ML | Extra Tree Classifier for Feature Selection
Prerequisites: Decision Tree Classifier Extremely Randomized Trees Classifier(Extra Trees Classifier) is a type of ensemble learning technique which aggregates the results of multiple de-correlated decision trees collected in a "forest" to output it's classification result. In concept, it is very similar to a Random Forest Classifier and only diffe
6 min read
ML | Voting Classifier using Sklearn
A Voting Classifier is a machine learning model that trains on an ensemble of numerous models and predicts an output (class) based on their highest probability of chosen class as the output. It simply aggregates the findings of each classifier passed into Voting Classifier and predicts the output class based on the highest majority of voting. The i
3 min read
ML | Case Based Reasoning (CBR) Classifier
As we know Nearest Neighbour classifiers stores training tuples as points in Euclidean space. But Case-Based Reasoning classifiers (CBR) use a database of problem solutions to solve new problems. It stores the tuples or cases for problem-solving as complex symbolic descriptions. How CBR works? When a new case arises to classify, a Case-based Reason
2 min read
Rule-Based Classifier - Machine Learning
Rule-based classifiers are just another type of classifier which makes the class decision depending by using various "if..else" rules. These rules are easily interpretable and thus these classifiers are generally used to generate descriptive models. The condition used with "if" is called the antecedent and the predicted class of each rule is called
4 min read
ML - Nearest Centroid Classifier
The Nearest Centroid (NC) Classifier is one of the most underrated and underutilised classifiers in Machine Learning. However, it is quite powerful and is highly efficient for certain Machine Learning classification tasks. The Nearest Centroid classifier is somewhat similar to the K-Nearest Neighbours classifier. To know more about the K-Nearest Ne
3 min read
Understanding Auxiliary Classifier : GAN
Prerequisite: GANs(General Adversarial Networks) In this article, we will be discussing a special class conditional GAN or c-GAN known as Auxiliary Classifier GAN or AC-GAN. Before getting into that, it is important to understand what a class conditional GAN is. Class-Conditional GAN (c-GANs): c-GAN can be understood as a GAN with some conditional
4 min read
Hyperparameters of Random Forest Classifier
In this article, we are going to learn about different hyperparameters that exist in a Random Forest Classifier. We have already learnt about the implementation of Random Forest Classifier using scikit-learn library in the article https://www.geeksforgeeks.org/random-forest-classifier-using-scikit-learn/. Hyperparameters are configurations that can
4 min read
Building a Machine Learning Model Using J48 Classifier
What is the J48 Classifier? J48 is a machine learning decision tree classification algorithm based on Iterative Dichotomiser 3. It is very helpful in examine the data categorically and continuously. Note: To build our J48 machine learning model we’ll use the weka tool. What is Weka? Weka is an open-source tool developed by the University of Waikato
3 min read
Identify Members of BTS — An Image Classifier
BTS is an eminent K-Pop band comprising of 7 members. This article looks at an image classifier that would recognize the name of the band member from a picture. The image classifier would be built using fastai. It is a deep learning library that aims to democratize deep learning. It is built on top of PyTorch, and has plethora of models with optimi
4 min read
Save classifier to disk in scikit-learn in Python
In this article, we will cover saving a Save classifier to disk in scikit-learn using Python. We always train our models whether they are classifiers, regressors, etc. with the scikit learn library which require a considerable time to train. So we can save our trained models and then retrieve them when required. This saves us a lot of time. Seriali
3 min read
Classifier Comparison in Scikit Learn
In scikit-learn, a classifier is an estimator that is used to predict the label or class of an input sample. There are many different types of classifiers that can be used in scikit-learn, each with its own strengths and weaknesses. Let's load the iris datasets from the sklearn.datasets and then train different types of classifier using it. C/C++ C
3 min read
Music Genre Classifier using Machine Learning
Music is the art of arranging sound and noise together to create harmony, melody, rhythm, and expressive content. It is organized so that humans and sometimes other living organisms can express their current emotions with it. We all have our own playlist, which we listen to while traveling, studying, dancing, etc. In short, every emotion has a diff
5 min read
Linear Classifier in Tensorflow
In this article, we will be using tf.estimator.LinearClassifier to build a model and train it on the famous titanic dataset. All of this will be done by using the TensorFlow API. Importing Libraries Python libraries make it easy for us to handle the data and perform typical and complex tasks with a single line of code. Pandas - This library helps t
3 min read
How to Make Better Models in Python using SVM Classifier and RBF Kernel
As machine learning models continue to become more popular and widespread, it is important for data scientists and developers to understand how to build the best models possible. One powerful tool that can be used to improve the accuracy and performance of machine learning models is the support vector machine (SVM) classifier, which is a type of li
5 min read
Logistic Regression Vs Random Forest Classifier
A statistical technique called logistic regression is used to solve problems involving binary classification, in which the objective is to predict a binary result (such as yes/no, true/false, or 0/1) based on one or more predictor variables (also known as independent variables, features, or predictors). Based on the values of the predictor variable
7 min read
Voting Classifier
We can create prediction models using a variety of machine learning algorithms and approaches, which is an exciting subject. Scikit-Learn Voting Classifier is one such method that may dramatically improve the performance of your models. An ensemble learning approach combines many base models to get a more effective and precise model. The theory beh
7 min read
Build a Neural Network Classifier in R
Creating a neural network classifier in R can be done using the popular deep learning framework called Keras, which provides a high-level interface to build and train neural networks. Here's a step-by-step guide on how to build a simple neural network classifier using Keras in R Programming Language. Before diving into building our own neural netwo
9 min read
Random Forest Classifier using Scikit-learn
In this article, we will see how to build a Random Forest Classifier using the Scikit-Learn library of Python programming language and to do this, we use the IRIS dataset which is quite a common and famous dataset. Random ForestThe Random forest or Random Decision Forest is a supervised Machine learning algorithm used for classification, regression
8 min read
What Is the Difference Between SGD Classifier and the Logistic Regression?
Answer: The main difference is that SGDClassifier uses stochastic gradient descent optimization while logistic regression uses the logistic function to model binary classification.Explanation:Optimization Technique:Logistic Regression: In logistic regression, the optimization is typically performed using methods like gradient descent or Newton's me
2 min read
three90RightbarBannerImg