CD0010 K-Means From Scratch

Mode B · Build & Trace 30 Min NumPy 4 Array Blanks

Clustering prototypes show up constantly on Google and Waymo ML teams, and this screen (reported by candidates from both companies' coding rounds) rewards the same habit: writing a few lines of vectorized NumPy that stay correct when the data misbehaves. You must implement KMeans.fit(X, k) from scratch. It takes a float array of shape (n_samples, n_features) and returns integer cluster labels of shape (n_samples,) and centroids of shape (k, n_features). Calling sklearn.cluster.KMeans, scipy.cluster.vq, or scipy.spatial.distance.cdist is forbidden.

Initialization is fixed for this round: k distinct rows of X drawn at random, with k-means++ left as a follow-up. The interviewer cares less about the happy path than about three edge cases. A cluster can come out empty mid-run, the loop needs a defensible stopping rule, and a correct implementation must preserve specific invariants on every iteration.

Complete the 4 missing operations in the skeleton below and narrate the array shape after each line. Then state the algorithm's time complexity, explain how you would choose k, and write a test that checks invariants rather than one hand-picked output.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  class KMeans:
05      def __init__(self, max_iter: int = 100, tol: float = 1e-6, seed: int = 0):
06          self.max_iter, self.tol = max_iter, tol
07          self.rng = np.random.default_rng(seed)
08
09      def fit(self, X: np.ndarray, k: int):
10          n_samples, n_features = X.shape                    # X: (n_samples, n_features) float64
11          centroids = X[self.rng.choice(n_samples, size=k, replace=False)]   # (k, n_features)
12          self.inertia_history = []
13          for it in range(self.max_iter):
14              # TODO (Blank 1): squared distances from every point to every
15              #                 centroid, shape (n_samples, k), no Python loops
16              sq_dists = ...
17              # TODO (Blank 2): index of the nearest centroid per point, (n_samples,)
18              labels = ...
19              self.inertia_history.append(sq_dists[np.arange(n_samples), labels].sum())
20              prev_centroids = centroids.copy()
21              # TODO (Blank 3): recompute each centroid as the mean of its
22              #                 points; an empty cluster must stay finite
23              ...
24              # TODO (Blank 4): stop when the centroids have converged
25              if ...:
26                  break
27          self.centroids_, self.labels_, self.n_iter_ = centroids, labels, it + 1
28          return labels, centroids
Operator contract for KMeans.fit: input X of shape (n_samples, n_features) with k random rows as initial centroids flows through four question-marked steps (Blank 1 distances, Blank 2 assignment, Blank 3 centroid update, Blank 4 stop check) with a loop back for the next iteration, ending at labels (n_samples,) and centroids (k, n_features); below, three boxes list the edge cases the interviewer probes

Figure 1: the input and output contract is fixed, the random-row initialization is given, and the four steps inside the Lloyd loop are yours to write, with the interviewer probing empty clusters, the stopping rule, and the loop's invariants.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the invariant checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Broadcast Geometry: Align the point axis of X and the centroid axis of centroids so one subtraction covers every pair, then reduce over the feature axis only.
(2) Reduction Axis: The assignment must produce one label per point, and line 19 indexes sq_dists with exactly that shape.
(3) Empty-Cluster Contract: Decide what a centroid with zero members should be before writing the update, and keep every centroid finite.
(4) Stopping Rule: Compare the updated centroids with the snapshot on line 20 using an explicit tolerance, and remember that line 13 is the second guard.

2Visual Review Map (Figure 2)
Shape trace for KMeans.fit: X (n_samples, n_features) and centroids (k, n_features) feed question-marked blanks whose target shapes are an intermediate (n_samples, k, n_features), sq_dists (n_samples, k), labels (n_samples,), new centroids (k, n_features), and a boolean stop flag; the line 19 inertia and the line 20 prev_centroids snapshot are shown as given, with a loop back to Blank 1 for the next iteration

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce; writing the operations that reach them is the exercise.

3Interviewer Nudge & Line Focus

Pin the input shape, output shape, and failure mode of each blank before writing the NumPy call:

Blank 1 (Distance Matrix): X is (n_samples, n_features) and centroids is (k, n_features). Which singleton axes must you insert so the subtraction broadcasts to a 3-axis tensor, and which axis do you reduce? If n_samples == k, what does a plain X - centroids silently compute instead of raising?
Blank 2 (Assignment): sq_dists is (n_samples, k). Does the reduction collapse the point axis or the centroid axis, what shape would the other choice produce, and which index wins when two centroids sit at exactly the same distance?
Blank 3 (Centroid Update): If X contains duplicate rows, two initial centroids can be identical. What does averaging a (0, n_features) array return, what happens to the next distance matrix once one centroid holds that value, and which two finite choices could you make instead?
Blank 4 (Convergence): Lloyd's algorithm visits finitely many partitions, so why still compare against a tolerance in the data's units, and why does line 13 keep its bound even when your stop check is correct?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *