The Wayback Machine - https://web.archive.org/web/20240824204434/https://www.geeksforgeeks.org/hdbscan/
Open In App

Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN)

Last Updated : 15 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Clustering is a machine-learning technique that divides data into groups, or clusters, based on similarity. By putting similar data points together and separating dissimilar points into separate clusters, it seeks to uncover underlying structures in datasets.

In this article, we will focus on the HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise) technique. Like other clustering methods, HDBSCAN begins by determining the proximity of the data points, distinguishing the regions with high density from sparse regions. But what distinguishes HDBSCAN from other methods is its capacity to dynamically adjust to the different densities and forms of clusters in the data, producing more reliable and adaptable clustering results.

What is HDBSCAN?

HDBSCAN is a clustering algorithm that is designed to uncover clusters in datasets based on the density distribution of data points. Unlike some other clustering methods, it doesn’t requires specifying the number of clusters in advance, making it more adaptable to different datasets. It uses high-density regions to identify clusters and views isolated or low-density points as noise. HDBSCAN is especially helpful for datasets with complex structures or varying densities because it creates a hierarchical tree of clusters that enable users to examine the data at different levels of granularity.

How does HDBSCAN work?

HDBSAN examines the density of the data points in the dataset. It starts by calculating a density-based clustering hierarchy, which creates clusters from densely connected data points. This hierarchical structure enables the recognition of clusters of various shapes and sizes.

The algorithm then extracts clusters from the hierarchy, taking into the account the stability of cluster assignments across different levels of the hierarchy. It identifies stable clusters as those with consistent memberships at multiple levels, ensuring cluster formation robustness.

In addition, HDBSCAN differentiates between noise and meaningful clusters by taking into account points with the low densities or the ones not belonging to any cluster. HDBSCAN captures and eliminates the noise by constantly adjusting the minimum cluster size parameter and adding a minimum spanning tree.

Parameters of HDBSCAN

HDBSCAN has a number of parameters that can be adjusted to modify the clustering process to the specific dataset. Here are some of the main paramters:

  • ‘min_cluster_size’: This parameter sets the minimum number of points required to form a cluster. Points that do not meet this criterion are consiered noise. Adjusting this paramater influences the granularity of the clusters found by the algoirthm.
  • ‘min_samples’: It sets the minimum nmber of samles in a neighborhood for a point to be considered a core point.
  • ‘cluster_selection_epsilon’: This parameter sets the epsilon value for selecting clusters based on the minimum spanning tree. It determines the maximum distances allowed between the points for them to be considered connected in the density-based clustering process.
  • ‘metric’: The distance metric to use for computing mutual reachability distance.
  • ‘cluster_selection_method’: This method is used to choose clusters from the condensed tree. It can be ‘eom'(Excess of Mass’), ‘leaf’ (cluster Tree Leaf) , ‘Leaf-dm'(Leaf with Distance Metric) or ‘flat'(Flat clustering).
  • ‘alpha’: A parameter that influcences the linkage criterion for clustering merging.
  • ‘gen_min_span_tree’: If the parameter is true, it generate the minimum spanning tree for later use.
  • ‘metric_params’: It is an additional keyword arguments for the metric function.
  • ‘algorithm’: The algorithm to use fo the mutual reachibility distance computation. Options include ‘best’, ‘generic’, ‘prime_kdtree’, and ‘boruvka_kdtree’.
  • ‘core_distance_n_jobs’: The number of parallel jobs to run for core distance calculation.
  • ‘allow_single_cluster’: A boolean indicating whether to allow single cluster outputs.

Implementation of HDBSCAN Clustering Algorithm

Installing necessary libraries

pip install hdbscan


Importing Libraries

Let’s see the implementation of HDBSCAN Clustering.

First, we will be importing the necessary libraries that includes numpy, sklearn.datasets, matplolib, hdbscan and metrics like silhouette_score, adjusted rand index for evaluating the metrics.

Python3
import hdbscan
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score, adjusted_rand_score


Generating Sample dataset

This code snippet creates a synthetic dataset (X) with 1000 data points distributed across five clusters. The clusters have a standard deviation of 0.6, ensuring some variance within each cluster, and are generated using a fixed random seed (random_state=42) to ensure reproducibility.

Python3
# Generate sample data
X, y_true = make_blobs(n_samples=1000, centers=5,
                       cluster_std=0.6, random_state=42)


Applying HDBSCAN with parameters

This code initializes the HDBSCAN clustering algorithm with the following parameters: min_cluster_size specifies the minimum number of samples required to form a cluster, min_samples specifies the minimum number of samples in a neighborhood for a point to be considered a core point, and cluster_selection_method specifies the method used to select clusters from the condensed tree, with ‘eom’ representing Excess of Mass. Other parameters affect the metric, algorithm, leaf size, and whether or not single clusters are allowed.

Python3
# Initialize HDBSCAN with additional parameters
clusterer = hdbscan.HDBSCAN(min_cluster_size=5,
                            min_samples=5,
                            cluster_selection_method='eom',
                            allow_single_cluster=True,
                            metric='euclidean',
                            algorithm='best',
                            leaf_size=30)


Fitting the model

This code applies the initialized HDBSCAN model to the input data X and performs the clustering process.

Python3
# Fit the model to the data
clusterer.fit(X)


Evaluate Clustering

This code assesses the clustering results by calculating the silhouette score and adjusted Rand index. It compares the predicted labels (labels) obtained from clustering to the true labels (y_true), if any, and prints both evaluation metrics.

Python3
# Evaluate clustering
labels = clusterer.labels_
silhouette_avg = silhouette_score(X, labels)
ari = adjusted_rand_score(y_true, labels)

# Evaluation metrics
print("Silhouette Coefficient: {:.2f}".format(silhouette_avg))
print("Adjusted Rand Index: {:.2f}".format(ari))

Output:

Silhouette Coefficient: 0.77
Adjusted Rand Index: 0.99





A Silhouette Coefficient of 0.77 indicates that the clustering is well-separated, with samples being assigned to the correct clusters. An Adjusted Rand Index of 0.99 indicates a very high similarity between the two clusterings being compared. Both metrics suggest that the clustering results are strong.

Visualizing the clusters

Python3
# Visualize the clusters
plt.figure(figsize=(10, 6))
plt.scatter(X[:, 0], X[:, 1], c=clusterer.labels_,
            cmap='viridis', s=50, alpha=0.7, edgecolors='k')
plt.colorbar()
plt.title('HDBSCAN Clustering')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.show()

Output:

Hdbscan-Geeks for geeks

Here, in this code it generates a scatter plot to visualize the clustering results. Each data point is represented by a marker, whose color indicates the cluster label assigned by HDBSCAN. The cmap parameter specifies the colormap for coloring the clusters, while s controls the marker size. Finally, labels, titles, and axes are added to the plot to make it clearer.

Advantages of HDBSCAN Clustering

Some of the advantages of HDBSCAN Clustering are:

  • Automatic cluster Discovery: It automatically determines the number of clusters in the dataset without requiring a prior specification, making it suitable for datasets with varying densities and complex structures.
  • Handling Cluster Shapes: It can identify clusters of varying shapes and sizes, including clusters that are non-convex and have irregular shapes.
  • Hierarchical Clustering: HDBSCAN constructs a hierarchical clustering structure allowing exploration of clusters at different levels of granularity, providing valuable insights into the data’s underlying structure.

Disadvantages of HDBSCAN Clustering

  • Computationally Intensive: HDBSCAN can be computationally expensive, particularly for large datasets, due to the construction of the minimum spanning tree and the calculation of mutual reachability distances.
  • Sensitive to Distance metric: In HDBSCAN, the distance metric used can influence the clustering results. Some distance metrics may not accurately capture the data’s underlying structure, resulting in suboptimal clustering results.
  • Parameter Sensitivity: Although HDBSCAN is less sensitive to parameter settings than some other clustering algorithms, it still requires parameter tuning, particularly for the minimum cluster size and minimum sample parameters, which can influence clustering results.


Similar Reads

DBSCAN Clustering in ML | Density based clustering
Clustering analysis or simply Clustering is basically an Unsupervised learning method that divides the data points into a number of specific batches or groups, such that the data points in the same groups have similar properties and data points in different groups have different properties in some sense. It comprises many different methods based on
7 min read
Difference between Hierarchical and Non Hierarchical Clustering
Hierarchical Clustering: Hierarchical clustering is basically an unsupervised clustering technique which involves creating clusters in a predefined order. The clusters are ordered in a top to bottom manner. In this type of clustering, similar clusters are grouped together and are arranged in a hierarchical manner. It can be further divided into two
2 min read
Hierarchical Clustering in R Programming
Hierarchical clustering in R Programming Language is an Unsupervised non-linear algorithm in which clusters are created such that they have a hierarchy(or a pre-determined ordering). For example, consider a family of up to three generations. A grandfather and mother have their children that become father and mother of their children. So, they all a
3 min read
Difference between K means and Hierarchical Clustering
k-means is method of cluster analysis using a pre-specified no. of clusters. It requires advance knowledge of 'K'. Hierarchical clustering also known as hierarchical cluster analysis (HCA) is also a method of cluster analysis which seeks to build a hierarchy of clusters without having fixed number of cluster. Main differences between K means and Hi
2 min read
Hierarchical clustering using Weka
In this article, we will see how to utilize the Weka Explorer to perform hierarchical analysis. The sample data set for this example is based on iris data in ARFF format. The data has been appropriately preprocessed, as this article expects. This dataset has 150 iris occurrences. Clustering: Clustering is the method of dividing a set of abstract ob
3 min read
Structured vs Unstructured Ward in Hierarchical Clustering Using Scikit Learn
Hierarchical clustering is a popular and widely used method for grouping and organizing data into clusters. In hierarchical clustering, data points are grouped based on their similarity, with similar data points being placed in the same cluster and dissimilar data points being placed in different clusters. One of the key decisions in hierarchical c
3 min read
Creating Heatmaps with Hierarchical Clustering
Before diving into our actual topic, let's have an understanding of Heatmaps and Hierarchical Clustering. HeatmapsHeatmaps are a powerful data visualization tool that can reveal patterns, relationships, and similarities within large datasets. When combined with hierarchical clustering, they become even more insightful. In this brief article, we'll
9 min read
Hierarchical Clustering in Data Mining
A Hierarchical clustering method works via grouping data into a tree of clusters. Hierarchical clustering begins by treating every data point as a separate cluster. Then, it repeatedly executes the subsequent steps: Identify the 2 clusters which can be closest together, andMerge the 2 maximum comparable clusters. We need to continue these steps unt
5 min read
Hierarchical Clustering in Machine Learning
In data mining and statistics, hierarchical clustering analysis is a method of clustering analysis that seeks to build a hierarchy of clusters i.e. tree-type structure based on the hierarchy. In machine learning, clustering is the unsupervised learning technique that groups the data based on similarity between the set of data. There are different-d
7 min read
Hierarchical Clustering with Scikit-Learn
Hierarchical clustering is a popular method in data science for grouping similar data points into clusters. Unlike other clustering techniques like K-means, hierarchical clustering does not require the number of clusters to be specified in advance. Instead, it builds a hierarchy of clusters that can be visualized as a dendrogram. In this article, w
4 min read
Difference between CURE Clustering and DBSCAN Clustering
Clustering is a technique used in Unsupervised learning in which data samples are grouped into clusters on the basis of similarity in the inherent properties of the data sample. Clustering can also be defined as a technique of clubbing data items that are similar in some way. The data items belonging to the same clusters are similar to each other i
2 min read
Difference Between Agglomerative clustering and Divisive clustering
Hierarchical clustering is a popular unsupervised machine learning technique used to group similar data points into clusters based on their similarity or dissimilarity. It is called "hierarchical" because it creates a tree-like hierarchy of clusters, where each node represents a cluster that can be further divided into smaller sub-clusters. There a
5 min read
Time Series Clustering: Techniques and Applications
Time series clustering is a powerful unsupervised learning technique used to group similar time series data points based on their characteristics. This method is essential in various domains, including finance, healthcare, meteorology, and retail, where understanding patterns over time can lead to valuable insights. This article delves into the tec
8 min read
Social Network Analysis Based on BSP Clustering Algorithm
Social Network Analysis (SNA) is a powerful tool used to study the relationships and interactions within a network of individuals, organizations, or other entities. It helps in uncovering patterns, identifying influential nodes, and understanding the overall structure of the network. One of the critical aspects of SNA is the ability to cluster simi
6 min read
Clustering Based Algorithms in Recommendation System
Recommendation systems have become an essential tool in various industries, from e-commerce to streaming services, helping users discover products, movies, music, and more. Clustering-based algorithms are a powerful technique used to enhance these systems by grouping similar users or items, enabling more personalized and accurate recommendations. T
5 min read
Spatial Segregation in Social Networks
Prerequisite - Introduction to Social Networks Segregation refers to the act of separation of people from others or the main group. Spatial Segregation refers to the distribution of social groups or any other elements in space. In Spatial Segregation, people tend to migrate to other places where they have more neighbors who are like them. According
6 min read
Spatial intelligence in AI
Spatial Intelligence is the capacity to manipulate, perceive, and reason about spatial dimensions and relationships. In AI, spatial intelligence refers to the capability of algorithms and systems to process and understand the physical space around them. In this article, we are going to explore more about Spatial Intelligence and AI. Table of Conten
5 min read
What is Spatial Analysis?
Have you ever wondered how city planners decide where to build schools, hospitals, or parks? How did authorities track and manage the spread of COVID-19 to contain the outbreak effectively? How are vaccination strategies devised and monitored to ensure equitable distribution? How are such precise maps created, and how does our GPS know the best rou
9 min read
Gaussian Process Regression (GPR) with Noise-Level Estimation
GPR is a machine learning technique capable of modeling complex nonlinear relationships between input and output variables. GPR can also estimate the level of noise in data, which is useful when dealing with noisy or uncertain observations. In this response, I will explain some fundamental GPR concepts and demonstrate how to use Scikit Learn to per
14 min read
How to handle Noise in Machine learning?
Random or irrelevant data that intervene in learning's is termed as noise. What is noise?In Machine Learning, random or irrelevant data can result in unpredictable situations that are different from what we expected, which is known as noise. It results from inaccurate measurements, inaccurate data collection, or irrelevant information. Similar to h
5 min read
Train Neural Networks With Noise to Reduce Overfitting
Neural networks have revolutionized artificial intelligence but they often fall into the trap of overfitting which may potentially reduce the model’s accuracy and reliability. To address this issue, we will be uncovering the noise-based regularization technique, that can help us to reduce overfitting. Table of Content Training Neural Networks With
7 min read
Noise injection for training artificial neural networks
In the training of artificial neural networks, noise injection is a technique used to improve the generalization capabilities of a model. By deliberately adding randomness to the input data or internal components during the training phase, the model becomes more robust to slight variations and noise in real-world data. In this tutorial will delve i
11 min read
What is the role of noise contrastive estimation (NCE) in training diffusion models for image generation?
In recent years, the field of image generation has seen significant advancements, largely due to the development of sophisticated models and training techniques. One such technique that has garnered attention is Noise Contrastive Estimation (NCE). The article delves into the role of NCE in training diffusion models for image generation and explaini
8 min read
Hierarchical linear regression using R
Linear Regression model is used to establish a connection between two or more variables. These variables are either dependent or independent. Linear Regression In R Programming Language is used to give predictions based on the given data about a particular topic, It helps us to have valuable insights and give conclusions that help us in many future
9 min read
Hierarchical Planning in AI
Hierarchical Planning in Artificial Intelligence is a problem-solving and decision-making technique employed to reduce the computational expense associated with planning. The article provides an overview of hierarchical planning in AI, discussing its components, techniques, applications in autonomous driving and robotics, advantages, and challenges
9 min read
Non Parametric Density Estimation Methods in Machine Learning
Non-parametric methods: Similar inputs have similar outputs. These are also called instance-based or memory-based learning algorithms. There are 4 Non - parametric density estimation methods: Histogram EstimatorNaive EstimatorKernel Density Estimator (KDE)KNN estimator (K - Nearest Neighbor Estimator)Histogram Estimator It is the oldest and the mos
5 min read
Histograms and Density Plots in R
A histogram is a graphical representation that organizes a group of data points into user-specified ranges and an approximate representation of the distribution of numerical data. In R language the histogram is built with the use of the hist() function. Syntax: hist(v,main,xlab,xlim,ylim,breaks,col,border) Parameters: v:- It is a vector containing
3 min read
Probability Density Estimation & Maximum Likelihood Estimation
Prerequisite: Probability Distribution Probability Density: Assume a random variable x that has a probability distribution p(x). The relationship between the outcomes of a random variable and its probability is referred to as the probability density.  The problem is that we don't always know the full probability distribution for a random variable.
6 min read
What is the difference between word-based and char-based text generation RNNs?
Answer: Word-based RNNs generate text based on words as units, while char-based RNNs use characters as units for text generation.Word-based RNNs emphasizing semantic meaning and higher-level structures, while char-based RNNs excel in capturing finer character-level patterns. AspectWord-based RNNsChar-based RNNsUnit of ProcessingOperates on words as
2 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
three90RightbarBannerImg