hdbscan Documentation

repository·master·Indexed 25 days ago

https://github.com/scikit-learn-contrib/hdbscan

A fast and robust hierarchical density-based clustering algorithm designed for exploratory data analysis and integration with the scikit-learn ecosystem. Version 0.8.44 provides the hdbscan.HDBSCAN class for clustering with variable density, tools for visualizing cluster hierarchies via CondensedTree and SingleLinkageTree, and modules for validity assessment, prediction, and branch detection.

Tokens
23.7K
Snippets
42
Records
131
Agent score
84%

What's inside hdbscan

  1. Overview of the hdbscan Clustering Library

    master
    The hdbscan library is a suite of tools for unsupervised learning designed to find clusters or dense regions within a dataset. It provides a high-performance implementation of the HDBSCAN* algorithm (as proposed by Campello, Moulavi, and Sander) and includes additional tools for analyzing the resulting clusters.
  2. Overview of HDBSCAN capabilities

    master

    HDBSCAN (Hierarchical Density-Based Spatial Clustering of Applications with Noise) is an unsupervised machine learning algorithm for clustering. Unlike DBSCAN, which uses a single epsilon value, HDBSCAN performs DBSCAN over varying epsilon values and integrates the results to find a clustering that provides the best stability. This enables the algorithm to identify clusters of varying densities and increases robustness to parameter selection.

    Key features include:

    • Clustering: Finds clusters of varying densities.
    • Robust Single Linkage: Support for robust single linkage clustering.
    • Outlier Detection: Includes GLOSH (Global-Local Outlier Score from Hierarchies) outlier detection.
    • Cluster Exploration: Tools for visualizing and exploring cluster structures.
    • Advanced Clustering: Support for prediction and soft clustering.
  3. Use DBSCAN for density-based clustering

    master

    DBSCAN extracts dense clusters and classifies sparse background points as 'noise'. It requires tuning eps (epsilon, a distance threshold) and min_samples.

    Limitations:

    • eps can be difficult to choose and the algorithm is sensitive to it.
    • It struggles with datasets containing clusters of varying densities; it may miss sparse clusters or lump dense clusters together depending on the parameters.
    plot_clusters(data, cluster.DBSCAN, (), {'eps':0.025})
  4. Select `alpha` for HDBSCAN*

    master

    The alpha parameter (default 1.0) provides an alternative way to control how conservative the clustering is.

    • Increasing alpha: Makes the clustering more conservative on a tight scale.

    Note: It is recommended to prioritize tuning min_samples or cluster_selection_epsilon before adjusting alpha. Adjusting alpha requires recomputing the single linkage tree.

  5. Use HDBSCAN for varying density clustering

    master

    HDBSCAN is an evolution of DBSCAN designed to handle clusters of varying densities. It eliminates the need for an eps parameter by using a condensed tree approach to find stable clusters.

    Key Parameters:

    • min_cluster_size: The minimum number of points to consider a group a cluster. This is considered an intuitive parameter for EDA.
    • min_samples: Inherited from DBSCAN for density-based space transformation. While less intuitive, the algorithm is generally not highly sensitive to it.

    Advantages:

    • Handles varying densities.
    • Identifies noise.
    • Stable across runs and subsampling.
    • High performance (can utilize fastcluster if available).
    import hdbscan
    
    plot_clusters(data, hdbscan.HDBSCAN, (), {'min_cluster_size':15})
  6. Set up environment for clustering comparison

    master

    To compare clustering algorithms, you need numpy, matplotlib, seaborn, and scikit-learn. This setup includes configuring seaborn for better visualization and defining standard plotting keyword arguments.

    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    import sklearn.cluster as cluster
    import time
    %matplotlib inline
    sns.set_context('poster')
    sns.set_color_codes()
    plot_kwds = {'alpha' : 0.25, 's' : 80, 'linewidths':0}
  7. Analyze clustering scaling trends with Seaborn

    master
    To visualize how clustering algorithms scale with dataset size, use seaborn.regplot. Since most clustering algorithms exhibit quadratic scaling, using order=2 in regplot helps fit a meaningful curve. Using x_estimator=np.mean allows you to handle multiple timing data points for the same dataset size by plotting the mean and an error bar.
  8. Identify points with ambiguous cluster membership

    master

    You can identify 'mixed' points (points that have a high likelihood of belonging to two different clusters) by analyzing the membership vectors. A common approach is to find points where the difference between the top two probabilities is very small, but the total sum of probabilities is high.

    import numpy as np
    
    def top_two_probs_diff(probs):
        sorted_probs = np.sort(probs)
        return sorted_probs[-1] - sorted_probs[-2]
    
    # Compute the differences between the top two probabilities
    diffs = np.array([top_two_probs_diff(x) for x in soft_clusters])
    
    # Select indices with a small difference and a large total probability
    mixed_points = np.where((diffs < 0.001) & (np.sum(soft_clusters, axis=1) > 0.5))[0]
  9. Detect branches in custom clusters using BranchDetector.fit()

    master

    You can use the BranchDetector class to find branches within clusters that were not generated by HDBSCAN (for example, labels from DBSCAN). To do this, pass the HDBSCAN clusterer object and your custom labels to the .fit() method.

    Requirement: Custom clusters must be within-cluster-path-connected in HDBSCAN's Minimum Spanning Tree (MST). This means the MST edges between all points in the cluster must form a single connected component. If the custom clusters break this condition, the detector will return MST connected component labels instead of branches.

    # Valid option: merging clusters manually to find new branching structures
    custom_labels = clusterer.labels_.copy()
    custom_labels[clusterer.labels_ == 3] = 2
    branch_detector.fit(clusterer, custom_labels)
    plot(branch_detector.labels_)
  10. Combine Distance and Outlier Membership (The Middle Way)

    master

    To improve soft clustering, you can combine distance-based membership (locality-oriented) and outlier-based membership (cluster-oriented) using a Bayesian approach. This treats the membership vectors as probability mass functions (PMFs) and multiplies them to get a combined posterior distribution.

    This method helps cluster membership follow manifolds while allowing noise points near clusters to retain some appropriate hue.

    # Combining distance-based and outlier-based membership
    def combined_membership_vector(point, data, tree, exemplar_dict, cluster_ids, 
                                   max_lambda_dict, point_dict, softmax=False):
        raw_tree = tree._raw_tree
        dist_vec = dist_membership_vector(point, exemplar_dict, data, softmax)
        outl_vec = outlier_membership_vector(point, cluster_ids, raw_tree, 
                                             max_lambda_dict, point_dict, softmax)
        result = dist_vec * outl_vec
        result /= result.sum()
        return result
  11. Perform basic clustering with HDBSCAN*

    master

    HDBSCAN follows the scikit-learn API. To cluster data, instantiate an hdbscan.HDBSCAN object and call .fit(data).

    Results are stored in the .labels_ attribute:

    • Integers starting from 0 represent cluster assignments.
    • The value -1 indicates noise (samples not assigned to any cluster).

    Additionally, you can access soft clustering membership scores via the .probabilities_ attribute. These scores range from 0.0 (noise) to 1.0 (core of the cluster).