TExcelTAD
Home › Machine Learning › ML Hierarchical Clustering

ML Hierarchical Clustering

Every model so far learned from labelled examples: we knew the right answer (price, hike or not) for each training row. That is supervised learning. Sometimes there are no labels at all — you just have a pile of data and want to know which items belong together. Finding groups without labels is clustering, a form of unsupervised learning.

Hierarchical clustering builds the groups step by step, from the bottom up (this version is called agglomerative):

  1. Start with every point as its own cluster.
  2. Find the two closest clusters and merge them.
  3. Repeat until only one cluster is left.

The full history of merges forms a tree called a dendrogram. Cutting the tree at some height gives you the clusters.

The data

Imagine a café chain with 10 loyalty-card customers, described by how many visits they make per month and how much they spend per visit:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

visits = np.array([2, 3, 2.5, 12, 14, 13, 6, 7, 6.5, 15])
spend = np.array([18, 22, 20, 5, 6, 4.5, 12, 11, 13, 5.5])

plt.scatter(visits, spend)
for i, (x, y) in enumerate(zip(visits, spend)):
    plt.annotate(str(i), (x + 0.2, y + 0.3))
plt.xlabel("Visits per month")
plt.ylabel("Spend per visit")
plt.show()
print("10 customers plotted, numbered 0-9")
10 customers plotted, numbered 0-9

Your eye probably sees three groups: rare big spenders, frequent small spenders, and a middle group. Let's see if the algorithm agrees.

Building the dendrogram with SciPy

scipy.cluster.hierarchy.linkage performs the merges and dendrogram draws them. The linkage method decides how the distance between two clusters is measured; "ward" merges the pair that increases the within-cluster variance the least, and is a good default:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram

visits = np.array([2, 3, 2.5, 12, 14, 13, 6, 7, 6.5, 15])
spend = np.array([18, 22, 20, 5, 6, 4.5, 12, 11, 13, 5.5])
data = np.column_stack([visits, spend])

merges = linkage(data, method="ward", metric="euclidean")
dendrogram(merges)
plt.xlabel("Customer")
plt.ylabel("Merge distance")
plt.show()

print("first three merges (cluster a, cluster b, distance, size):")
print(merges[:3].round(2))
first three merges (cluster a, cluster b, distance, size):
[[6.   8.   1.12 2.  ]
 [3.   5.   1.12 2.  ]
 [4.   9.   1.12 2.  ]]

Read the dendrogram from the bottom: short vertical lines mean very similar customers that merged early. The tall lines near the top join clusters that are far apart. Cutting the tree horizontally just below those tall lines leaves three branches — three clusters.

In the linkage result, each row is one merge. Indices 0–9 are the original customers; index 10 is the cluster created by the first merge, 11 by the second, and so on.

Getting cluster labels

fcluster cuts the tree for you. With criterion="maxclust" you ask for a fixed number of clusters:

python · try it yourself
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster

visits = np.array([2, 3, 2.5, 12, 14, 13, 6, 7, 6.5, 15])
spend = np.array([18, 22, 20, 5, 6, 4.5, 12, 11, 13, 5.5])
merges = linkage(np.column_stack([visits, spend]), method="ward")

labels = fcluster(merges, t=3, criterion="maxclust")
print("labels:", labels)
for c in sorted(set(labels)):
    members = np.where(labels == c)[0]
    print(f"cluster {c}: customers {members.tolist()}")
labels: [3 3 3 1 1 1 2 2 2 1]
cluster 1: customers [3, 4, 5, 9]
cluster 2: customers [6, 7, 8]
cluster 3: customers [0, 1, 2]

The scikit-learn way

AgglomerativeClustering gives the same result with the familiar scikit-learn interface. Because there is no target, fit_predict(X) takes only X:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering

visits = np.array([2, 3, 2.5, 12, 14, 13, 6, 7, 6.5, 15])
spend = np.array([18, 22, 20, 5, 6, 4.5, 12, 11, 13, 5.5])
X = np.column_stack([visits, spend])

model = AgglomerativeClustering(n_clusters=3, linkage="ward")
labels = model.fit_predict(X)
print("labels:", labels)

plt.scatter(visits, spend, c=labels, cmap="viridis", s=60)
plt.xlabel("Visits per month")
plt.ylabel("Spend per visit")
plt.show()
print("Customers coloured by cluster")
labels: [0 0 0 1 1 1 2 2 2 1]
Customers coloured by cluster

The label numbers may differ from SciPy's (cluster "1" in one library might be cluster "2" in another) — only the grouping matters.

Linkage methods compared

Linkage Distance between two clusters
ward increase in total within-cluster variance
single distance between the two closest points
complete distance between the two farthest points
average average distance between all pairs

single linkage tends to produce long chains; ward and complete make compact, round groups.

Tip: Clustering uses distances, so scale your features first when they have different units (see the Scale lesson). Here both features happen to be in similar ranges.

Test yourself

Why is clustering called unsupervised learning?

  1. It needs no computer
  2. The data has no target labels
  3. It always uses decision trees
  4. It cannot make mistakes

How does agglomerative clustering start?

  1. All points in one cluster
  2. Every point in its own cluster
  3. With k random centres
  4. With a decision tree

In a dendrogram, what does a very tall vertical line before a merge suggest?

  1. The two clusters are very similar
  2. The two clusters are far apart
  3. There is an error in the data
  4. There are exactly two points