KatInterview

Build K-Means from Scratch and Contrast It with GMM

Machine LearningModel answer
MediumModel answerMachine Learningclusteringk-meansGMM

Last 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:

  1. Initialization — seed k starting centroids using the k-means++ strategy (not random uniform).
  2. Assignment — assign every point to its closest centroid by squared Euclidean distance.
  3. Update — move each centroid to the mean of the points currently assigned to it.
  4. Convergence — stop when assignments are unchanged, total centroid shift falls below tol, or max_iter is reached.

You also need to handle these edge cases explicitly:

  • k outside the valid range [1, n_samples] should raise a ValueError.
  • 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.