The Wayback Machine - https://web.archive.org/web/20240910133911/https://www.geeksforgeeks.org/ml-binning-or-discretization/
Open In App

ML | Binning or Discretization

Last Updated : 14 Apr, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Real-world data tend to be noisy. Noisy data is data with a large amount of additional meaningless information in it called noise. Data cleaning (or data cleansing) routines attempt to smooth out noise while identifying outliers in the data.

There are three data smoothing techniques as follows –

  1. Binning : Binning methods smooth a sorted data value by consulting its “neighborhood”, that is, the values around it.
  2. Regression : It conforms data values to a function. Linear regression involves finding the “best” line to fit two attributes (or variables) so that one attribute can be used to predict the other.
  3. Outlier analysis : Outliers may be detected by clustering, for example, where similar values are organized into groups, or “clusters”. Intuitively, values that fall outside of the set of clusters may be considered as outliers.

Binning method for data smoothing –
Here, we are concerned with the Binning method for data smoothing. In this method the data is first sorted and then the sorted values are distributed into a number of buckets or bins. As binning methods consult the neighborhood of values, they perform local smoothing.

There are basically two types of binning approaches –

  1. Equal width (or distance) binning : The simplest binning approach is to partition the range of the variable into k equal-width intervals. The interval width is simply the range [A, B] of the variable divided by k,
    w = (B-A) / k

    Thus, ith interval range will be [A + (i-1)w, A + iw] where i = 1, 2, 3…..k
    Skewed data cannot be handled well by this method.

  2. Equal depth (or frequency) binning : In equal-frequency binning we divide the range [A, B] of the variable into intervals that contain (approximately) equal number of points; equal frequency may not be possible due to repeated values.

How to perform smoothing on the data?

There are three approaches to perform smoothing –

  1. Smoothing by bin means : In smoothing by bin means, each value in a bin is replaced by the mean value of the bin.
  2. Smoothing by bin median : In this method each bin value is replaced by its bin median value.
  3. Smoothing by bin boundary : In smoothing by bin boundaries, the minimum and maximum values in a given bin are identified as the bin boundaries. Each bin value is then replaced by the closest boundary value.

Sorted data for price(in dollar) : 2, 6, 7, 9, 13, 20, 21, 24, 30

Partition using equal frequency approach:
Bin 1 : 2, 6, 7
Bin 2 : 9, 13, 20
Bin 3 : 21, 24, 30

Smoothing by bin mean :
Bin 1 : 5, 5, 5
Bin 2 : 14, 14, 14
Bin 3 : 25, 25, 25

Smoothing by bin median :
Bin 1 : 6, 6, 6
Bin 2 : 13, 13, 13
Bin 3 : 24, 24, 24

Smoothing by bin boundary :
Bin 1 : 2, 7, 7
Bin 2 : 9, 9, 20
Bin 3 : 21, 21, 30

Binning can also be used as a discretization technique. Here discretization refers to the process of converting or partitioning continuous attributes, features or variables to discretized or nominal attributes/features/variables/intervals.
For example, attribute values can be discretized by applying equal-width or equal-frequency binning, and then replacing each bin value by the bin mean or median, as in smoothing by bin means or smoothing by bin medians, respectively. Then the continuous values can be converted to a nominal or discretized value which is same as the value of their corresponding bin.

Below is the Python implementation:

bin_mean




import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
# import statsmodels.api as sm
import statistics
import math
from collections import OrderedDict
  
x =[]
print("enter the data")
x = list(map(float, input().split()))
  
print("enter the number of bins")
bi = int(input())
  
# X_dict will store the data in sorted order
X_dict = OrderedDict()
# x_old will store the original data
x_old ={}
# x_new will store the data after binning
x_new ={}
  
  
for i in range(len(x)):
    X_dict[i]= x[i]
    x_old[i]= x[i]
  
x_dict = sorted(X_dict.items(), key = lambda x: x[1])
  
# list of lists(bins)
binn =[]
# a variable to find the mean of each bin
avrg = 0
  
i = 0
k = 0
num_of_data_in_each_bin = int(math.ceil(len(x)/bi))
  
# performing binning
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        avrg = avrg + h
        i = i + 1
    elif(i == num_of_data_in_each_bin):
        k = k + 1
        i = 0
        binn.append(round(avrg / num_of_data_in_each_bin, 3))
        avrg = 0
        avrg = avrg + h
        i = i + 1
rem = len(x)% bi
if(rem == 0):
    binn.append(round(avrg / num_of_data_in_each_bin, 3))
else:
    binn.append(round(avrg / rem, 3))
  
# store the new value of each data
i = 0
j = 0
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        x_new[g]= binn[j]
        i = i + 1
    else:
        i = 0
        j = j + 1
        x_new[g]= binn[j]
        i = i + 1
print("number of data in each bin")
print(math.ceil(len(x)/bi))
  
for i in range(0, len(x)):
    print('index {2} old value {0} new value {1}'.format(x_old[i], x_new[i], i))


bin_median




import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
# import statsmodels.api as sm
import statistics
import math
from collections import OrderedDict
  
  
x =[]
print("enter the data")
x = list(map(float, input().split()))
  
print("enter the number of bins")
bi = int(input())
  
# X_dict will store the data in sorted order
X_dict = OrderedDict()
# x_old will store the original data
x_old ={}
# x_new will store the data after binning
x_new ={}
  
for i in range(len(x)):
    X_dict[i]= x[i]
    x_old[i]= x[i]
  
x_dict = sorted(X_dict.items(), key = lambda x: x[1])
  
  
# list of lists(bins)
binn =[]
# a variable to find the mean of each bin
avrg =[]
  
i = 0
k = 0
num_of_data_in_each_bin = int(math.ceil(len(x)/bi))
# performing binning
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        avrg.append(h)
        i = i + 1
    elif(i == num_of_data_in_each_bin):
        k = k + 1
        i = 0
        binn.append(statistics.median(avrg))
        avrg =[]
        avrg.append(h)
        i = i + 1
  
binn.append(statistics.median(avrg))
  
# store the new value of each data
i = 0
j = 0
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        x_new[g]= round(binn[j], 3)
        i = i + 1
    else:
        i = 0
        j = j + 1
        x_new[g]= round(binn[j], 3)
        i = i + 1
  
print("number of data in each bin")
print(math.ceil(len(x)/bi))
for i in range(0, len(x)):
    print('index {2} old value {0} new value {1}'.format(x_old[i], x_new[i], i))


bin_boundary




import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn import linear_model
# import statsmodels.api as sm
import statistics
import math
from collections import OrderedDict
  
x =[]
print("enter the data")
x = list(map(float, input().split()))
  
print("enter the number of bins")
bi = int(input())
  
# X_dict will store the data in sorted order
X_dict = OrderedDict()
# x_old will store the original data
x_old ={}
# x_new will store the data after binning
x_new ={}
  
  
for i in range(len(x)):
    X_dict[i]= x[i]
    x_old[i]= x[i]
  
x_dict = sorted(X_dict.items(), key = lambda x: x[1])
  
# list of lists(bins)
binn =[]
# a variable to find the mean of each bin
avrg =[]
  
i = 0
k = 0
num_of_data_in_each_bin = int(math.ceil(len(x)/bi))
  
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        avrg.append(h)
        i = i + 1
    elif(i == num_of_data_in_each_bin):
        k = k + 1
        i = 0
        binn.append([min(avrg), max(avrg)])
        avrg =[]
        avrg.append(h)
        i = i + 1
binn.append([min(avrg), max(avrg)])
  
i = 0
j = 0
  
for g, h in X_dict.items():
    if(i<num_of_data_in_each_bin):
        if(abs(h-binn[j][0]) >= abs(h-binn[j][1])):
            x_new[g]= binn[j][1]
            i = i + 1
        else:
            x_new[g]= binn[j][0]
            i = i + 1
    else:
        i = 0
        j = j + 1
        if(abs(h-binn[j][0]) >= abs(h-binn[j][1])):
            x_new[g]= binn[j][1]
        else:
            x_new[g]= binn[j][0]
        i = i + 1
  
print("number of data in each bin")
print(math.ceil(len(x)/bi))
for i in range(0, len(x)):
    print('index {2} old value  {0} new value  {1}'.format(x_old[i], x_new[i], i))


 
Reference: https://en.wikipedia.org/wiki/Data_binning



Similar Reads

Python | Binning method for data smoothing
Prerequisite: ML | Binning or Discretization Binning method is used to smoothing data or to handle noisy data. In this method, the data is first sorted and then the sorted values are distributed into a number of buckets or bins. As binning methods consult the neighbourhood of values, they perform local smoothing. There are three approaches to perfo
3 min read
Binning in Data Mining
Data binning, bucketing is a data pre-processing method used to minimize the effects of small observation errors. The original data values are divided into small intervals known as bins and then they are replaced by a general value calculated for that bin. This has a smoothing effect on the input data and may also reduce the chances of overfitting
2 min read
Binning Data In Python With Scipy &amp; Numpy
Binning data is an essential technique in data analysis that enables the transformation of continuous data into discrete intervals, providing a clearer picture of the underlying trends and distributions. In the Python ecosystem, the combination of numpy and scipy libraries offers robust tools for effective data binning. In this article, we'll explo
8 min read
Exploration with Hexagonal Binning and Contour Plots
Hexagonal binning is a plot of two numeric variables with the records binned into hexagons. The code below is a hexagon binning plot of the relationship between the finished square feet versus the tax-assessed value for homes. Rather than plotting points, records are grouped into hexagonal bins and color indicating the number of records in that bin
2 min read
Machine Learning Tutorial
Machine Learning tutorial covers basic and advanced concepts, specially designed to cater to both students and experienced working professionals. This machine learning tutorial helps you gain a solid introduction to the fundamentals of machine learning and explore a wide range of techniques, including supervised, unsupervised, and reinforcement lea
8 min read
Backpropagation in Neural Network
Machine learning models learn from data and make predictions. One of the fundamental concepts behind training these models is backpropagation. In this article, we will explore what backpropagation is, why it is crucial in machine learning, and how it works. Table of Content What is backpropagation?Advantages of Using the Backpropagation Algorithm i
12 min read
Types of Machine Learning
Machine learning is the branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data and improve from previous experience without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data. In this article,
13 min read
100+ Machine Learning Projects with Source Code [2024]
Machine Learning gained a lot of popularity and become a necessary tool for research purposes as well as for Business. It is a revolutionary field that helps us to make better decisions and automate tasks. Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. In this article, you'll
6 min read
Support Vector Machine (SVM) Algorithm
Support Vector Machine (SVM) is a powerful machine learning algorithm used for linear or nonlinear classification, regression, and even outlier detection tasks. SVMs can be used for a variety of tasks, such as text classification, image classification, spam detection, handwriting identification, gene expression analysis, face detection, and anomaly
10 min read
Filter Pandas Dataframe by Column Value
Filtering a Pandas DataFrame by way of column values is a commonplace operation while running with information in Python. You can use various methods and techniques for Pandas filtering. Here are numerous ways to filter out a Pandas DataFrame through column values. Pandas Filtering using Exact Value # Filter rows where column 'A' is equal to 3filte
5 min read
One Hot Encoding in Machine Learning
Most real-life datasets we encounter during our data science project development have columns of mixed data type. These datasets consist of both categorical as well as numerical columns. However, various Machine Learning models do not work with categorical data and to fit this data into the machine learning model it needs to be converted into numer
5 min read
How to rename columns in Pandas DataFrame
Given a Pandas DataFrame, let’s see how to rename columns in Pandas with examples. Here, we will discuss 5 different ways to rename column names in Pandas DataFrame. Pandas Rename Column df.rename(columns={'old_column_name1': 'new_column_name1', 'old_column_name2': 'new_column_name2'}, inplace=True)Pandas Rename ColumnRename Column Pandas using ren
6 min read
Adding new column to existing DataFrame in Pandas
Adding new columns to an existing DataFrame is a fundamental task in data analysis using Pandas . It allows you to enrich your data with additional information and facilitate further analysis and manipulation. This article will explore various methods for adding new columns, including simple assignment, the insert() method, the assign() method. Let
7 min read
How to Get Column Names in Pandas
While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform some certain operations. Let's discuss how to get column names in the Pandas . Syntax to Get Column Names in Pandas # Get column names as an Index objectcolumn_names = df.columns Get Column Names in Pandas Get a list
3 min read
Pandas dataframe.groupby() Method
Pandas groupby is used for grouping the data according to the categories and applying a function to the categories. It also helps to aggregate data efficiently. The Pandas groupby() is a very powerful function with a lot of variations. It makes the task of splitting the Dataframe over some criteria really easy and efficient. Pandas dataframe groupb
7 min read
Different ways to create Pandas Dataframe
It is the most commonly used Pandas object. The pd. DataFrame() function is used to create a DataFrame in Pandas . You can also create Pandas DataFrame in multiple ways. There are several ways to create a Pandas Dataframe in Python . You can create a DataFrame with the following methods: Different Ways to Create Dataframe in Python Pandas Dataframe
9 min read
Introduction to Recurrent Neural Network
In this article, we will introduce a new variation of neural network which is the Recurrent Neural Network also known as (RNN) that works better than a simple neural network when data is sequential like Time-Series data and text data. What is Recurrent Neural Network (RNN)?Recurrent Neural Network(RNN) is a type of Neural Network where the output f
15+ min read
Linear Regression in Machine learning
Machine Learning is a branch of Artificial intelligence that focuses on the development of algorithms and statistical models that can learn from and make predictions on data. Linear regression is also a type of machine-learning algorithm more specifically a supervised machine-learning algorithm that learns from the labelled datasets and maps the da
15+ min read
Principal Component Analysis(PCA)
As the number of features or dimensions in a dataset increases, the amount of data required to obtain a statistically significant result increases exponentially. This can lead to issues such as overfitting, increased computation time, and reduced accuracy of machine learning models this is known as the curse of dimensionality problems that arise wh
13 min read
Introduction to Deep Learning
In the fast-evolving era of artificial intelligence, Deep Learning stands as a cornerstone technology, revolutionizing how machines understand, learn, and interact with complex data. At its essence, Deep Learning AI mimics the intricate neural networks of the human brain, enabling computers to autonomously discover patterns and make decisions from
11 min read
Reinforcement learning
Reinforcement Learning: An OverviewReinforcement Learning (RL) is a branch of machine learning focused on making decisions to maximize cumulative rewards in a given situation. Unlike supervised learning, which relies on a training dataset with predefined answers, RL involves learning through experience. In RL, an agent learns to achieve a goal in a
8 min read
Agents in Artificial Intelligence
In artificial intelligence, an agent is a computer program or system that is designed to perceive its environment, make decisions and take actions to achieve a specific goal or set of goals. The agent operates autonomously, meaning it is not directly controlled by a human operator. Agents can be classified into different types based on their charac
11 min read
Decision Tree
Decision trees are a popular and powerful tool used in various fields such as machine learning, data mining, and statistics. They provide a clear and intuitive way to make decisions based on data by modeling the relationships between different variables. This article is all about what decision trees are, how they work, their advantages and disadvan
5 min read
Understanding the Confusion Matrix in Machine Learning
Machine learning models are increasingly used in various applications to classify data into different categories. However, evaluating the performance of these models is crucial to ensure their accuracy and reliability. One essential tool in this evaluation process is the confusion matrix. In this article, we will delve into the details of the confu
11 min read
Supervised and Unsupervised learning
Machine learning is a field of computer science that gives computers the ability to learn without being explicitly programmed. Supervised learning and unsupervised learning are two main types of machine learning. In supervised learning, the machine is trained on a set of labeled data, which means that the input data is paired with the desired outpu
15 min read
Introduction to Convolution Neural Network
A Convolutional Neural Network (CNN) is a type of Deep Learning neural network architecture commonly used in Computer Vision. Computer vision is a field of Artificial Intelligence that enables a computer to understand and interpret the image or visual data. When it comes to Machine Learning, Artificial Neural Networks perform really well. Neural Ne
10 min read
Logistic Regression in Machine Learning
Logistic regression is a supervised machine learning algorithm used for classification tasks where the goal is to predict the probability that an instance belongs to a given class or not. Logistic regression is a statistical algorithm which analyze the relationship between two data factors. The article explores the fundamentals of logistic regressi
13 min read
K means Clustering - Introduction
K-Means Clustering is an Unsupervised Machine Learning algorithm, which groups the unlabeled dataset into different clusters. The article aims to explore the fundamentals and working of k mean clustering along with the implementation. Table of Content What is K-means Clustering?What is the objective of k-means clustering?How k-means clustering work
9 min read
K-Nearest Neighbor(KNN) Algorithm
The K-Nearest Neighbors (KNN) algorithm is a supervised machine learning method employed to tackle classification and regression problems. Evelyn Fix and Joseph Hodges developed this algorithm in 1951, which was subsequently expanded by Thomas Cover. The article explores the fundamentals, workings, and implementation of the KNN algorithm. What is t
15+ min read
Naive Bayes Classifiers
A Naive Bayes classifiers, a family of algorithms based on Bayes' Theorem. Despite the "naive" assumption of feature independence, these classifiers are widely utilized for their simplicity and efficiency in machine learning. The article delves into theory, implementation, and applications, shedding light on their practical utility despite oversimp
12 min read