Sub topic 12
Clustering the matrix and reading a dendrogram
This chapter assumes you can build a similarity matrix from a set of sorts, as in the previous chapter. It also assumes you can run a short Python script with NumPy, SciPy and Matplotlib installed. A similarity matrix with 60 cards has 1,770 pairs, which is too many to scan by eye. Hierarchical clustering turns it into a tree that shows which cards belong together and how strongly.
From similarity to distance
Clustering algorithms work on distance, where small means close. Your matrix holds similarity, the share of participants who put two cards together. The conversion is distance = 1 - similarity. Cards that every participant grouped together are 0 apart. Cards that nobody grouped together are 1 apart.
SciPy's linkage function does not accept a square matrix as a distance matrix. If you pass one, it treats each row as a point in space and measures distances between the rows, and the result looks plausible but is wrong. Convert the matrix to condensed form first. This is a flat array holding the upper triangle without the diagonal. squareform does the conversion.
How agglomerative clustering works
Hierarchical clustering, in its agglomerative form, starts with every card as its own cluster. It then repeats one step: find the two closest clusters and merge them. It records the distance at which each merge happened. After n − 1 merges, one cluster holds everything. The list of merges is the tree.
The only open question is how to measure the distance between two clusters that each contain several cards. That choice is the linkage method.
| Method | Cluster distance is | Tendency |
|---|---|---|
| Single | The closest pair of cards, one from each cluster | Chains. One loosely shared card can pull unrelated groups together. |
| Complete | The farthest pair of cards | Compact groups, but one outlier card can block a merge. |
| Average | The mean of all cross-cluster pair distances | A balance between the two. The usual default for card sorts. |
Ward's method needs raw Euclidean coordinates. It is not appropriate for a precomputed card-sort distance matrix, so don't use it here.
Running the clustering
The script below uses the four-card matrix from the previous chapter.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
cards = ["Shipping rates", "Track order", "Returns", "Gift cards"]
# Share of participants who put each pair of cards together (symmetric, 1 on the diagonal)
similarity = np.array([
[1.00, 1.00, 0.67, 0.00],
[1.00, 1.00, 0.67, 0.00],
[0.67, 0.67, 1.00, 0.33],
[0.00, 0.00, 0.33, 1.00],
])
distance = 1 - similarity
condensed = squareform(distance, checks=False)
Z = linkage(condensed, method="average")
labels = fcluster(Z, t=0.5, criterion="distance")
print(np.round(Z, 2))
for card, label in zip(cards, labels):
print(label, card)Z is the linkage matrix, with one row per merge. Each row has four columns:
- The first two columns are the IDs of the two clusters merged. Original cards are numbered 0 to n − 1, and each new cluster gets the next number.
- The third column is the distance at which the merge happened.
- The fourth column is the number of cards in the new cluster.
Here the merges are:
- Shipping rates and Track order merge at distance 0.
- Returns joins them at about 0.33.
- Gift cards joins last at about 0.89.
fcluster cuts the tree at distance 0.5. The first three cards get one label and Gift cards gets another. The label numbers themselves are arbitrary, so only which cards share a label matters.
Reading a dendrogram
A dendrogram draws the merge list as a tree. Cards sit along one axis. The other axis is distance. Each U-shaped link joins two clusters, and the link's position along the distance axis is the merge height.
The tree below shows the same four cards. Each box is a cluster, and the label gives the distance at which it formed.
To plot the real dendrogram, use Matplotlib:
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import squareform
cards = ["Shipping rates", "Track order", "Returns", "Gift cards"]
similarity = np.array([
[1.00, 1.00, 0.67, 0.00],
[1.00, 1.00, 0.67, 0.00],
[0.67, 0.67, 1.00, 0.33],
[0.00, 0.00, 0.33, 1.00],
])
Z = linkage(squareform(1 - similarity, checks=False), method="average")
fig, ax = plt.subplots(figsize=(7, 3))
dendrogram(Z, labels=cards, orientation="right", color_threshold=0.5, ax=ax)
ax.axvline(0.5, linestyle="--")
ax.set_xlabel("Distance (1 - share of participants who grouped the pair)")
plt.tight_layout()
plt.show()Read the plot with these rules:
- Short links mean strong agreement. A merge near 0 means almost everyone grouped those cards together. A merge near 1 means almost nobody did.
- Compare merge heights, not positions. Branches can swap sides at any joint without changing the meaning. Two cards drawn next to each other are not necessarily similar. Only the height of the join that connects them tells you how close they are.
- Large jumps suggest natural cut points. If merges happen at 0, 0.1 and 0.15, then jump to 0.7, cutting before the jump gives stable groups. A gradual slope with no jump means there are no clear groups, and any cut is arbitrary.
- A card that joins late is a poor fit. Gift cards merges at 0.89 because participants disagreed about where it belongs. This is a finding. It may need a different label, a second location, or a place in a "Shop" area rather than forcing it into a group.
How the linkage choice changes the tree
Run the same distances through three methods and compare the merge heights.
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import squareform
similarity = np.array([
[1.00, 1.00, 0.67, 0.00],
[1.00, 1.00, 0.67, 0.00],
[0.67, 0.67, 1.00, 0.33],
[0.00, 0.00, 0.33, 1.00],
])
condensed = squareform(1 - similarity, checks=False)
for method in ["single", "average", "complete"]:
Z = linkage(condensed, method=method)
print(method, np.round(Z[:, 2], 2))The output is:
single [0. 0.33 0.67]
average [0. 0.33 0.89]
complete [0. 0.33 1. ]The groupings are the same, but the last merge sits at 0.67, 0.89 or 1.0. Single linkage reports Gift cards as fairly close to the rest, because its link to Returns (distance 0.67) is the only one that counts. Complete linkage reports it as maximally far. On real data with dozens of cards, the groupings themselves can differ. Run average and complete linkage, and treat groups that appear under both as reliable. Treat groups that appear under only one as tentative.
Checking the tree against the matrix
A dendrogram compresses the matrix, and some information is lost. The cophenetic correlation measures how well the tree's distances match the original ones. Values near 1 mean the tree is faithful.
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import squareform
similarity = np.array([
[1.00, 1.00, 0.67, 0.00],
[1.00, 1.00, 0.67, 0.00],
[0.67, 0.67, 1.00, 0.33],
[0.00, 0.00, 0.33, 1.00],
])
condensed = squareform(1 - similarity, checks=False)
Z = linkage(condensed, method="average")
c, _ = cophenet(Z, condensed)
print(f"Cophenetic correlation: {c:.2f}")Compare this number across linkage methods, and prefer the one that stays closest to the data. It cannot tell you whether the groups make sense to users. That is a job for the category names and comments you read earlier.
Common errors
- Passing the square matrix to
linkage. This runs without error and gives a meaningless tree. Always pass the condensed form. - Clustering similarity instead of distance. The tree comes out inverted, with the least-grouped cards merging first.
- Treating the dendrogram as the answer. It proposes groups. It does not name them, order them, or decide how deep the navigation should be.
- Reading too much from a small sample. With 10 participants, similarity values move in steps of 10 points. Small differences in merge height are noise.
- Ignoring singletons. Cards that never merge until the root are often the most useful finding, as long as you act on them.
Exercise
A card sort with 20 participants gives merge heights of 0.05, 0.10, 0.12, 0.15, 0.20 for most cards, then two final merges at 0.75 and 0.92. You cut the tree at 0.5 and get three groups. A colleague cuts at 0.1 and gets many small groups. Which cut would you use, and what would you check before trusting it?
Show answer
Use the cut at 0.5. It sits in the large gap between 0.20 and 0.75, so the three groups are stable across a wide range of thresholds. The cut at 0.1 splits groups that participants largely grouped together. Before trusting the three groups, rerun with complete linkage and see whether the same groups appear. Then read participants' category names for each group to confirm they describe a coherent theme.