🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Hierarchical Clustering and DBSCAN

Hierarchical clustering builds a tree of groups. DBSCAN builds groups of any shape and leaves odd rows out as noise.

The first joins are the closest pairs

The linkage table lists each join. Rows 9 and 47 join first, at a distance of 1.16.

import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
wine = load_wine()
X = StandardScaler().fit_transform(wine.data)
joins = linkage(X, method="ward")
print([round(float(v), 2) for v in joins[0]])

Three groups from the tree

Cutting the tree at three groups gives sizes of 58, 56, and 64. The groups are nearly even.

from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
wine = load_wine()
X = StandardScaler().fit_transform(wine.data)
model = AgglomerativeClustering(n_clusters=3)
labels = model.fit_predict(X)
print([int((labels == k).sum()) for k in range(3)])

DBSCAN leaves odd rows as noise

With eps 2.0, DBSCAN finds five groups and calls 85 rows noise. The noise rows sit too far from any group.

from sklearn.cluster import DBSCAN
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
wine = load_wine()
X = StandardScaler().fit_transform(wine.data)
labels = DBSCAN(eps=2.0, min_samples=5).fit_predict(X)
print("Clusters:", len(set(labels) - {-1}))
print("Noise:", int((labels == -1).sum()))

Example

import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.cluster import AgglomerativeClustering, DBSCAN
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler

wine = load_wine()
X = StandardScaler().fit_transform(wine.data)

# Hierarchical: the join table, first three joins and the last join.
joins = linkage(X, method="ward")
print("First joins:")
print(np.round(joins[:3], 2))
print("Last join:", [round(float(v), 2) for v in joins[-1]])
agg = AgglomerativeClustering(n_clusters=3)
agg_labels = agg.fit_predict(X)
print("Tree groups:", [int((agg_labels == k).sum()) for k in range(3)])

# DBSCAN: the same data, two values of eps.
for eps in [2.0, 3.0]:
    labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
    print("eps =", eps, "clusters:", len(set(labels) - {-1}), "noise:", int((labels == -1).sum()))

Key points

  • Hierarchical clustering: a method that joins rows into a tree of groups
  • Dendrogram: a tree diagram that shows which rows join first
  • Linkage: the table of joins that builds the tree
  • DBSCAN: a method that groups close rows and calls the rest noise
  • Noise: a row too far from any group to join one
  • eps: the distance that counts as close in DBSCAN
  • Use min_samples to set how many close rows a group needs

In this example, the Wine columns are scaled before anything else, because both methods measure distance. The linkage table shows the first joins, and the last join merges all 178 rows into one group. Cutting the tree at three groups gives sizes of 58, 56, and 64. Then DBSCAN runs twice on the same data. With eps 2.0 it finds five groups and calls 85 rows noise. With eps 3.0 it finds one big group and only 11 rows of noise. A small eps splits the data and leaves many rows out, while a big eps merges nearly everything.

Note

DBSCAN needs scaling first, because it measures distance like K-Means.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

DBSCAN calls a row noise. What does that mean?