Clustering with Hypertools

Setup: install HyperTools (run this cell first on Colab)
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
    _hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
    _hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
    _spec = importlib.util.find_spec('hypertools')
    if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
        raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
    %pip install -q "hypertools[interactive]>=1.1.0"
else:
    print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')

The cluster feature performs clustering analysis on the data (an array, dataframe, or list) and returns a list of cluster labels.

The default clustering model is K-Means (argument ‘KMeans’). Also supported: AffinityPropagation, AgglomerativeClustering, BayesianGaussianMixture, Birch, DBSCAN, FeatureAgglomeration, GaussianMixture, HDBSCAN, LatentDirichletAllocation, MeanShift, MiniBatchKMeans, NMF, OPTICS, and SpectralClustering. (Note that FeatureAgglomeration clusters the features – columns – rather than the observations.)

Note that, if a list is passed, the arrays will be stacked and clustering will be performed across all lists (not within each list).

Import Packages

[1]:
import hypertools as hyp
from collections import Counter

%matplotlib inline

Load your data

We will load one of the sample datasets. This dataset consists of 8,124 samples of mushrooms with various text features.

[2]:
mushrooms = hyp.load('mushrooms')

We can peek at the first few rows of the dataframe using the pandas function head()

[3]:
mushrooms.head()
[3]:
bruises cap-color cap-shape cap-surface gill-attachment gill-color gill-size gill-spacing habitat odor ... ring-type spore-print-color stalk-color-above-ring stalk-color-below-ring stalk-root stalk-shape stalk-surface-above-ring stalk-surface-below-ring veil-color veil-type
0 t n x s f k n c u p ... p k w w e e s s w p
1 t y x s f k b c g a ... p n w w c e s s w p
2 t w b s f n b c m l ... p n w w c e s s w p
3 t w x y f n n c u p ... p k w w e e s s w p
4 f g x s f k b w g n ... e n w w e t s s w p

5 rows × 22 columns

Obtain cluster labels

To obtain cluster labels, simply pass the data to hyp.cluster. Since we have not specified a desired number of clusters, the default of 3 clusters is used (labels 0, 1, and 2). Additionally, since we have not specified a desired clustering algorithm, K-Means is used by default. K-Means starts from random centroids, so random_state=0 fixes them: the labels, and the counts below, are then the same on every run.

Every column of this dataframe holds categorical strings, so format_data dummy-codes them first (one 0/1 column per category value, turning the 22 original columns into 117) and K-means sees that numeric matrix.

[4]:
labels = hyp.cluster(mushrooms, random_state=0)
set(labels)
[4]:
{0, 1, 2}

We can further examine the number of datapoints assigned each label.

[5]:
Counter(labels)
[5]:
Counter({2: 5067, 1: 1761, 0: 1296})

Specify number of cluster labels

You can also specify the number of desired clusters by setting the n_clusters argument to an integer number of clusters, as below. We can see that when we pass the int 10 to n_clusters, 10 cluster labels are assigned.

Since we have not specified a desired clustering algorithm, K-Means is used by default.

[6]:
labels_10 = hyp.cluster(mushrooms, n_clusters=10, random_state=0)
set(labels_10)
[6]:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Different clustering models

You may prefer to use a clustering model other than K-Means. To do so, simply pass a string to the cluster argument specifying the desired clustering algorithm.

In this case, we specify the clustering model (HDBSCAN). Note that HDBSCAN determines the number of clusters directly from the data, so we don’t pass n_clusters (it would be ignored).

[7]:
labels_HDBSCAN = hyp.cluster(mushrooms, cluster='HDBSCAN')
[8]:
fig = hyp.plot(mushrooms, '.', hue=[f'cluster {label}' for label in labels_10],
               legend=True, title='K-means clustering')
fig2 = hyp.plot(mushrooms, '.', hue=[f'cluster {label}' for label in labels_HDBSCAN],
               legend=True, title='HDBSCAN clustering')
../_images/tutorials_cluster_21_0.png
../_images/tutorials_cluster_21_1.png

Feeding the cluster labels back in as hue colors each point by its cluster. The labels here are strings ('cluster 0', 'cluster 1', and so on), which sends hue down the categorical path, so each cluster gets its own discrete color; legend=True then names those clusters in the legend.

Note that hyp.plot(mushrooms, cluster='HDBSCAN') would produce a colored-by-cluster figure in a single call, but the two are not equivalent. plot clusters the 3-D reduced coordinates it is about to draw, whereas hyp.cluster(mushrooms, cluster='HDBSCAN') above clustered the full 117-column feature space.