Implementing the AdaBoost Algorithm From Scratch
Last Updated :
15 Jul, 2024
In this article, we will learn about the AdaBoost classifier and its practical implementation over a dataset.AdaBoost algorithm falls under ensemble boosting techniques, as we will discuss it combines multiple models to produce more accurate results and this is done in two phases:
- Multiple weak learners are allowed to learn on training data
- Combining these models to generate a meta-model, this meta-model aims to resolve the errors as predicted by the individual weak learners.
Note: For more information, refer Boosting ensemble models
What is AdaBoost
AdaBoost short for Adaptive Boosting is an ensemble learning used in machine learning for classification and regression problems. The main idea behind AdaBoost is to iteratively train the weak classifier on the training dataset with each successive classifier giving more weightage to the data points that are misclassified. The final AdaBoost model is decided by combining all the weak classifier that has been used for training with the weightage given to the models according to their accuracies. The weak model which has the highest accuracy is given the highest weightage while the model which has the lowest accuracy is given a lower weightage.Â
Institution Behind AdaBost Algorithm
AdaBoost techniques combine many weak machine-learning models to create a powerful classification model for the output. The steps to build and combine these models are asÂ
Step1 – Initialize the weights
- For a dataset with N training data points instances, initialize N [Tex]W_{i}[/Tex] weights for each data point with [Tex]W_{i} = \frac{1}{N} Â [/Tex] Â
Step2 – Train weak classifiers
- Train a weak classifier Mk where k is the current iterationÂ
- The weak classifier we are training should have an accuracy greater than 0.5 which means it should be performing better than a naive guess
Step3 – Calculate the error rate and importance of each weak model MkÂ
- Calculate rate error_rate for every weak classifier Mk on the training datasetÂ
- Calculate the importance of each model Îą_k using formula  [Tex]\alpha_k = \frac{1}{2} \ln{\frac{1 – error_k}{error_k}}[/Tex]
Step4 – Update data point weight for each data point WiÂ
- After applying the weak classifier model to the training data we will update the weight assigned to the points using the accuracy of the model. The formula for updating the weights will be [Tex]w_i = w_i \exp{(-\alpha_k y_i M_k(x_i))}[/Tex] . Here yi is the true output and Xi is the corresponding input vectorÂ
Step5 – Normalize the Instance weightÂ
- We will normalize the instance weight so that they can be summed up to 1 using the formula [Tex]W_i = W_i / sum(W)[/Tex]
Step6 – Repeat steps 2-5 for K iterationsÂ
- We will train K classifiers and will calculate model importance and update the instance weights using the above formulaÂ
- The final model M(X) will be an ensemble model which is obtained by combining these weak models weighted by their model weightsÂ

Boosting AlgorithmsÂ
Python implementation of AdaBoostÂ
Python provides special packages for applying AdaBoost we will see how we can use Python for applying AdaBoost on a machine learning problem.Â
In this problem, we are given a dataset containing 3 species of flowers and the features of these flowers such as sepal length, sepal width, petal length, and petal width, and we have to classify the flowers into these species.
Import Libraries
Let’s begin with importing important libraries that we will require to do our classification task:
Python
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier
import warnings
warnings.filterwarnings("ignore")
Reading  And Describing The DatasetÂ
 After, importing the libraries we will load our dataset using the pandas read_csv method as:
Python
# Reading the dataset from the csv file
# separator is a vertical line, as seen in the dataset
data = pd.read_csv("Iris.csv")
# Printing the shape of the dataset
print(data.shape)
(150, 6)
We can see our dataset contains 150 rows and 6 columns. Let us take a look at our actual content in the dataset using head() method as:
Python
|  | Id | SepalLengthCm | SepalWidthCm | PetalLengthCm | PetalWidthCm | Species |
|---|
| 0 | 1 | 5.1 | 3.5 | 1.4 | 0.2 | Iris-setosa |
| 1 | 2 | 4.9 | 3.0 | 1.4 | 0.2 | Iris-setosa |
| 2 | 3 | 4.7 | 3.2 | 1.3 | 0.2 | Iris-setosa |
| 3 | 4 | 4.6 | 3.1 | 1.5 | 0.2 | Iris-setosa |
| 4 | 5 | 5.0 | 3.6 | 1.4 | 0.2 | Iris-setosa |
Dropping Irrevelant Column and Separating Target VariableÂ
The first column is the Id column which has no relevance to flowers so, we will drop it using drop() function. The Species column is our target feature and tells us about the species the flowers belong to. We will separate it using pandas iloc slicing.
Python
data = data.drop('Id',axis=1)
X = data.iloc[:,:-1]
y = data.iloc[:,-1]
print("Shape of X is %s and shape of y is %s"%(X.shape,y.shape))
Shape of X is (150, 4) and shape of y is (150,)
Unique values in our Target VariableÂ
Since this is a classification task we will see the numbers of categories we want to classify our dataset input vector into.Â
Python
total_classes = y.nunique()
print("Number of unique species in dataset are: ",total_classes)
Number of unique species in dataset are: 3
Python
distribution = y.value_counts()
print(distribution)
Iris-virginica 50
Iris-setosa 50
Iris-versicolor 50
Name: Species, dtype: int64
Let’s dig deep into our dataset, and we can see in the above image that our dataset contains 3 classes into which our flowers are distributed also since we have 150 samples all three species have an equal number of samples in the dataset, so we have no class imbalance.
Splitting The DatasetÂ
Now, we will split the dataset for training and validation purposes, the validation set is 25% of the total dataset. For dividing the dataset into training and testing we will use train_test_split method from the sklearn model selection. Â
Python
X_train, X_val, Y_train, Y_val = train_test_split(
X, y, test_size=0.25, random_state=28)
Applying AdaBoost
After creating the training and validation set we will build our AdaBoost classifier model and fit it over the training set for learning. To fit our AdaBoost model we need our dependent variable y and independent variable x.Â
Python
# Creating adaboost classifier model
adb = AdaBoostClassifier()
adb_model = adb.fit(X_train,Y_train)
Accuracy of the AdaBoost ModelÂ
As we fit our model on the train set, we will check the accuracy of our model on the validation set. To check the accuracy of the model we will use the validation dataset that we have created using the train_test_split method.Â
Python
print("The accuracy of the model on validation set is", adb_model.score(X_val,Y_val))
The accuracy of the model on validation set is 0.9210526315789473
As we can see the model has an accuracy of 92% on the validation set which is quite good with no hyperparameter tuning and feature engineering.
Similar Reads
Machine Learning Algorithms
Machine learning algorithms are essentially sets of instructions that allow computers to learn from data, make predictions, and improve their performance over time without being explicitly programmed. Machine learning algorithms are broadly categorized into three types: Supervised Learning: Algorith
9 min read
Top 15 Machine Learning Algorithms Every Data Scientist Should Know in 2025
Machine Learning (ML) Algorithms are the backbone of everything from Netflix recommendations to fraud detection in financial institutions. These algorithms form the core of intelligent systems, empowering organizations to analyze patterns, predict outcomes, and automate decision-making processes. Wi
15 min read
Linear Model Regression
Ordinary Least Squares (OLS) using statsmodels
In this article, we will use Python's statsmodels module to implement Ordinary Least Squares ( OLS ) method of linear regression. Introduction : A linear regression model establishes the relation between a dependent variable( y ) and at least one independent variable( x ) as : [Tex] \hat{y}=b_1x+b_0
4 min read
Linear Regression (Python Implementation)
Linear regression is a statistical method that is used to predict a continuous dependent variable i.e target variable based on one or more independent variables. This technique assumes a linear relationship between the dependent and independent variables which means the dependent variable changes pr
14 min read
ML | Multiple Linear Regression using Python
Linear regression is a basic and commonly used for predictive analysis. It is a statistical approach for modeling relationship between a dependent variable and one independent variables. Multiple Linear Regression is a extended version of it only. It attempts to model relationship between two or mor
4 min read
Polynomial Regression ( From Scratch using Python )
Prerequisites Linear RegressionGradient DescentIntroductionLinear Regression finds the correlation between the dependent variable ( or target variable ) and independent variables ( or features ). In short, it is a linear model to fit the data linearly. But it fails to fit and catch the pattern in no
5 min read
Implementation of Bayesian Regression
Linear regression is a popular regression approach in machine learning. Linear regression is based on the assumption that the underlying data is normally distributed and that all relevant predictor variables have a linear relationship with the outcome. Â But In the real world, this is not always poss
13 min read
How to Perform Quantile Regression in Python
In this article, we are going to see how to perform quantile regression in Python. Linear regression is defined as the statistical method that constructs a relationship between a dependent variable and an independent variable as per the given set of variables. While performing linear regression we a
4 min read
Isotonic Regression in Scikit Learn
Isotonic regression is a regression technique in which the predictor variable is monotonically related to the target variable. This means that as the value of the predictor variable increases, the value of the target variable either increases or decreases in a consistent, non-oscillating manner. Mat
6 min read
Stepwise Regression in Python
Stepwise regression is a method of fitting a regression model by iteratively adding or removing variables. It is used to build a model that is accurate and parsimonious, meaning that it has the smallest number of variables that can explain the data. There are two main types of stepwise regression: F
6 min read
Least Angle Regression (LARS)
Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm u
3 min read
Linear Model Classification
K-Nearest Neighbors (KNN)
ML | Stochastic Gradient Descent (SGD)
Gradient Descent is an iterative optimization process that searches for an objective function's optimum value (Minimum/Maximum). It is one of the most used methods for changing a model's parameters in order to reduce a cost function in machine learning projects. Â The primary goal of gradient descen
10 min read
Ensemble Learning
Ensemble Methods in Python
Ensemble means a group of elements viewed as a whole rather than individually. An Ensemble method creates multiple models and combines them to solve it. Ensemble methods help to improve the robustness/generalizability of the model. In this article, we will discuss some methods with their implementat
11 min read
Random Forest Regression in Python
Random Forest Regression is a versatile machine-learning technique for predicting numerical values. It combines the predictions of multiple decision trees to reduce overfitting and improve accuracy. Python's machine-learning libraries make it easy to implement and optimize this approach. Ensemble Le
11 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 si
6 min read
Implementing the AdaBoost Algorithm From Scratch
In this article, we will learn about the AdaBoost classifier and its practical implementation over a dataset.AdaBoost algorithm falls under ensemble boosting techniques, as we will discuss it combines multiple models to produce more accurate results and this is done in two phases: Multiple weak lear
6 min read
XGBoost
XGBoost is short form for Extreme Gradient Boosting, has become one of the most powerful and widely used machine learning algorithms known for its speed, scalability, and high performance. In this article we will learn about the XG Boost algorithm. Understanding XG Boost Algorithm XGBoost is an impl
5 min read
CatBoost in Machine Learning
We often encounter datasets that contain categorical features and to fit these datasets into the Boosting model we apply various encoding techniques to the dataset such as One-Hot Encoding or Label Encoding. But applying One-Hot encoding creates a sparse matrix which may sometimes lead to the overfi
9 min read
LightGBM (Light Gradient Boosting Machine)
LightGBM is an ensemble learning framework, specifically a gradient boosting method, which constructs a strong learner by sequentially adding weak learners in a gradient descent manner. It optimizes memory usage and training time with techniques like Gradient-based One-Side Sampling (GOSS). Table of
10 min read
Stacking in Machine Learning
Stacking is a way to ensemble multiple classifications or regression model. There are many ways to ensemble models, the widely known models are Bagging or Boosting. Bagging allows multiple similar models with high variance are averaged to decrease variance. Boosting builds multiple incremental model
2 min read