DBSCAN Clustering in ML - Density based clustering Last Updated : 18 May, 2025 Comments Improve Suggest changes Like Article Like Report DBSCAN is a density-based clustering algorithm that groups data points that are closely packed together and marks outliers as noise based on their density in the feature space. It identifies clusters as dense regions in the data space separated by areas of lower density. Unlike K-Means or hierarchical clustering which assumes clusters are compact and spherical, DBSCAN perform well in handling real-world data irregularities such as:Arbitrary-Shaped Clusters: Clusters can take any shape not just circular or convex.Noise and Outliers: It effectively identifies and handles noise points without assigning them to any cluster.DBSCAN Clustering in ML | Density based clusteringThe figure above shows a data set with clustering algorithms: K-Means and Hierarchical handling compact, spherical clusters with varying noise tolerance while DBSCAN manages arbitrary-shaped clusters and noise handling.Key Parameters in DBSCAN1. eps: This defines the radius of the neighborhood around a data point. If the distance between two points is less than or equal to eps they are considered neighbors. A common method to determine eps is by analyzing the k-distance graph. Choosing the right eps is important:If eps is too small most points will be classified as noise.If eps is too large clusters may merge and the algorithm may fail to distinguish between them.2. MinPts: This is the minimum number of points required within the eps radius to form a dense region. A general rule of thumb is to set MinPts >= D+1 where D is the number of dimensions in the dataset. For most cases a minimum value of MinPts = 3 is recommended.How Does DBSCAN Work? DBSCAN works by categorizing data points into three types: Core points which have a sufficient number of neighbors within a specified radius (eplison)Border points which are near core points but lack enough neighbors to be core points themselvesNoise points which do not belong to any cluster. By iteratively expanding clusters from core points and connecting density-reachable points, DBSCAN forms clusters without relying on rigid assumptions about their shape or size. Steps in the DBSCAN AlgorithmIdentify Core Points: For each point in the dataset count the number of points within its eps neighborhood. If the count meets or exceeds MinPts mark the point as a core point.Form Clusters: For each core point that is not already assigned to a cluster create a new cluster. Recursively find all density-connected points i.e points within the eps radius of the core point and add them to the cluster.Density Connectivity: Two points a and b are density-connected if there exists a chain of points where each point is within the eps radius of the next and at least one point in the chain is a core point. This chaining process ensures that all points in a cluster are connected through a series of dense regions.Label Noise Points: After processing all points any point that does not belong to a cluster is labeled as noise.Implementation Of DBSCAN Algorithm In Python Here we’ll use the Python library sklearn to compute DBSCAN and matplotlib.pyplot library for visualizing clusters.Step 1: Importing Libraries We import all the necessary library like numpy , matplotlib and scikit-learn. Python import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets import make_blobs from sklearn.preprocessing import StandardScaler from sklearn import datasets Step 2: Preparing Dataset We will create a dataset of 4 clusters using make_blob. The dataset have 300 points that are grouped into 4 visible clusters. Python # Load data in X X, y_true = make_blobs(n_samples=300, centers=4, cluster_std=0.50, random_state=0) Step 3: Applying DBSCAN ClusteringNow we apply DBSCAN clustering on our data, count it and visualize it using the matplotlib library.eps=0.3: The radius to look for neighboring points.min_samples: Minimum number of points required to form a dense region a cluster.labels: Cluster numbers for each point. -1 means the point is considered noise. Python db = DBSCAN(eps=0.3, min_samples=10).fit(X) core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) unique_labels = set(labels) colors = ['y', 'b', 'g', 'r'] print(colors) for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = 'k' class_member_mask = (labels == k) xy = X[class_member_mask & core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) xy = X[class_member_mask & ~core_samples_mask] plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6) plt.title('number of clusters: %d' % n_clusters_) plt.show() Output:Cluster of dataset As shown in above output image cluster are shown in different colours like yellow, blue, green and red.Step 4: Evaluation Metrics For DBSCAN Algorithm In Machine Learning We will use the Silhouette score and Adjusted rand score for evaluating clustering algorithms. Silhouette's score is in the range of -1 to 1. A score near 1 denotes the best meaning that the data point i is very compact within the cluster to which it belongs and far away from the other clusters. The worst value is -1. Values near 0 denote overlapping clusters.Absolute Rand Score is in the range of 0 to 1. More than 0.9 denotes excellent cluster recovery and above 0.8 is a good recovery. Less than 0.5 is considered to be poor recovery. Python sc = metrics.silhouette_score(X, labels) print("Silhouette Coefficient:%0.2f" % sc) ari = adjusted_rand_score(y_true, labels) print("Adjusted Rand Index: %0.2f" % ari) Output:Coefficient:0.13Adjusted Rand Index: 0.31:Black points represent outliers. By changing the eps and the MinPts we can change the cluster configuration.When Should We Use DBSCAN Over K-Means Clustering?DBSCAN and K-Means are both clustering algorithms that group together data that have the same characteristic. However they work on different principles and are suitable for different types of data. We prefer to use DBSCAN when the data is not spherical in shape or the number of classes is not known beforehand. DBSCAN K-Means In DBSCAN we need not specify the number of clusters.It is very sensitive to the number of clusters so it need to specifiedClusters formed in DBSCAN can be of any arbitrary shape.Clusters formed are spherical or convex in shapeIt can work well with datasets having noise and outliersIt does not work well with outliers data. Outliers can skew the clusters in K-Means to a very large extent. In DBSCAN two parameters are required for training the ModelIn K-Means only one parameter is required is for training the modelDBSCAN Vs K-MeansAs it can identify clusters of arbitrary shapes and effectively handle noise. K-Means on the other hand is better suited for data with well-defined, spherical clusters and is less effective with noise or complex cluster structures.More differences between these two algorithms can be found here. Comment More infoAdvertise with us Next Article Apriori Algorithm D Debomit Dey Follow Improve Article Tags : Machine Learning AI-ML-DS ML-Clustering AI-ML-DS With Python Practice Tags : Machine Learning Similar Reads Machine Learning Tutorial Machine learning is a branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data 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.Machin 5 min read Introduction to Machine LearningIntroduction to Machine LearningMachine learning (ML) allows computers to learn and make decisions without being explicitly programmed. It involves feeding data into algorithms to identify patterns and make predictions on new data. It is used in various applications like image recognition, speech processing, language translation, 8 min read Types of Machine LearningMachine 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 h 13 min read What is Machine Learning Pipeline?In artificial intelligence, developing a successful machine learning model involves more than selecting the best algorithm; it requires effective data management, training, and deployment in an organized manner. A machine learning pipeline becomes crucial in this situation. A machine learning pipeli 7 min read Applications of Machine LearningMachine learning is one of the most exciting technologies that one would have ever come across. As is evident from the name, it gives the computer that which makes it more similar to humans: The ability to learn. Machine learning is actively being used today, perhaps in many more places than one wou 5 min read Python for Machine LearningMachine Learning with Python TutorialPython language is widely used in Machine Learning because it provides libraries like NumPy, Pandas, Scikit-learn, TensorFlow, and Keras. These libraries offer tools and functions essential for data manipulation, analysis, and building machine learning models. It is well-known for its readability an 5 min read Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t 6 min read NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens 3 min read Scikit Learn TutorialScikit-learn (also known as sklearn) is a widely-used open-source Python library for machine learning. It builds on other scientific libraries like NumPy, SciPy and Matplotlib to provide efficient tools for predictive data analysis and data mining.It offers a consistent and simple interface for a ra 3 min read ML | Data Preprocessing in PythonData preprocessing is a important step in the data science transforming raw data into a clean structured format for analysis. It involves tasks like handling missing values, normalizing data and encoding variables. Mastering preprocessing in Python ensures reliable insights for accurate predictions 6 min read EDA - Exploratory Data Analysis in PythonExploratory Data Analysis (EDA) is a important step in data analysis which focuses on understanding patterns, trends and relationships through statistical tools and visualizations. Python offers various libraries like pandas, numPy, matplotlib, seaborn and plotly which enables effective exploration 6 min read Feature EngineeringWhat is Feature Engineering?Feature Engineering is the process of creating new features or transforming existing features to improve the performance of a machine-learning model. It involves selecting relevant information from raw data and transforming it into a format that can be easily understood by a model. The goal is to im 14 min read Introduction to Dimensionality ReductionWhen working with machine learning models, datasets with too many features can cause issues like slow computation and overfitting. Dimensionality reduction helps to reduce the number of features while retaining key information. Techniques like principal component analysis (PCA), singular value decom 4 min read Feature Selection Techniques in Machine LearningIn data science many times we encounter vast of features present in a dataset. But it is not necessary all features contribute equally in prediction that's where feature selection comes. It involves selecting a subset of relevant features from the original feature set to reduce the feature space whi 5 min read Feature Engineering: Scaling, Normalization, and StandardizationFeature Scaling is a technique to standardize the independent features present in the data. It is performed during the data pre-processing to handle highly varying values. If feature scaling is not done then machine learning algorithm tends to use greater values as higher and consider smaller values 6 min read Supervised LearningSupervised Machine LearningSupervised machine learning is a fundamental approach for machine learning and artificial intelligence. It involves training a model using labeled data, where each input comes with a corresponding correct output. The process is like a teacher guiding a studentâhence the term "supervised" learning. I 12 min read Linear Regression in Machine learningLinear regression is a type of supervised machine-learning algorithm that learns from the labelled datasets and maps the data points with most optimized linear functions which can be used for prediction on new datasets. It assumes that there is a linear relationship between the input and output, mea 15+ min read Logistic Regression in Machine LearningLogistic Regression is a supervised machine learning algorithm used for classification problems. Unlike linear regression which predicts continuous values it predicts the probability that an input belongs to a specific class. It is used for binary classification where the output can be one of two po 11 min read Decision Tree in Machine LearningA decision tree is a supervised learning algorithm used for both classification and regression tasks. It has a hierarchical tree structure which consists of a root node, branches, internal nodes and leaf nodes. It It works like a flowchart help to make decisions step by step where: Internal nodes re 9 min read Random Forest Algorithm in Machine LearningRandom Forest is a machine learning algorithm that uses many decision trees to make better predictions. Each tree looks at different random parts of the data and their results are combined by voting for classification or averaging for regression. This helps in improving accuracy and reducing errors. 5 min read K-Nearest Neighbor(KNN) AlgorithmK-Nearest Neighbors (KNN) is a supervised machine learning algorithm generally used for classification but can also be used for regression tasks. It works by finding the "k" closest data points (neighbors) to a given input and makesa predictions based on the majority class (for classification) or th 8 min read Support Vector Machine (SVM) AlgorithmSupport Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or 9 min read Naive Bayes ClassifiersNaive Bayes is a classification algorithm that uses probability to predict which category a data point belongs to, assuming that all features are unrelated. This article will give you an overview as well as more advanced use and implementation of Naive Bayes in machine learning. Illustration behind 7 min read Unsupervised LearningWhat is Unsupervised Learning?Unsupervised learning is a branch of machine learning that deals with unlabeled data. Unlike supervised learning, where the data is labeled with a specific category or outcome, unsupervised learning algorithms are tasked with finding patterns and relationships within the data without any prior knowl 8 min read K means Clustering â IntroductionK-Means Clustering is an Unsupervised Machine Learning algorithm which groups unlabeled dataset into different clusters. It is used to organize data into groups based on their similarity. Understanding K-means ClusteringFor example online store uses K-Means to group customers based on purchase frequ 4 min read Hierarchical Clustering in Machine LearningHierarchical clustering is used to group similar data points together based on their similarity creating a hierarchy or tree-like structure. The key idea is to begin with each data point as its own separate cluster and then progressively merge or split them based on their similarity. Lets understand 7 min read DBSCAN Clustering in ML - Density based clusteringDBSCAN is a density-based clustering algorithm that groups data points that are closely packed together and marks outliers as noise based on their density in the feature space. It identifies clusters as dense regions in the data space separated by areas of lower density. Unlike K-Means or hierarchic 6 min read Apriori AlgorithmApriori Algorithm is a basic method used in data analysis to find groups of items that often appear together in large sets of data. It helps to discover useful patterns or rules about how items are related which is particularly valuable in market basket analysis. Like in a grocery store if many cust 6 min read Frequent Pattern Growth AlgorithmThe FP-Growth (Frequent Pattern Growth) algorithm efficiently mines frequent itemsets from large transactional datasets. Unlike the Apriori algorithm which suffers from high computational cost due to candidate generation and multiple database scans. FP-Growth avoids these inefficiencies by compressi 5 min read ECLAT Algorithm - MLECLAT stands for Equivalence Class Clustering and bottom-up Lattice Traversal. It is a data mining algorithm used to find frequent itemsets in a dataset. These frequent itemsets are then used to create association rules which helps to identify patterns in data. It is an improved alternative to the A 3 min read Principal Component Analysis(PCA)PCA (Principal Component Analysis) is a dimensionality reduction technique used in data analysis and machine learning. It helps you to reduce the number of features in a dataset while keeping the most important information. It changes your original features into new features these new features donât 7 min read Model Evaluation and TuningEvaluation Metrics in Machine LearningEvaluation is always good in any field, right? In the case of machine learning, it is best practice. In this post, we will cover almost all the popular as well as common metrics used for machine learning.Table of ContentClassification MetricsAccuracyLogarithmic Loss Area Under Curve (AUC)PrecisionRe 7 min read Regularization in Machine LearningRegularization is an important technique in machine learning that helps to improve model accuracy by preventing overfitting which happens when a model learns the training data too well including noise and outliers and perform poor on new data. By adding a penalty for complexity it helps simpler mode 7 min read Cross Validation in Machine LearningCross-validation is a technique used to check how well a machine learning model performs on unseen data. It splits the data into several parts, trains the model on some parts and tests it on the remaining part repeating this process multiple times. Finally the results from each validation step are a 7 min read Hyperparameter TuningHyperparameter tuning is the process of selecting the optimal values for a machine learning model's hyperparameters. These are typically set before the actual training process begins and control aspects of the learning process itself. They influence the model's performance its complexity and how fas 7 min read ML | Underfitting and OverfittingMachine learning models aim to perform well on both training data and new, unseen data and is considered "good" if:It learns patterns effectively from the training data.It generalizes well to new, unseen data.It avoids memorizing the training data (overfitting) or failing to capture relevant pattern 5 min read Bias and Variance in Machine LearningThere are various ways to evaluate a machine-learning model. We can use MSE (Mean Squared Error) for Regression; Precision, Recall, and ROC (Receiver operating characteristics) for a Classification Problem along with Absolute Error. In a similar way, Bias and Variance help us in parameter tuning and 10 min read Advance Machine Learning TechniqueReinforcement LearningReinforcement Learning (RL) is a branch of machine learning that focuses on how agents can learn to make decisions through trial and error to maximize cumulative rewards. RL allows machines to learn by interacting with an environment and receiving feedback based on their actions. This feedback comes 6 min read Semi-Supervised Learning in MLToday's Machine Learning algorithms can be broadly classified into three categories, Supervised Learning, Unsupervised Learning, and Reinforcement Learning. Casting Reinforced Learning aside, the primary two categories of Machine Learning problems are Supervised and Unsupervised Learning. The basic 4 min read Self-Supervised Learning (SSL)In this article, we will learn a major type of machine learning model which is Self-Supervised Learning Algorithms. Usage of these algorithms has increased widely in the past times as the sizes of the model have increased up to billions of parameters and hence require a huge corpus of data to train 8 min read Ensemble LearningEnsemble learning is a method where we use many small models instead of just one. Each of these models may not be very strong on its own, but when we put their results together, we get a better and more accurate answer. It's like asking a group of people for advice instead of just one personâeach on 8 min read Machine Learning PracticeTop 50+ Machine Learning Interview Questions and AnswersMachine Learning involves the development of algorithms and statistical models that enable computers to improve their performance in tasks through experience. Machine Learning is one of the booming careers in the present-day scenario.If you are preparing for machine learning interview, this intervie 15+ min read 100+ Machine Learning Projects with Source Code [2025]This article provides over 100 Machine Learning projects and ideas to provide hands-on experience for both beginners and professionals. Whether you're a student enhancing your resume or a professional advancing your career these projects offer practical insights into the world of Machine Learning an 5 min read Like