Build a Clustering Algorithm and Analyze Its Behavior
Machine LearningModel answerLast updated
Write a clustering algorithm that groups data points iteratively, then explain the cost function it optimizes and why it terminates.
Problem
Write a function that partitions a dataset into k groups by iteratively assigning points to nearby centers and repositioning those centers. Your implementation should work with numerical data in any dimension.
Function Interface
def cluster_points(data, k, max_iters=100):
"""
Partition data into k clusters.
Args:
data: array-like of shape (n_samples, n_features)
k: number of clusters to form
max_iters: maximum iterations before stopping
Returns:
centers: array of shape (k, n_features) — final cluster centers
labels: array of shape (n_samples,) — cluster index for each point
"""
Requirements
- Measure distance using the standard Euclidean metric
- Initialize centers by randomly selecting
kdistinct points from the dataset - Alternate between two steps:
- Assign each point to its closest center
- Recompute each center as the average of its assigned points
- Stop when centers stabilize or
max_itersis reached - Handle the case where a center has no assigned points (re-initialize it)
Constraints
- Up to 10,000 samples, up to 50 features
1 ≤ k ≤ n_samples
Example
data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]
centers, labels = cluster_points(data, k=2)
# centers will typically converge near [1, 2] and [10, 2]
# labels might be [0, 0, 0, 1, 1, 1] (exact indices depend on initialization)
Conceptual Questions
After implementing the function, address these points:
-
Objective function: What quantity does this algorithm minimize? Write it mathematically.
-
Convergence guarantee: Why must the algorithm reach a stopping point in finite steps? Does it find the global optimum?
-
Computational cost: What is the time complexity of one iteration in terms of
n(samples),k(clusters), andd(features)? -
Practical considerations: What initialization strategies improve results? How would you choose
kfor real data?
Hints
Hint 1
Compute all pairwise distances at once using matrix operations rather than nested loops
Hint 2
The squared distance ||x - c||² can be expanded as ||x||² - 2·x·c + ||c||² to avoid computing square roots
Hint 3
Each iteration decreases (or keeps constant) a well-defined cost, and there are only finitely many possible partitions
Hint 4
If a cluster becomes empty, reassign its center to the point that is currently farthest from its assigned center
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution
Algorithm Overview
The clustering procedure alternates between two operations until convergence:
- Assignment: Given fixed centers, assign each point to the nearest center by Euclidean distance
- Repositioning: Given fixed assignments, move each center to the mean (centroid) of its assigned points
This is Lloyd's algorithm, commonly known as K-means. Each step optimally solves one half of the problem while holding the other half constant.
Objective Function
The algorithm minimizes the within-cluster sum of squared distances:
J = Σᵢ₌₁ⁿ ||xᵢ - μ_{label(i)}||²
where xᵢ is the i-th data point, label(i) indicates which cluster it belongs to, and μⱼ is the center of cluster j.
This is a coordinate descent procedure: the assignment step minimizes J over labels with centers fixed, and the repositioning step minimizes J over centers with labels fixed. Finding the global minimum is NP-hard; Lloyd's algorithm finds a local minimum.
Why Convergence is Guaranteed
The cost J never increases. Each assignment step picks the closest center for each point, which minimizes that point's contribution to J. Each repositioning step sets each center to the arithmetic mean of its points, which is the unique minimizer of the sum of squared distances for a fixed set of points (this follows from taking the gradient and setting it to zero).
There are finitely many partitions. With n points and k clusters, there are at most k^n possible labelings (in practice, far fewer are reachable). Since J decreases or stays constant and each partition produces a deterministic set of centers, the algorithm cannot cycle (with consistent tie-breaking, such as always picking the lowest index in case of equal distances). Therefore, it must reach a fixed point in finite steps.
Caveat: The algorithm converges to a local minimum, not necessarily the global one. The final result depends on initialization, which is why multiple restarts or smarter seeding (like K-means++) are used in practice.
Complexity Analysis
Per iteration:
- Computing all n×k distances: O(n·k·d)
- Finding the nearest center for each point: O(n·k)
- Summing points per cluster and dividing: O(n·d)
The distance computation dominates, so one iteration costs O(n·k·d).
Total runtime: O(I·n·k·d) where I is the number of iterations. In practice I is small (often 10–100), but pathological examples can require exponentially many iterations in theory.
Space: O(n·d + k·d + n·k) for data, centers, and the distance matrix.
At n=10,000, k=20, d=50, one iteration involves ~10 million operations, which runs in milliseconds with vectorized code.
Implementation
import numpy as np
def cluster_points(data, k, max_iters=100):
X = np.asarray(data, dtype=float)
if X.ndim != 2:
raise ValueError("data must be 2D")
n, d = X.shape
if not (1 <= k <= n):
raise ValueError(f"k must be between 1 and {n}")
# Initialize: pick k distinct points randomly
indices = np.random.choice(n, size=k, replace=False)
centers = X[indices].copy()
# Precompute squared norms of data points (constant)
x_squared_norms = np.einsum("ij,ij->i", X, X)
labels = None
for iteration in range(max_iters):
# Assignment: find nearest center for each point
# ||x - c||² = ||x||² - 2·x·c + ||c||²
c_squared_norms = np.einsum("ij,ij->i", centers, centers)
distances_sq = (
x_squared_norms[:, None]
- 2.0 * (X @ centers.T)
+ c_squared_norms[None, :]
)
# Clip tiny negatives from floating point error
np.maximum(distances_sq, 0.0, out=distances_sq)
labels = np.argmin(distances_sq, axis=1)
# Repositioning: move each center to the mean of its points
new_centers = np.zeros_like(centers)
counts = np.bincount(labels, minlength=k)
for j in range(k):
mask = (labels == j)
if counts[j] > 0:
new_centers[j] = X[mask].mean(axis=0)
else:
# Empty cluster: reinitialize to the worst-served point
point_costs = distances_sq[np.arange(n), labels]
farthest = np.argmax(point_costs)
new_centers[j] = X[farthest]
# Check convergence
if np.allclose(centers, new_centers):
centers = new_centers
break
centers = new_centers
# Recompute labels to be consistent with final centers
c_squared_norms = np.einsum("ij,ij->i", centers, centers)
distances_sq = (
x_squared_norms[:, None]
- 2.0 * (X @ centers.T)
+ c_squared_norms[None, :]
)
labels = np.argmin(distances_sq, axis=1)
return centers, labels
Edge Cases and Implementation Notes
-
Empty clusters: When no points are assigned to a center, reinitialize it to the point currently farthest from its assigned center. This decreases total cost (that point's cost drops to zero) and maintains the descent property.
-
Vectorization: The distance computation uses the expanded form of squared Euclidean distance to avoid loops. The matrix multiply
X @ centers.Tis the bottleneck. -
Numerical stability: The squared distance can be slightly negative due to floating point error. Clipping to zero prevents issues with downstream operations.
-
Final consistency: After the loop, recompute labels against the final centers to ensure the return values match.
Practical Improvements
K-means++ initialization: Instead of random centers, choose the first center uniformly at random, then iteratively add centers with probability proportional to squared distance from the nearest existing center. This spreads out initial centers and typically reduces iterations while improving final cost.
Multiple restarts: Run the algorithm several times with different initializations and keep the result with lowest J.
Choosing k: Use the elbow method (plot J vs. k and look for diminishing returns), silhouette score (measures cluster cohesion vs. separation), or cross-validation on a downstream task.
Common Mistakes
- Using nested Python loops for distances (O(n²·k·d) is prohibitive at scale)
- Not handling empty clusters, leading to NaN centers
- Claiming the algorithm finds the global optimum (it finds a local one)
- Forgetting to recompute labels after the final center update
- Initializing centers in ways that allow duplicates (causes immediate empty clusters)
This algorithm is fundamental to unsupervised learning and appears in many variations (soft clustering, kernel K-means, mini-batch K-means). Understanding its mechanics, guarantees, and limitations is essential for applying it effectively.