Build K-Means from Scratch and Contrast It with GMM
Machine LearningModel answerLast updated
Implement Lloyd's algorithm with k-means++ seeding, handle edge cases, then explain how Gaussian Mixture Models and EM extend the core idea.
Clustering from Scratch
You are given a 2-D NumPy array X of shape (n_samples, n_features) and an integer k. Write a function:
def kmeans(X, k, max_iter=300, tol=1e-6, seed=None):
...
return centroids, labels, inertia, n_iter
Your implementation must cover all four stages of the algorithm:
- Initialization — seed
kstarting centroids using the k-means++ strategy (not random uniform). - Assignment — assign every point to its closest centroid by squared Euclidean distance.
- Update — move each centroid to the mean of the points currently assigned to it.
- Convergence — stop when assignments are unchanged, total centroid shift falls below
tol, ormax_iteris reached.
You also need to handle these edge cases explicitly:
koutside the valid range[1, n_samples]should raise aValueError.- One or more centroids receiving zero points in an iteration (empty cluster).
- Numerical precision issues when computing squared distances.
Add at least one correctness assertion — for example, verify that within-cluster loss never increases between iterations.
After writing the code, answer the following questions in prose:
Q1. How does a Gaussian Mixture Model differ from K-Means in terms of assignments, cluster geometry, and what the model ultimately represents?
Q2. Walk through the EM algorithm for fitting a GMM: what are the E-step and M-step doing, and what objective are they optimizing?
Q3. In what real-world scenarios would you reach for a GMM instead of K-Means?
Hints
Hint 1
For k-means++ initialization, pick the first centroid uniformly at random, then select each subsequent centroid with probability proportional to the squared distance from a point to its nearest already-chosen centroid. This spreads seeds out and reduces the chance of a poor starting configuration.
Hint 2
An empty cluster makes the mean undefined. A practical fix is to relocate that centroid to the point currently farthest from its assigned centroid — this keeps inertia non-increasing and guarantees the empty cluster contributes something useful in the next iteration.
Hint 3
K-Means is a degenerate case of GMM: fix all covariances to σ²I with equal mixing weights and let σ → 0. The soft responsibilities collapse to hard one-hot assignments and EM becomes exactly Lloyd's algorithm. Keeping this connection in mind makes the GMM comparison much easier to explain.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
K-Means minimizes within-cluster inertia:
$$J = \sum_{i=1}^{n} \lVert x_i - \mu_{c_i} \rVert^2$$
Lloyd's algorithm alternates two steps, each of which is an exact minimization of $J$ over one set of variables while the other is held fixed. Because $J$ is bounded below by zero and each step cannot increase it, the algorithm is guaranteed to terminate — though at a local minimum, not necessarily the global one.
Why k-means++ matters. Random seeding can place two initial centroids near the same cluster, giving poor solutions. k-means++ samples each new centroid with probability proportional to $D(x)^2$, the squared distance to the nearest centroid already chosen. This spreads seeds across the space, provides an $O(\log k)$ competitive guarantee on expected inertia, and in practice converges in fewer iterations.
Empty cluster fix. When no points are assigned to a centroid, its mean is undefined. The standard recovery is to move the centroid to the point with the highest individual loss. That point then sits at distance zero in the next assignment step, strictly reducing inertia.
Numerical stability. Expanding $\lVert x - \mu \rVert^2 = \lVert x \rVert^2 - 2x \cdot \mu + \lVert \mu \rVert^2$ and computing with matrix operations is efficient but can produce tiny negative values due to floating-point rounding. Clipping at zero prevents downstream issues.
Complexity
- Seeding (k-means++): $O(nkd)$
- Per iteration: $O(nkd)$ for distances, $O(nd)$ for centroid updates
- Total: $O(T \cdot nkd)$ where $T$ is the number of iterations
- Space: $O(nk)$ for the distance matrix; $O(kd)$ for centroids
For very large n, compute the distance matrix in row chunks to avoid memory pressure.
Python Implementation
import numpy as np
def _sq_dists(X: np.ndarray, C: np.ndarray) -> np.ndarray:
"""Compute squared Euclidean distances, returning shape (n, k).
Uses the expansion ||x - c||^2 = ||x||^2 - 2*x·c + ||c||^2,
then clips at zero to guard against floating-point negatives.
"""
d = (
(X ** 2).sum(axis=1)[:, None]
- 2 * (X @ C.T)
+ (C ** 2).sum(axis=1)[None, :]
)
return np.maximum(d, 0.0)
def _kmeans_plus_plus(X: np.ndarray, k: int, rng: np.random.Generator) -> np.ndarray:
"""Seed k centroids using the k-means++ strategy."""
n = X.shape[0]
first = rng.integers(n)
centroids = [X[first]]
# Track each point's squared distance to the nearest chosen centroid
min_sq_dist = _sq_dists(X, X[[first]])[:, 0]
for _ in range(1, k):
total = min_sq_dist.sum()
if total == 0:
# All remaining candidate points coincide with existing centroids
idx = int(rng.integers(n))
else:
idx = int(rng.choice(n, p=min_sq_dist / total))
centroids.append(X[idx])
# Update min distances incrementally
new_dists = _sq_dists(X, X[[idx]])[:, 0]
min_sq_dist = np.minimum(min_sq_dist, new_dists)
return np.array(centroids, dtype=float)
def kmeans(
X,
k: int,
max_iter: int = 300,
tol: float = 1e-6,
seed=None,
):
"""Lloyd's K-Means with k-means++ initialization.
Parameters
----------
X : array-like, shape (n_samples, n_features)
k : number of clusters
max_iter : iteration cap
tol : stop when total squared centroid shift <= tol
seed : RNG seed for reproducibility
Returns
-------
centroids : ndarray, shape (k, n_features)
labels : ndarray, shape (n_samples,)
inertia : float, final within-cluster sum of squared distances
n_iter : int, number of iterations completed
"""
X = np.asarray(X, dtype=float)
if X.ndim != 2:
raise ValueError("X must be 2-D with shape (n_samples, n_features).")
n = X.shape[0]
if not (1 <= k <= n):
raise ValueError(f"k must satisfy 1 <= k <= n_samples; got k={k}, n={n}.")
rng = np.random.default_rng(seed)
C = _kmeans_plus_plus(X, k, rng)
labels = np.full(n, -1, dtype=int)
prev_inertia = np.inf
for it in range(1, max_iter + 1):
# ── Assignment step ───────────────────────────────────────────────
D = _sq_dists(X, C) # (n, k)
new_labels = D.argmin(axis=1) # (n,)
point_costs = D[np.arange(n), new_labels]
inertia = float(point_costs.sum())
# Monotonicity guard: inertia must never increase
slack = 1e-9 * max(1.0, prev_inertia)
assert inertia <= prev_inertia + slack, (
f"Inertia increased: {prev_inertia:.6f} → {inertia:.6f}"
)
prev_inertia = inertia
if np.array_equal(new_labels, labels):
labels = new_labels
break # exact fixed point
labels = new_labels
# ── Update step ───────────────────────────────────────────────────
counts = np.bincount(labels, minlength=k) # (k,)
new_C = np.zeros_like(C)
np.add.at(new_C, labels, X)
nonempty = counts > 0
new_C[nonempty] /= counts[nonempty, None]
# ── Empty cluster recovery ────────────────────────────────────────
empty_idx = np.flatnonzero(~nonempty)
if empty_idx.size:
# Relocate each empty centroid to a distinct high-cost point
far_points = np.argsort(point_costs)[::-1][: empty_idx.size]
new_C[empty_idx] = X[far_points]
shift = float(((new_C - C) ** 2).sum())
C = new_C
if shift <= tol:
break
# Recompute labels and inertia consistently against the final centroids
D = _sq_dists(X, C)
labels = D.argmin(axis=1)
inertia = float(D[np.arange(n), labels].sum())
return C, labels, inertia, it
# ── Quick smoke test ──────────────────────────────────────────────────────────
if __name__ == "__main__":
rng = np.random.default_rng(42)
blobs = np.vstack([
rng.normal(loc, 0.3, (100, 2))
for loc in ([0, 0], [6, 0], [3, 5])
])
C, labels, inertia, iters = kmeans(blobs, k=3, seed=0)
assert len(set(labels.tolist())) == 3, "Expected 3 non-empty clusters"
counts = sorted(np.bincount(labels).tolist())
assert counts == [100, 100, 100], f"Unexpected cluster sizes: {counts}"
print("Centroids:\n", np.round(C, 2))
print(f"Inertia: {inertia:.2f} | Iterations: {iters}")
Q1: How GMM Differs from K-Means
The core difference is hard vs. soft assignment. K-Means forces each point into exactly one cluster. A GMM instead assigns every point a responsibility — the posterior probability $\gamma_{ij} = P(z = j \mid x_i)$ that point $i$ came from component $j$. A point near two cluster boundaries shares probability mass between them rather than being arbitrarily snapped to one.
The second difference is cluster geometry. K-Means produces Voronoi cells — always convex, roughly spherical regions of equal width. A GMM can model elongated, rotated ellipses through a full covariance matrix $\Sigma_j$ per component.
Finally, GMM is a generative model. It defines a proper probability density $p(x) = \sum_j \pi_j \mathcal{N}(x \mid \mu_j, \Sigma_j)$, which means you can score new points, compute likelihoods, detect outliers, and draw samples. K-Means produces a partition but no density.
Q2: EM for GMM
The objective is the log-likelihood $\sum_i \log \sum_j \pi_j \mathcal{N}(x_i \mid \mu_j, \Sigma_j)$, which is intractable to maximize directly because the sum is inside the log. EM introduces a latent variable $z_i$ (the component that generated $x_i$) and iterates two steps:
E-step — compute the responsibilities using Bayes' rule: $$\gamma_{ij} = \frac{\pi_j \mathcal{N}(x_i \mid \mu_j, \Sigma_j)}{\sum_{l} \pi_l \mathcal{N}(x_i \mid \mu_l, \Sigma_l)}$$ This is cheap: just evaluate Gaussian densities and normalize.
M-step — update parameters using the responsibilities as soft counts. Let $N_j = \sum_i \gamma_{ij}$: $$\pi_j = \frac{N_j}{n}, \quad \mu_j = \frac{1}{N_j}\sum_i \gamma_{ij} x_i, \quad \Sigma_j = \frac{1}{N_j}\sum_i \gamma_{ij}(x_i - \mu_j)(x_i - \mu_j)^\top$$
Each step increases a lower bound on the log-likelihood, so the objective is monotonically non-decreasing. Convergence is to a local maximum, just as K-Means converges to a local minimum.
Q3: When to Prefer GMM over K-Means
- Overlapping or elongated clusters — financial returns, sensor noise, and many natural datasets are not spherical. GMM handles these without any preprocessing.
- Uncertainty quantification — if you need to know how confident the model is in each assignment (e.g., flagging borderline customers for manual review), soft responsibilities are directly useful.
- Density estimation or anomaly detection — because GMM defines $p(x)$, you can threshold the likelihood to flag outliers. K-Means inertia is not a proper density.
- Clusters of very different sizes or densities — K-Means pulls cluster boundaries toward smaller or denser groups because it minimizes squared distance, not likelihood. GMM's per-component weights and covariances adapt independently.
Common mistakes to avoid: forgetting to standardize features before K-Means (it is not scale-invariant); ignoring degenerate covariances in GMM when a component collapses onto a single point (requires regularization, e.g. adding $\epsilon I$ to $\Sigma_j$); and running only one random restart — both algorithms are sensitive to initialization and benefit from multiple runs with the best result kept.