Clustering is the unsupervised task of organizing observations into groups so that observations assigned to the same group are similar according to some criterion, while observations in different groups are comparatively dissimilar. Unlike supervised learning, clustering begins without a target variable that identifies the desired partition.
Let \(\mathcal D=\{x_1,x_2,\ldots,x_N\}, x_n\in\mathcal X\), be an unlabeled dataset. A hard clustering into \(K\) groups is a collection \(\mathcal C=\{C_1,\ldots,C_K\}\) satisfying
\[
C_k\subseteq \{1,\ldots,N\},\qquad
C_k\cap C_\ell=\varnothing \text{ for }k\neq \ell,
\] and \[
\bigcup_{k=1}^{K}C_k=\{1,\ldots,N\}.
\]
Equivalently, clustering assigns each observation a latent label \(z_n\in\{1,\ldots,K\}\).
However, this formal definition does not determine what a cluster is. Different algorithms embody different concepts of grouping:
In K-means, a cluster is a compact collection of points around a centroid.
In K-medoids, a cluster is organized around a representative observation.
In hierarchical clustering, clusters are levels of a nested merging or splitting structure.
In a Gaussian mixture model, a cluster is a latent probability-generating component.
In DBSCAN, a cluster is a density-connected region separated by low-density space.
In spectral clustering, a cluster is a well-connected subgraph with comparatively weak connections to other groups.
In topic modeling, a document may belong fractionally to several latent semantic topics.
In relational clustering, membership depends partly on links among entities rather than only on their measured attributes.
Therefore, clustering is not one uniquely defined mathematical problem. It is a collection of unsupervised methods based on different structural assumptions. It asks:
What form of structure would constitute a meaningful cluster in this dataset?
1. Data Geometry Before Clustering
1.1. Representation Determines the Clusters
A clustering algorithm operates on a representation of the observations. Suppose an observation is represented as \(x_n=(x_{n1},\ldots,x_{nD})^\top\in\mathbb R^D\).
Even before selecting an algorithm, the analyst has made consequential choices:
which variables define similarity;
whether variables are transformed;
how missingness is handled;
whether observations are aggregated;
whether time, geography, or network structure is included;
whether raw variables or learned embeddings are used.
Two observations can be near each other in one representation and far apart in another. Thus, clustering does not reveal structure independently of representation. It reveals structure under a specified geometry or probability model.
1.2. Distances and Dissimilarities
Many clustering methods begin with a distance or dissimilarity function \(d:\mathcal X\times\mathcal X\rightarrow[0,\infty).\) For numerical vectors, common choices include the Euclidean distance
Income may dominate because of its numerical units. Standardization replaces each feature by
\[
z_{nr} = \frac{x_{nr}-\bar x_r}{s_r}.
\]
After standardization, the algorithm works in units of marginal standard deviations. Raw-scale clustering asks which observations are close in physical measurement units. Standardized clustering asks which observations have similar relative profiles across variables.
Robust scaling may be preferable when features contain extreme values:
However, pairwise missingness can cause different distances to be based on different coordinate sets, making the resulting geometry difficult to interpret.
Imputation may create artificial concentration near central values and can therefore generate apparent clusters or remove genuine ones. Missingness indicators and sensitivity analysis are often necessary.
1.5. Outliers and Rare Groups
An extreme observation may be:
an error;
an isolated anomaly;
an early sign of system failure;
a member of a small but meaningful cluster;
a valid observation from a different population.
The treatment depends on the scientific question. K-means can be strongly influenced by extreme observations because it minimizes squared distances. K-medoids is more resistant. DBSCAN may classify isolated points as noise. A mixture model may create a small component around them.
Calling a point “noise” is itself a modeling judgment. Rare observations are not automatically meaningless.
1.6. Cluster Tendency
Before forcing a partition, one should ask whether the data exhibit clustering tendency at all.
A clustering algorithm can partition almost any dataset, even a uniform cloud. The existence of an output does not prove the existence of meaningful clusters.
Useful questions include:
Are there multimodal marginal or projected distributions?
Are within-group distances systematically smaller than between-group distances?
Is the partition stable across samples, initializations, and feature choices?
Does the result outperform structure expected under a reference null distribution?
Are the clusters interpretable through variables not used to construct them?
Does the cluster solution support a meaningful downstream action?
The gap statistic explicitly compares within-cluster dispersion against that expected under a reference distribution with no comparable cluster structure
2. \(k\)-Means Clustering
2.1. The \(k\)-Means Objective
Assume \(x_n\in\mathbb R^D\) and choose a number of clusters \(K\).
Let \(z_{nk}\in\{0,1\}\) indicate whether point \(n\) is assigned to cluster \(k\), with \(\sum_{k=1}^{K}z_{nk}=1.\) Let \(\mu_k\in\mathbb R^D\) be the centroid of cluster \(k\).
The K-means objective is
\[
J(Z,\mu) = \sum_{n=1}^{N} \sum_{k=1}^{K} z_{nk}\|x_n-\mu_k\|_2^2.
\] Equivalently, if \(C_k\) is the index set of cluster \(k\),
\[
J(\mathcal C) = \sum_{k=1}^{K} \sum_{n\in C_k} \|x_n-\mu_k\|_2^2.
\]
This is called:
within-cluster sum of squares;
within-cluster dispersion;
quantization error;
distortion;
inertia.
2.2. The Optimal Centroid
NoteTheorem: The Mean Minimizes Squared Distance
For a fixed nonempty cluster C, the point \[
\mu^* = \frac{1}{|C|} \sum_{n\in C}x_n
\]
During the update step, assignments are fixed. By Theorem 1, replacing each centroid with the mean of its assigned observations minimizes the within-cluster squared error.
Because only finitely many hard partitions of \(N\) observations into \(K\) labeled groups exist, the algorithm eventually reaches a fixed assignment under ordinary tie-handling conditions. However, the result may be only a local optimum.
2.5. Geometry of \(K\)-Means
The assignment region of centroid \(\mu_k\) is
\[
V_k = \left\{ x: \|x-\mu_k\| \leq \|x-\mu_j\| \text{ for all }j \right\}.
\]
These regions form a Voronoi partition. Under Euclidean distance, boundaries between two centroids are hyperplanes.
For centroids \(\mu_a\) and \(\mu_b\), the boundary satisfies
This explains why K-means favors clusters that can be separated by centroid-based Voronoi cells. It is poorly matched to intertwined spirals, rings, highly unequal densities, or strongly nonconvex shapes.
The squared Euclidean objective works best when groups are approximately:
compact;
convex;
spherical or isotropic;
similar in spread;
sufficiently separated.
Suppose one genuine cluster is large and diffuse while another is small and compact. Reducing squared error may split the diffuse group and merge the compact group with a neighbor. The optimization objective need not recover the grouping a human expects.
K-Means
3. \(k\)-Medoids and Robust Prototypes
In \(K\)-medoids, each cluster center must be an observed object.
Let \(m_k\in\{1,\ldots,N\}\) be the index of medoid \(k\). Then
Because the prototype is an actual observation, \(K\)-medoids can work with an arbitrary dissimilarity matrix and does not require a meaningful coordinate mean.
\(s(i)\approx 1\): the point is well matched to its cluster;
\(s(i)\approx 0\): it lies near a boundary;
\(s(i)<0\): another cluster may fit it better.
The average silhouette is
\[
\bar s = \frac{1}{N}\sum_{i=1}^{N}s(i).
\]
Rousseeuw introduced silhouettes as both a numerical and graphical aid to interpreting partition quality.
Silhouette analysis inherits the chosen distance and tends to favor separated, compact clusters. A high score is not proof of substantive validity.
Silhouette Coefficient
4.3. Gap Statistic
Let W_K be within-cluster dispersion for the observed data. Generate B reference datasets from a null distribution with no comparable cluster structure and calculate
Single linkage merges groups when any pair of points is close.
It can recover elongated or irregular connected structures, but it is prone to chaining: a sequence of intermediate points may join otherwise separated dense regions.
Construct a graph connecting points whose distance is below a threshold \(t\). Cutting a single-linkage dendrogram at t gives the connected components of this threshold graph.
Single linkage is also closely related to the minimum spanning tree.
\[
q(Z)=p(Z\mid X,\Theta^{\text{old}}),
\] making the bound tight at the current parameters. The M-step increases or maximizes the bound with respect to \(\Theta\). Therefore, the observed-data likelihood cannot decrease.
EM may still converge to a local maximum or saddle point and remains initialization-sensitive.
6.5. Small-Variance Relationship to \(K\)-Means
Consider a Gaussian mixture with equal mixing weights and shared spherical covariance
The soft responsibilities become hard nearest-centroid assignments, and the weighted mean update becomes the K-means centroid update.
This is more accurately described as a limiting relationship than as a universal equivalence. General Gaussian mixtures can model unequal sizes and elliptical covariance structures that K-means cannot.
WarningMixture Components Are Not Always Substantive Clusters
A mixture component is a probability-density component. It need not correspond one-to-one with a meaningful population group.
A skewed unimodal population may require several Gaussian components for approximation. Conversely, one substantive group may contain several statistical modes.
The component interpretation should therefore be checked against domain variables and posterior ambiguity.
7. Density-Based Clustering
Centroid and Gaussian methods tend to favor convex or elliptical groups. Density-based methods define clusters as connected regions of high observation density separated by low-density regions.
DBSCAN was introduced to discover arbitrarily shaped spatial clusters while identifying isolated points as noise2.
It requires:
a neighborhood radius \(\varepsilon>0\);
a minimum number of observations \(\operatorname{MinPts}\).
7.1. DBSCAN Definitions
The \(\varepsilon\)-neighborhood of point \(x\) is
A point is a border point if it is not a core point but lies in the \(\varepsilon\)-neighborhood of a core point.
NoteDefinition: Noise Point
A point is labeled noise if it is neither a core point nor density-reachable from a core point under the algorithm’s connectivity rules.
Direct density reachability
Point \(y\) is directly density-reachable from \(x\) if
\[
y\in N_\varepsilon(x)
\]
and \(x\) is a core point.
Density reachability
Point \(y\) is density-reachable from \(x\) if there is a sequence
\[
x=p_1,p_2,\ldots,p_m=y
\]
such that each \(p_{r+1}\) is directly density-reachable from \(p_r\).
A DBSCAN cluster is a maximal density-connected set.
DBSCAN
7.2. DBSCAN Characteristics
Strengths:
no requirement to prespecify \(K\);
recovery of nonconvex shapes;
explicit noise labeling;
robustness to isolated observations.
Limitations:
sensitivity to \(\varepsilon\) and \(\operatorname{MinPts}\);
difficulty with clusters having different densities;
degradation in high-dimensional spaces;
ambiguous border points;
dependence on scale and metric.
A \(k\)-distance plot, which sorts the distance from each point to its \(k\)-th nearest neighbor, can help identify an \(\varepsilon\) transition, though the choice remains judgment-based.
OPTICS and HDBSCAN extend density-based analysis to varying density levels and hierarchical structure.
8. Spectral Clustering
8.1. From Data Points to a Similarity Graph
Spectral clustering represents observations as a graph \(G=(V,E)\), where each vertex corresponds to an observation.
Spectral clustering
Define a nonnegative similarity matrix
\[
W\in\mathbb R^{N\times N},
\]
where \(W_{ij}\) measures similarity between \(x_i\) and \(x_j\).
Every term is nonnegative, so \(f^\top Lf\geq0\). Therefore, \(L\) is positive semidefinite.
NoteTheorem: Connected Components and Zero Eigenvalues
The number of connected components in an undirected graph equals the multiplicity of eigenvalue 0 of \(L\).
If \(C\) is a connected component and \(\mathbf 1_C\) is its indicator vector, then no edges leave \(C\), and \(L\mathbf 1_C=0.\) Indicators of distinct components are linearly independent. Conversely, any vector satisfying \(Lf=0\) must have \(f_i=f_j\) along every positively weighted edge, because
The normalization discourages solutions that isolate a few low-degree vertices.
Exact normalized-cut optimization is combinatorial. Spectral methods relax the discrete indicator constraints into a continuous eigenvector problem. Ng, Jordan, and Weiss developed a widely used normalized spectral clustering algorithm based on leading eigenvectors of a normalized similarity matrix3.
8.4. Spectral Clustering Algorithm
One common version proceeds as follows:
Construct \(W\).
Compute \(D\).
Form
\[
A=D^{-1/2}WD^{-1/2}.
\]
Compute the K eigenvectors associated with the largest eigenvalues of \(A\), equivalently the smallest eigenvalues of \(L_{\text{sym}}\).
As \(m\) approaches 1, memberships become harder. Larger \(m\) produces more diffuse memberships.
Fuzzy membership can be useful when the phenomenon is genuinely gradual—for example, transitional ecological zones or customers with mixed behavioral profiles. It should not be interpreted automatically as a calibrated probability.
10. Topic Models
A scientific article may discuss both machine learning and transportation. A news article may combine economics and public policy. Assigning each document to exactly one topic can be artificial.
LDA
Latent Dirichlet Allocation represents each document as a distribution over topics and each topic as a distribution over words 4.
Let:
\(K\) be the number of topics;
\(V\) be vocabulary size;
\(\theta_d\) be document \(d\)’s topic proportions;
\[
\begin{aligned}
z_{dn} &\sim \operatorname{Categorical}(\theta_d),\\
w_{dn} &\sim \operatorname{Categorical}(\beta_{z_{dn}}).
\end{aligned}
\] Each document is therefore a mixture rather than a single cluster.
LDA is not interchangeable with geometric clustering. It is a probabilistic latent-variable model tailored to discrete count data.
11. Self-Organizing Maps
A Self-Organizing Map places prototypes on a fixed low-dimensional grid. Let
\[
m_1,\ldots,m_K\in\mathbb R^D
\]
be prototype vectors, each assigned a grid coordinate.
\(h_{c,k}^{(t)}\) decreases with grid distance from the winning unit.
Unlike ordinary \(K\)-means, nearby prototypes on the grid are updated together. The resulting map attempts to preserve neighborhood structure while providing a two-dimensional visualization.
SOMs are useful exploratory tools but may distort distances and should not be treated as exact low-dimensional geometric embeddings.
12. Archetypal Analysis
\(K\)-means prototypes are central averages. Archetypal analysis instead seeks extreme profiles on or near the convex hull.
Archetypal Analysis
Each observation is approximated as
\[
x_i \approx \sum_{k=1}^{K}\alpha_{ik}z_k,
\]
where \(\alpha_{ik}\geq0, \sum_{k=1}^{K}\alpha_{ik}=1\).
Each archetype is itself a convex combination of observations:
\[
z_k = \sum_{j=1}^{N}\beta_{kj}x_j,
\]
with \(\beta_{kj}\geq0, \sum_{j=1}^{N}\beta_{kj}=1\).
Mini-batch \(K\)-means uses small batches to approximate Lloyd updates efficiently.
Streaming clustering must also confront concept drift: the population itself may change. A fixed historical cluster may no longer describe current behavior. Forgetting factors or sliding windows can emphasize recent observations.
14. Relational and Graph Clustering
In many datasets, observations are connected:
people communicate;
airports exchange flights;
papers cite one another;
customers purchase the same products;
proteins interact.
The observations are not independent feature vectors. Their relations carry structural information.
Relational and Graph Clustering
Graph clustering seeks communities with strong internal connectivity and weaker external connectivity. Objectives may include normalized cut, modularity, stochastic block-model likelihood, or random-walk persistence.
A stochastic block model assumes latent group assignments \(z_i\) and connection probabilities
\[
P(A_{ij}=1\mid z_i=k,z_j=\ell) = B_{k\ell}.
\]
This is a probabilistic relational analogue of mixture modeling.
Feature information and graph information can also be combined, but their relative weighting must be specified.
15. Internal Evaluation
Internal measures use only the data and fitted partition.
Sometimes known labels exist but are withheld during clustering. They can then evaluate whether the unsupervised partition aligns with an external categorization. This must be interpreted carefully. A clustering solution may be useful without matching known labels, and known labels may not correspond to the geometry being modeled.
16.1. Purity
For cluster \(C_k\), let \(n_{kj}\) be the number of observations with external class \(j\).
Lloyd’s algorithm alternates between nearest-centroid assignment and mean updates. Each step decreases the objective, but the nonconvex problem permits local optima and initialization dependence.
\(K\)-medoids replaces abstract means with observed representatives and supports more general dissimilarities. Hierarchical clustering reveals nested relationships, but the result depends critically on linkage. Ward’s method joins groups according to the increase
\[
\frac{|A||B|}{|A|+|B|} \|\mu_A-\mu_B\|^2
\]
in within-cluster variation.
Gaussian mixture models treat clusters as latent probability components. Their responsibilities
\[
\gamma_{nk} = P(Z_n=k\mid x_n)
\]
retain assignment uncertainty. EM alternates between estimating these responsibilities and updating component parameters. K-means emerges as a small-variance limiting case of an equal spherical Gaussian mixture, but general mixture models are more flexible.
DBSCAN identifies density-connected regions and explicitly labels noise. Spectral clustering transforms similarity into graph geometry and uses Laplacian eigenvectors to reveal weakly connected graph regions. Fuzzy clustering and topic models allow mixed membership, while SOMs, archetypal analysis, streaming methods, and relational models adapt the clustering idea to specialized structures.
The absence of labels makes evaluation fundamentally difficult. WCSS, silhouettes, and gap statistics measure properties induced by specific objectives. External measures such as ARI and NMI require labels that were not used in fitting. Stability and independent cluster characterization are therefore essential.
The deepest lesson is that a cluster is not simply found in data. It is defined jointly by:
the observation unit;
the selected variables;
data transformations;
the metric or likelihood;
the clustering objective;
the number of groups or density scale;
the sampling context;
the intended interpretation.
Clustering is most useful when these choices are made explicitly and when the resulting groups remain stable, interpretable, and appropriate for the decisions they are meant to support.
Dempster, A. P., N. M. Laird, and D. B. Rubin. “Maximum Likelihood from Incomplete Data Via the EM Algorithm.” Journal of the Royal Statistical Society: Series B (Methodological) 39, no. 1 (1977): 1–22. https://doi.org/10.1111/j.2517-6161.1977.tb01600.x.↩︎
Ester, Martin, Hans-Peter Kriegel, Jörg Sander, and Xiaowei Xu. “A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise.” Proceedings of the Second International Conference on Knowledge Discovery and Data Mining (Portland, Oregon), KDD’96, August 2, 1996, 226–31.↩︎
Blei, David M., Andrew Y. Ng, and Michael I. Jordan. “Latent Dirichlet Allocation.” The Journal of Machine Learning Research 3, no. null (2003): 993–1022.↩︎