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 1,3.
- Lloyd's algorithm: initialise centroids; assign every point to its nearest centroid; update each centroid to the mean of its points; repeat until the centroids stop moving or a maximum number of iterations is reached1. Every point belongs to exactly one cluster at every step.
- Inertia never increases, so the algorithm always converges, but only to a local optimum that depends on the initialisation. Finding the global optimum is NP-hard1,3. Use several restarts and k-means++ seeding1.
- The centroids cut the space into Voronoi cells, so k-means suits convex, isotropic, similar-sized ("flat geometry") clusters and fails on curved or elongated ones1,3.
- It works on Euclidean distances: scale the features first, or the one with the largest range dominates. Do not rescale features whose units are already comparable and meaningful, such as latitude and longitude: scaling them separately would distort real distances.
- k-means came from signal processing (vector quantization): each value is replaced by the nearest of representatives3. k-medoids uses an actual data point as centre and works with any distance3; a medoid is much less pulled by an outlier than a mean.
Choosing . The best achievable inertia never increases with 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 , which is often unclear3. The silhouette of a point compares , its mean distance to its own cluster, with , its mean distance to the nearest other cluster. It lies in , 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 , 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.
- A core point has at least
min_samplespoints (itself included) within distanceeps. Clusters are chains of core points plus their border points, which are withinepsof a core point but are not core themselves. Everything else is noise, labelled 1,2. - No to choose; finds clusters of arbitrary shape and uneven size; robust to outliers ("non-flat geometry")1. Lower
epsor highermin_samplesdemands higher density: too small anepslabels most points as noise, too large anepsmerges nearby clusters1.
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
- Inertia: 1.
- Silhouette: 1.
- GMM E-step (responsibilities): 4.
- M-step: , , 4.
- Example: equal weights, components and , point : .
- Dot product .
Worked example
k-means with on , starting from centroids and .
- Assign: to centroid 1 and to centroid 4. Update: and .
- Assign again: is now closer to (distance 2.5) than to (3.5), so the clusters become and . Update: and . Nothing changes after that: converged.
- Inertia .
- Silhouette of the point 4: , , .
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
- k-means does not find the same clusters on every run, and it is not guaranteed to find the optimum; it also does not decide for you.
- The best is not the one with the smallest inertia (that is always ).
- In DBSCAN, border points belong to a cluster without having
min_samplesneighbours themselves; only core points need that. - k-means is more affected by outliers than DBSCAN, which labels isolated points as noise.
- The in k-means (number of clusters) has nothing to do with the in -NN (number of neighbours).
- A good silhouette score says clusters are compact and separated, not that they mean what you care about.
- Purity against reference labels rewards tiny clusters: one point per cluster gives purity 16. Prefer chance-adjusted scores such as the adjusted Rand index1.
References
- 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
- scikit-learn API: sklearn.cluster.DBSCAN — Parameters eps and min_samples; attribute labels_
- Wikipedia: k-means clustering — Description; History; Algorithms — Standard algorithm (naive k-means), Complexity, Optimal number of clusters, Variations; Discussion
- Wikipedia: Expectation–maximization algorithm — Examples — Gaussian mixture (E step, M step); Properties
- Google Machine Learning courses: Decision Forests, Clustering, GANs, Problem Framing — Clustering: Measuring similarity from embeddings — Choosing a similarity measure
- Wikipedia: Cluster analysis — Evaluation and assessment — External evaluation — Purity