CodeBlanks Logo Icon CodeBlanks

Dendrogram

A dendrogram visualizes hierarchical clustering results as a tree.

Dendrogram

A dendrogram is the drawing of the merge tree: a plot where the leaves are examples, the horizontal lines merges and the line height the merge distance. Cut with a horizontal line, the number of vertical lines it crosses gives the number of clusters.

from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
dendrogram(Z, ax=ax)
ax.axhline(4, color="r", linestyle="--")   # cut at this height

Long vertical branches are the sign of well-separated clusters.

Cutting with fcluster

To cut the tree from code, fcluster is used: either with a distance threshold (criterion="distance") or with the desired number of clusters (criterion="maxclust"):

from scipy.cluster.hierarchy import fcluster
etiket = fcluster(Z, t=4, criterion="distance")   # cut merges above 4
etiket2 = fcluster(Z, t=3, criterion="maxclust")  # at most 3 clusters

fcluster starts labels at 1; scikit-learn starts at 0.

Practice Cut the tree

Build the tree with Ward linkage. Make a cut with fcluster first using t=3, criterion="maxclust", then t=10, criterion="distance"; print the two label arrays on separate lines.

Starter code

model.py
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster

X = np.array([[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5], [12, 0], [12, 1]])

# buraya yaz

Sample solution

model.py
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster

X = np.array([[0, 0], [0, 1], [1, 0], [5, 5], [5, 6], [6, 5], [12, 0], [12, 1]])

Z = linkage(X, method="ward")
print(fcluster(Z, t=3, criterion="maxclust"))
print(fcluster(Z, t=10, criterion="distance"))

Expected output

[2 2 2 3 3 3 1 1]
[2 2 2 3 3 3 1 1]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If a horizontal cut crosses 3 vertical lines in a dendrogram, how many clusters result?

  • 2
  • 4
  • It can't be determined
  • 3 Correct answer

Explanation: Each independent branch below the cut is a cluster.

2 Cut the tree so there are at most 2 clusters.

Question
etiket = fcluster(Z, t=2, criterion=____)
Answer
etiket = fcluster(Z, t=2, criterion="maxclust")

Explanation: "maxclust" interprets t as the number of clusters.

3 Match the concepts.

Term Meaning
leaf A single example
line height Merge distance
horizontal cut Sets the cluster count
long branch Well-separated cluster

All lessons in Intermediate