The six observations from the K-means example, now labeled 1 through 6.
Show the reproducible code
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom scipy.spatial.distance import pdist, squareformfrom scipy.cluster.hierarchy import linkage, dendrogram, cut_tree, to_tree, leaves_listnavy ="#13294B"orange ="#C84A16"toy = pd.read_csv("data/unsupervised/clustering-six-points.csv")x = toy[["x1", "x2"]].to_numpy()fig, ax = plt.subplots(figsize=(6, 4.8))ax.scatter(*x.T, s=350, facecolors="white", edgecolors=navy)for i, point inenumerate(x): ax.text(*point, str(i +1), ha="center", va="center", color=navy)ax.set(xlim=(-1.35, 0.45), ylim=(-1.51, 1.61))ax.axis("off")plt.tight_layout()plt.show()
The six observations from the K-means example, now labeled 1 through 6.
The goal is to progressively group them together until there is only one group. During this process, we always choose the closest two groups (some may be individuals) to merge.
If we evaluate the distance between two observations, that is straightforward. For example, Euclidean distance can be used for numerical measurements and Hamming distance for categorical sequences. But what about the distance between two groups? Suppose we have two groups of observations and , with sizes and . Several linkage rules can be considered:
Complete linkage: the furthest pair,
Single linkage: the closest pair,
Average linkage: the average pairwise distance,
The R function hclust() uses complete linkage by default. To perform hierarchical clustering, we need all the pairwise distances . Let’s consider Euclidean distance. Python’s linkage defaults to single linkage, so we explicitly request method="complete" to match R.
We use these distances in the hierarchical clustering algorithm. The dendrogram displays the merging process. It gives the same sequence as the four steps above, followed by the final merge of the two groups.
Complete-linkage dendrogram for the six observations.
The height of each merge represents how separated the two subsets are, measured by their linkage distance when they merge. Selecting the number of clusters is still a tricky problem. A horizontal cutoff below a large jump in merge height can suggest a useful grouping. Here, two clusters merge only at a much larger height, so a two-cluster description is reasonable.
Example 1: iris data
The iris data contain three species and four measurements. As in the K-means example, we use the two petal variables in the distance calculation and start with complete linkage. Species labels are used only to examine the fitted clusters afterward.
The three-cluster cut does not reproduce the three species exactly. In practice, detected clusters can depend heavily on the variables and linkage rule. Let’s try average linkage with the same two variables.
The iris measurements include tied distances. The short Python implementation above selects the earliest active pair when distances tie, matching the original R complete-linkage result without changing any distances. The maximum update is exactly the complete-linkage rule.
The cross-tabulations show how the grouping changes. A dendrogram’s appearance alone does not establish agreement with species. Identical or tied distances can also be resolved differently across software, and left-to-right leaf order has no statistical meaning.
Now we can also consider other ways to plot this result. For example, the R package ape provides an unrooted view. The Python code draws the same hierarchy with an equal-angle tree layout. This changes the display, not the fitted clustering. Use the rooted dendrogram above to read merge heights.
We can also add the true class colors to the plot. This plot is motivated by the dendextend package vignettes. Branch colors show the three fitted clusters, and label colors show species. In a realistic unsupervised problem, the true classes may be unknown.
We use a tissue gene expression dataset from the tissuesGeneExpression library, available from Bioconductor. I prepared the data to include only 100 genes. The shared expression matrix and tissue labels are exported from the original course data. Rows are 189 tissue samples, and columns are 100 genes.
In this first step, we simply plot the data using a heatmap without organizing the columns or rows. We standardize each column (gene) to mean zero and sample standard deviation one. Navy denotes lower standardized expression, white denotes zero, and orange denotes higher expression. We turn off any additional heatmap scaling so that both languages display this same matrix.
Hierarchical clustering may help us discover interesting patterns. If we reorganize the columns and rows based on their clusters, this may reveal underlying subclasses of tissues or subgroups of genes. We use Euclidean distance and complete linkage separately for the samples and the genes. Only their ordering changes; the standardized values and color scale are unchanged.
Blocks of similar expression become easier to see after reordering. These clusters describe similarity under the selected genes, standardization, distance, and linkage; they do not by themselves establish biological tissue classes.
There are many other R packages that produce interactive heatmaps. For example, you can try heatmaply.