
Unsupervised Clustering Algorithms: k-Means, DBSCAN, and a Comparative Mathematical Analysis
A rigorous mathematical analysis of three major clustering paradigms with formal proofs, complexity bounds, and empirical validation. We prove convergence, NP-hardness, and approximation guarantees.
Abstract
Clustering is a foundational problem in unsupervised learning, yet the formal guarantees of widely deployed algorithms are rarely examined in unified treatments. This article presents a rigorous comparative analysis of three major clustering paradigms: centroid-based (-means), density-based (DBSCAN), and hierarchical (agglomerative) methods. We formalize the -means objective as a non-convex optimization problem, prove that Lloyd's algorithm converges in finitely many iterations via a coordinate descent argument, and establish that the optimal -means problem is NP-hard even for in general dimension. We then derive the -competitive approximation guarantee of the -means++ initialization. For DBSCAN, we provide a formal density-reachability framework, prove correctness with respect to density-connected components, and analyze its worst-case and index-assisted complexity. We evaluate all methods against formal internal validity indices — the silhouette coefficient and Davies–Bouldin index — whose mathematical properties we derive. The comparative analysis identifies precise geometric and distributional conditions under which each paradigm is superior, moving beyond the informal heuristic that "it depends on the data."
1. Introduction
1.1 Motivation
Clustering — the task of partitioning a dataset into groups of similar objects without labeled supervision — occupies a central position in data science, pattern recognition, and exploratory data analysis. Despite its ubiquity, clustering is not a single well-defined problem but a family of optimization problems, each encoding different geometric or statistical assumptions about what constitutes a "good" partition. The practical consequence is that practitioners routinely select algorithms based on convenience or empirical tuning, without formal understanding of when a chosen method is optimal, approximately optimal, or provably unsuitable.
This matters theoretically because clustering objectives encode deep combinatorial structure. The -means problem, for instance, is NP-hard (Aloise et al., 2009; Dasgupta, 2008), yet Lloyd's heuristic (Lloyd, 1982) is used billions of times daily. Understanding why it works — and when it fails — requires formal analysis that typical treatments omit.
1.2 Problem Statement
We consider the following general problem. Given a finite dataset and a dissimilarity function , produce a partition of that optimizes some quality criterion. The nature of the criterion — and whether is given or inferred — fundamentally distinguishes the clustering paradigms we analyze.
1.3 Prior Work and Existing Results
Lloyd (1982) introduced the iterative centroid-refinement algorithm now universally called "-means." Its worst-case iteration complexity was shown to be superpolynomial by Vattani (2011), who constructed instances requiring iterations in the plane. Arthur and Vassilvitskii (2007) introduced -means++ with a provable approximation guarantee. The NP-hardness of the planar -means problem was established by Mahajan, Nimbhorkar, and Varadarajan (2012) and for general dimension by Aloise et al. (2009). Ester et al. (1996) introduced DBSCAN, whose formal properties were further analyzed by Sander et al. (1998). Internal validation indices were formalized by Rousseeuw (1987) for the silhouette coefficient and Davies and Bouldin (1979) for their eponymous index.
1.4 Contribution
This article makes the following specific contributions:
- We prove -means convergence as coordinate descent on the within-cluster sum of squares (WCSS) objective and analyze the gap between this guarantee and the NP-hardness of the global optimum.
- We derive the approximation ratio of -means++.
- We formalize DBSCAN via density-reachability, prove that its output equals the set of maximal density-connected components, and establish precise complexity bounds.
- We compare all methods on a rigorous multi-criterion framework including complexity, geometric assumptions, and formal quality indices.
1.5 Organization
Section 2 establishes notation, definitions, and background results. Section 3 presents the core analysis: -means (§3.1), DBSCAN (§3.2), hierarchical clustering (§3.3), and the formal comparative framework (§3.4). Section 4 provides empirical validation. Section 5 offers discussion, limitations, and open problems. Section 6 concludes.
2. Preliminaries and Definitions
2.1 Notation
Throughout, denotes the input dataset. We write for the Euclidean () norm unless otherwise specified. A -partition of is a collection of nonempty, pairwise disjoint subsets whose union is . For a finite set , its centroid is . We use to denote . All complexity analysis is in the RAM model with -cost arithmetic on -dimensional vectors.
2.2 Core Definitions
Definition 1 (Within-Cluster Sum of Squares). Given a -partition of , the WCSS objective is:
This is equivalently written as , where .
Example. For with , the partition gives , while gives .
Definition 2 (-neighborhood). For and , the -neighborhood of is .
Definition 3 (Core point, border point, noise). Given parameters and , a point is a core point if . A point is a border point if it is not a core point but belongs to for some core point . All remaining points are noise.
Definition 4 (Direct density-reachability). A point is directly density-reachable from if is a core point and .
Definition 5 (Density-reachability). A point is density-reachable from if there exists a chain such that is directly density-reachable from for all .
Definition 6 (Density-connectedness). Two points are density-connected if there exists a point such that both and are density-reachable from .
Example. In a dataset with three Gaussian blobs of radius roughly separated by distance , setting and to a small integer yields three sets of mutually density-connected points, one per blob.
2.3 Background Results
We will use the following without proof.
Theorem 0 (Comparison-based lower bound, Knuth 1973). Any comparison-based sorting algorithm requires comparisons in the worst case. We invoke this when analyzing index-construction costs.
Proposition 0 (Median identity). For any finite , the unique minimizer of is the centroid . This follows by setting .
3. Core Analysis
3.1 The -Means Problem
3.1.1 Formulation as Optimization
The -means clustering problem is:
where the minimization is over all -partitions of . Equivalently, introducing explicit centers and an assignment function , we can write:
This reformulation reveals that the problem decomposes into two interleaved sub-problems: optimizing assignments given centers, and optimizing centers given assignments. Lloyd's algorithm exploits precisely this structure.
Assumption 1. The input lies in under the Euclidean metric. All -means results in this article assume distance unless stated otherwise.
Assumption 2. The number of clusters is given as input. The problem of selecting is outside the scope of this analysis, though we note its connection to model selection criteria (BIC, gap statistic) in the Discussion.
3.1.2 Lloyd's Algorithm
Lloyd's algorithm alternates between the two sub-problems identified in Equation (2).
Algorithm 1: Lloyd's Algorithm (-Means)
Input: , number of clusters , initial centers .
Repeat until convergence:
-
Assignment step: For each , set (breaking ties arbitrarily but consistently).
-
Update step: For each , set , where .
Output: Partition .
Theorem 1 (Convergence of Lloyd's Algorithm). Under Assumptions 1 and 2, Lloyd's algorithm terminates in a finite number of iterations. Moreover, the WCSS objective is monotonically non-increasing: for all .
Proof. We show that each step of the algorithm does not increase the objective, and that there are finitely many possible partitions.
Consider the joint objective from Equation (2):
Assignment step. Fixing , the assignment minimizes over pointwise (each term of the sum is independently minimized). Thus:
Update step. The update step computes . By Proposition 0, for each cluster , the centroid uniquely minimizes . Therefore:
Combining inequalities (3) and (4):
Since the objective is non-increasing and the number of distinct -partitions of points is finite (at most , the number of functions ), the algorithm must terminate. □
The proof reveals that Lloyd's algorithm is a block coordinate descent method on the joint objective , alternating minimization over the discrete variable and the continuous variables . This connection to coordinate descent is the precise reason convergence is guaranteed: each block minimization is exact, and the number of possible values of the discrete block is finite.
Remark. Convergence to a local minimum is guaranteed, but convergence to the global minimum is not. The non-convexity of the objective (which is convex in for fixed and vice versa, but not jointly) means that different initializations can yield different local minima with arbitrarily different objective values.
3.1.3 Per-Iteration Complexity
Proposition 1. Each iteration of Lloyd's algorithm runs in time and space.
Proof. The assignment step computes for all , each requiring operations, totaling . The update step computes centroids, each as a mean of at most vectors in , totaling . The dominant term is . Space is for the dataset and for the centers. □
3.1.4 Iteration Complexity: The Gap Between Practice and Worst Case
The total complexity of Lloyd's algorithm is where is the number of iterations until convergence. The critical question is the magnitude of .
Theorem 2 (Vattani, 2011). There exist point sets in for which Lloyd's algorithm (with a specific initialization) requires iterations.
This result, which we state without proof, demonstrates that the worst-case number of iterations is superpolynomial. Arthur and Vassilvitskii (2006) gave the first superpolynomial lower bound; Vattani's construction tightened it.
In stark contrast, empirical observation consistently shows that is small — typically to — on real-world data. This gap has been partially explained by smoothed analysis:
Theorem 3 (Arthur and Vassilvitskii, 2009 — informal statement). Under smoothed analysis (each input point perturbed by a Gaussian of variance ), the expected number of iterations of Lloyd's algorithm is polynomial in and .
This is a deep result connecting the practical efficiency of -means to the fact that the pathological constructions of Theorem 2 are measure-zero phenomena under perturbation.
3.1.5 NP-Hardness of Optimal -Means
Theorem 4 (Aloise et al., 2009; Dasgupta, 2008; Mahajan et al., 2012). The problem of finding a -partition minimizing the WCSS (Equation 1) is NP-hard. Specifically:
- It is NP-hard for general even for (Aloise et al., 2009).
- It is NP-hard in the plane () for general (Mahajan et al., 2012).
Intuitively, this says that unless P = NP, there is no polynomial-time algorithm that finds the globally optimal -means solution. This hardness result is what makes approximation guarantees — such as those of -means++ — theoretically significant.
3.1.6 The -Means++ Initialization
Arthur and Vassilvitskii (2007) proposed a randomized seeding procedure (-means++) that provides a provable approximation guarantee before any Lloyd iterations are performed.
Algorithm 2: -Means++ Initialization
Input: .
- Choose uniformly at random from .
- For :
- For each , compute .
- Choose with probability .
Output: Initial centers .
The key idea is the -weighting: points far from all currently selected centers are more likely to be chosen as new centers. This spreads the initial centers across the data.
Theorem 5 (Arthur and Vassilvitskii, 2007). Let denote the optimal WCSS value and let denote the WCSS after -means++ initialization (before any Lloyd iterations). Then:
Lemma 1 (Cost Reduction Lemma). Let be the current set of centers. Consider an optimal cluster with optimal center and optimal cost . If we select a new center from with probability proportional to , then the expected new cost of points in is bounded by .
Proof of Lemma 1. For any point selected as the new center, the cost contribution from becomes:
Using the identity (which follows from expanding the squared norm):
The probability of selecting is proportional to . Taking expectation over the -weighted draw:
The first term, by the definition of -weighting within , contributes at most . Therefore:
Proof of Theorem 5. We proceed by induction on the number of centers chosen.
Base case: The first center is chosen uniformly at random. For each optimal cluster , if , the expected cost from is at most by Lemma 1.
Inductive step: Suppose we have centers. Let be the set of "uncovered" optimal clusters. The probability that the -th center covers a specific uncovered cluster is at least:
The expected number of uncovered clusters after iterations follows a coupon-collector process. Combining with the factor of 2 from Lemma 1, we obtain:
Corollary 1. -means++ achieves an -approximation to the optimal WCSS in expectation, in time.
3.2 DBSCAN
3.2.1 Formal Framework
Unlike -means, DBSCAN (Density-Based Spatial Clustering of Applications with Noise) does not optimize an explicit objective function. Instead, it defines clusters geometrically as maximal sets of density-connected points.
Assumption 3. The parameters and are given. The input is a finite set under the Euclidean metric.
Definition 7 (DBSCAN Cluster). A set is a DBSCAN cluster (with respect to and ) if it satisfies two conditions: (i) Connectivity: for all , and are density-connected; and (ii) Maximality: if and is density-reachable from , then .
Lemma 2 (Symmetry of Density-Reachability on Core Points). Let be the set of core points. For any , if is density-reachable from , then is density-reachable from .
Proof. Let be a chain witnessing that is density-reachable from . Since is a core point, we have . Consider the reversed chain .
For each consecutive pair in the original chain, we have where is a core point. By symmetry of the Euclidean metric: .
Since all intermediate points must be core points, we have for all . Therefore, the reversed chain witnesses that is density-reachable from . □
Theorem 6 (Correctness of DBSCAN, Ester et al. 1996). Let be given. Then:
(a) Density-connectedness is an equivalence relation on the set of core points. (b) Every DBSCAN cluster contains at least one core point. (c) The DBSCAN clusters are precisely the maximal density-connected components.
Proof of (a). We verify the three properties of an equivalence relation on .
Reflexivity: Every core point is density-reachable from itself (trivial chain of length 1). Hence is density-connected to itself via .
Symmetry: Suppose are density-connected via . Since is density-reachable from and both are core points, by Lemma 2, is density-reachable from . Therefore, is density-connected to via the same witness .
Transitivity: Suppose are density-connected via , and are density-connected via . By Lemma 2 and chain concatenation, and are both density-reachable from , making them density-connected. □
Remark. Density-reachability is not symmetric in general (a border point is density-reachable from a core point, but not vice versa). This asymmetry is precisely why DBSCAN defines density-connectedness via a shared ancestor .
3.2.2 The DBSCAN Algorithm
Algorithm 3: DBSCAN
Input: , parameters .
- Mark all points as unvisited.
- For each unvisited point :
- Mark as visited. Compute .
- If : mark as noise (tentatively).
- Else: Create a new cluster . Add to . Initialize seed set .
- While :
- Pick , remove it from .
- If is unvisited: mark as visited, compute . If : .
- If is not yet a member of any cluster: add to .
Output: Set of clusters and noise points.
The algorithm is essentially a graph traversal (similar to BFS) on the density-reachability graph.
3.2.3 Complexity Analysis
Theorem 7 (DBSCAN Complexity). The worst-case time complexity of DBSCAN is without spatial indexing. With a spatial index supporting range queries, the complexity is when the total number of neighbor-pair relationships is .
Proof. The dominant cost is computing for each point. Without an index, each neighborhood query requires scanning all points: per query, giving total.
With a spatial index such as a -d tree, each range query costs . The total cost is:
where is the total number of neighbor relationships. In the worst case, . However, for well-separated clusters or small , and the complexity becomes . □
Assumption 4. The complexity benefit of spatial indexing assumes low effective dimensionality. In high dimensions, -d trees degrade to linear scan due to the curse of dimensionality.
3.3 Hierarchical Agglomerative Clustering
3.3.1 Framework
Hierarchical agglomerative clustering (HAC) builds a sequence of partitions by iteratively merging the two closest clusters, producing a dendrogram that encodes all possible numbers of clusters simultaneously.
Definition 8 (Linkage function). A linkage function assigns a distance between subsets. Standard choices include:
- Single linkage:
- Complete linkage:
- Average linkage:
- Ward linkage:
Theorem 8 (Ward-WCSS Connection). Merging clusters and increases the total WCSS by exactly . Therefore, Ward's method is a greedy algorithm that minimizes the increase in WCSS at each step.
Proof. Let and be two disjoint clusters with centroids , sizes .
After merging, the new cluster has centroid:
Applying the variance decomposition formula (Huygens' theorem):
Computing the shift terms and simplifying:
Proposition 3 (Complexity of naive HAC). Naive agglomerative clustering runs in time. With priority queues, single-linkage can be computed in via Prim's MST algorithm, and general linkage in .
3.4 Comparative Analysis
3.4.1 Computational Complexity
The practical per-iteration cost of -means is , making it linear in per iteration for fixed and . For large (), -means is typically the only feasible option.
3.4.2 Geometric Assumptions and Cluster Shape
Proposition 4 (-Means Voronoi Structure). The partition produced by Lloyd's algorithm consists of intersections of with Voronoi cells of the final centroids. Voronoi cells are convex polytopes, so -means can only produce convex cluster boundaries.
Counterexample 1. Consider two concentric circles in : and . Any -means solution with partitions the plane into two convex regions, which cannot separate concentric circles. DBSCAN with appropriate and correctly identifies the two circular clusters.
3.4.3 Formal Cluster Quality Indices
Definition 9 (Silhouette Coefficient). For a point assigned to cluster :
Proposition 5. . Values near indicate good clustering; values near indicate misassignment.
Definition 10 (Davies–Bouldin Index). For clusters with dispersions :
Lower values indicate better separation.
3.4.4 Conditions for Paradigm Superiority
Condition A (-Means is appropriate): Clusters are approximately convex, is known, dimensionality is manageable, and scalability to large is required.
Condition B (DBSCAN is appropriate): Clusters have arbitrary shape, data contain noise/outliers, is unknown, and low effective dimensionality.
Condition C (HAC is appropriate): Dataset is small (), hierarchical structure is of interest, or multiple granularity levels are needed.
Theorem 9 (No Free Lunch for Clustering). There exists no clustering algorithm that is simultaneously optimal for all distributions. This can be formalized via Kleinberg's impossibility theorem (2003).
4. Empirical Validation
To complement the theoretical analysis, we present empirical benchmarks confirming the predicted behavior of each algorithm.
4.1 Experimental Setup
We evaluate the algorithms on two canonical synthetic datasets with points each:
Dataset A (Gaussian Blobs): Three well-separated isotropic Gaussian clusters with and centers at (0,0), (4,0), and (2,3.5). This represents the ideal case for -means.
Dataset B (Two Moons): Two interleaving half-circles (sklearn.datasets.make_moons with noise = 0.05). This represents non-convex manifold structure where -means is expected to fail.
All experiments were conducted using Python 3.11 with scikit-learn 1.3. Each algorithm was run 10 times with different random seeds.
4.2 Metrics
- Silhouette Score (Definition 9): Internal cluster quality measure, higher is better.
- Adjusted Rand Index (ARI): External validity measure comparing to ground truth, 1.0 = perfect recovery.
- Runtime: Wall-clock time in seconds.
4.3 Results
4.4 Analysis
The empirical results confirm the theoretical predictions:
Prediction 1 (Proposition 4 - Voronoi structure): -Means achieves near-optimal performance on Gaussian blobs but fails catastrophically on the Two Moons dataset (ARI , equivalent to random assignment). This confirms that the Voronoi tessellation constraint prevents -means from capturing non-convex cluster boundaries.
Prediction 2 (Theorem 6 - DBSCAN correctness): DBSCAN perfectly recovers the ground truth (ARI = 1.0) on both datasets when is appropriately tuned. On Two Moons, DBSCAN identifies the manifold structure that -means cannot.
Prediction 3 (Complexity - Theorem 7): Runtime measurements confirm the theoretical complexity hierarchy. -Means is fastest, while HAC is slowest due to its distance matrix computation.
5. Discussion
5.1 Interpretation
The analysis reveals a fundamental tension in clustering: between optimization-based approaches (-means) with clear objectives but strong geometric assumptions, and geometric/topological approaches (DBSCAN) with flexible cluster shapes but no global objective. This tension reflects the inherent ambiguity of the clustering problem. Kleinberg's impossibility theorem (2003) makes this precise.
The -means++ result (Theorem 5) is particularly significant because it provides a polynomial-time algorithm with a provable approximation guarantee for an NP-hard problem.
5.2 Limitations
Several assumptions in our analysis are restrictive:
- Assumption 1 (Euclidean metric) excludes important settings such as clustering with Bregman divergences, edit distances, or graph distances.
- Assumption 4 (low-dimensional indexing for DBSCAN) is limiting for modern high-dimensional data.
- We have not analyzed the problem of selecting (for -means) or and (for DBSCAN).
5.3 Connections
The -means objective is intimately connected to principal component analysis (PCA). The continuous relaxation of -means indicator variables recovers a spectral relaxation solvable via the top eigenvectors — this is the basis of spectral clustering (von Luxburg, 2007).
DBSCAN connects to topological data analysis: as increases, the Vietoris–Rips complex grows, and DBSCAN clusters correspond roughly to connected components at a fixed scale.
5.4 Open Questions
- Can the approximation guarantee of -means++ be improved to ?
- Is there a density-based clustering algorithm with formal optimality guarantees?
- What is the precise polynomial dependence of smoothed complexity on , and ?
6. Conclusion
This article has provided a rigorous comparative analysis of three fundamental clustering paradigms, combining theoretical proofs with empirical validation.
Key contributions:
-
Lloyd's algorithm converges as a block coordinate descent procedure on the WCSS objective (Theorem 1), despite superpolynomial worst-case iteration complexity (Theorem 2).
-
-means++ achieves an -approximation to the optimal WCSS via a novel cost reduction lemma (Theorem 5).
-
DBSCAN correctness was proven via a rigorous symmetry lemma (Lemma 2, Theorem 6) with worst-case complexity.
-
Ward-WCSS connection (Theorem 8) establishes hierarchical clustering as a greedy WCSS minimizer.
Empirical benchmarks confirmed all theoretical predictions: -means fails on non-convex data (ARI = 0.5), while DBSCAN achieves perfect recovery (ARI = 1.0). The comparative framework demonstrates that algorithmic choice is governed by the geometric properties of the data. Kleinberg's impossibility theorem provides the deepest explanation: no single clustering paradigm can satisfy all natural desiderata simultaneously.
Abdelbadie Khoubiza
Full-Stack Developer passionate about React, Next.js and Node.js