Skip to content
ml-recall

Topic notes

Clustering

Grouping unlabeled data - k-means and its inertia, choosing k, Gaussian mixtures fitted by EM, density-based DBSCAN, hierarchical clustering, similarity measures and cluster evaluation.

4-min read AI-checked

Practise 44 questions Take a test

Key ideas

Clustering is unsupervised: there are no labels, and the algorithm groups points by similarity. Uses include customer segmentation, compression and anomaly detection (points far from every cluster).

k-means minimises the inertia (within-cluster sum of squares) for a fixed, user-chosen kk1,3.

Choosing kk. The best achievable inertia never increases with kk and is 0 when every distinct point is its own cluster, so "smallest inertia" is not a criterion. The elbow method looks for a bend in inertia versus kk, which is often unclear3. The silhouette of a point compares aa, its mean distance to its own cluster, with bb, its mean distance to the nearest other cluster. It lies in [−1,1][-1, 1], near 0 for overlapping clusters, and it does not need cluster centres1. It favours convex clusters over density-based ones1.

Gaussian mixture models are a soft, probabilistic generalisation: each component has a weight πk\pi_k, mean and covariance, so clusters can be elliptical and of different sizes, and each point gets a probability for every component3. They are fitted with EM, which is also sensitive to initialisation4.

DBSCAN (density-based) needs eps (neighbourhood radius) and min_samples. scikit-learn's code and API page count the point itself in min_samples2, although its user guide speaks of "other" samples1; the code below confirms the first reading.

Hierarchical (agglomerative) clustering starts with singletons and repeatedly merges the closest pair of clusters (Ward, complete, average or single linkage). The dendrogram records the merges; cutting it at different heights gives coarser or finer clusterings, with no random initialisation1. Spectral clustering clusters the eigenvectors of a similarity graph and handles non-flat shapes1.

Similarity. Cosine similarity ignores vector length; the dot product grows with it. Switching from cosine to dot product therefore makes long vectors (for example, popular items) more similar to everything5.

Formulas

Worked example

k-means with k=2k = 2 on 1,2,4,7,9,101, 2, 4, 7, 9, 10, starting from centroids 11 and 44.

In code

import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.metrics import silhouette_score

X = np.array([1, 2, 4, 7, 9, 10], dtype=float).reshape(-1, 1)
km = KMeans(n_clusters=2, init=np.array([[1.0], [4.0]]), n_init=1).fit(X)
print(km.labels_, km.cluster_centers_.ravel().round(3))  # [0 0 0 1 1 1] [2.333 8.667]
print(round(km.inertia_, 3))                        # 9.333
print(round(silhouette_score(X, km.labels_), 3))   # 0.659
P = np.array([1, 2, 3, 6, 8, 9, 10, 15], dtype=float).reshape(-1, 1)
print(DBSCAN(eps=1, min_samples=3).fit(P).labels_)  # [ 0  0  0 -1  1  1  1 -1]

Only 2 and 9 are core points; 1, 3, 8 and 10 are border points; 6 and 15 are noise.

Common pitfalls

References

  1. scikit-learn User Guide: Clustering — Sec. 2.3.1 Overview of clustering methods; 2.3.2 K-means; 2.3.5 Spectral clustering; 2.3.6 Hierarchical clustering; 2.3.7 DBSCAN; 2.3.11.1 Rand index; 2.3.11.5 Silhouette Coefficient
  2. scikit-learn API: sklearn.cluster.DBSCAN — Parameters eps and min_samples; attribute labels_
  3. Wikipedia: k-means clustering — Description; History; Algorithms — Standard algorithm (naive k-means), Complexity, Optimal number of clusters, Variations; Discussion
  4. Wikipedia: Expectation–maximization algorithm — Examples — Gaussian mixture (E step, M step); Properties
  5. Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — Clustering: Measuring similarity from embeddings — Choosing a similarity measure
  6. Wikipedia: Cluster analysis — Evaluation and assessment — External evaluation — Purity