Skillversitas

Cluster Analysis

Bio.Cluster performs hierarchical clustering on distance matrices and expression-style data tables: compute distances between rows or columns, build a dendrogram, and extract cluster assignments. It is the classic tool for grouping genes by expression pattern or grouping sequences by similarity.

Computing Distances

from Bio.Cluster import distance

# a small expression matrix: genes x conditions
matrix = [
    [1.0, 2.0, 1.5],
    [1.2, 1.8, 1.4],
    [5.0, 4.8, 5.1],
    [0.1, 0.2, 0.05],
]

# euclidean distance matrix between rows (genes)
d = distance(matrix, method="euc")
for row in d:
    print([round(x, 2) for x in row])

Distance Methods

methodMetric
eucEuclidean
corCorrelation (1 - Pearson correlation)
pearsonPearson
cityCity-block (Manhattan)
hammingHamming (for discrete data)

Clustering

from Bio.Cluster import cluster

# hierarchical clustering on the distance matrix
linkage = cluster(d, method="average")
print(linkage)  # clustering tree (UPGMA-style average linkage)

Cutting the Tree into Clusters

from Bio.Cluster import cluster

# k-means style: partition into k clusters
centroids = cluster(matrix, method="kmeans", num_clusters=2)
print(centroids)  # cluster assignment per row

Visualizing (with matplotlib)

import matplotlib.pyplot as plt

# a quick 2D projection of the rows colored by cluster
from Bio.Cluster import cluster
assign = cluster(matrix, method="kmeans", num_clusters=2)
plt.scatter(matrix[:, 0], matrix[:, 1], c=assign, cmap="viridis")
plt.colorbar(label="cluster")
plt.show()

Practical Notes

  • Standardize columns (z-score) before correlation-based clustering of expression data.
  • Hierarchical results are a tree; choose a height cut to get clusters, or use kmeans for a fixed k.
  • Biopython's cluster module requires NumPy; install it if import fails.

Summary

Bio.Cluster computes distance matrices (euc, cor, city, hamming) and clusters them: hierarchical clustering with cluster(method=...) for dendrograms, or kmeans for fixed-size partitions. Pair it with matplotlib to visualize cluster assignments - the standard first pass for grouping expression data or similar row-based datasets.