Sub topic 2
Reading a Dendrogram
Assume you know basic Python, NumPy, Euclidean distance, and scikit-learn’s fit style. A dendrogram is a tree that shows how agglomerative clustering merges observations. The leaves at the bottom are individual observations. Each merge is drawn at a height equal to the distance between the clusters being merged.
Cutting the Tree into Flat Clusters
Imagine drawing a horizontal line across the dendrogram. Every connected group below the line becomes one flat cluster. A cut just below height 5.0 produces two clusters. A cut above height 5.0 produces one cluster.
Large vertical gaps between merges can suggest useful cut heights. This is a heuristic, not proof that the resulting clusters are meaningful.
> callout note > Dendrogram leaf order is mainly for display. Nearby leaves in the drawing are not necessarily the nearest observations in the original feature space.
Running Hierarchical Clustering
SciPy exposes the merge tree directly. Scikit-learn is convenient when you already know the desired number of clusters.
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
Z = linkage(X, method="ward")
scipy_labels = fcluster(Z, t=3, criterion="maxclust")
model = AgglomerativeClustering(n_clusters=3, linkage="ward")
sklearn_labels = model.fit_predict(X)
print(Z.shape)
print(sorted(set(scipy_labels)))
print(sorted(set(sklearn_labels)))Z stores the two clusters merged at each step, the merge distance, and the new cluster size. Ward linkage favors compact groups and requires Euclidean features.
Cost and Limits
Hierarchical clustering commonly needs quadratic memory because it tracks many pairwise distances. It becomes impractical for very large datasets. It also commits to every earlier merge. A poor early merge cannot be undone, and different linkage choices can produce very different trees.
Clusters as Dense Regions
DBSCAN uses a different model: a cluster is a connected, dense region separated from sparse space. It can find curved shapes and can mark isolated observations as noise.
- A core point has at least
min_samplespoints within distanceeps, including itself. - A border point is within
epsof a core point but does not meet the core requirement itself. - A noise point is neither core nor connected to a core point.
Exercise
Exercise
If a dendrogram has a large gap between merge heights 2 and 7, where might you try cutting it, and what does DBSCAN call an isolated point?
Show answer
Try a cut between 2 and 7. DBSCAN calls an isolated point noise.