880. Fast k-means assignment step
Why it matters k-means is still used for vector quantization, IVF indexes in vector databases and data dedup. The assignment step is where the time goes.
assign_clusters(X, C) returns, for every point, the index of the nearest centroid by squared Euclidean distance. Ties go to the lower centroid index (np.argmin behaviour).
Inputs: X is a list or ndarray of shape (n, d), C of shape (k, d).
Return an ndarray of ints with shape (n,).
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 90 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def assign_clusters(X, C)Example 1
Input: assign_clusters([[0.0, 0.0], [9.0, 9.0], [4.0, 5.0]], [[0.0, 1.0], [10.0, 10.0]])
Output: [0, 1, 0]
Example 2
Input: X = [[1.0]], C = [[0.0], [2.0]]
Output: [0]
Constraints
Chas shape(k, d)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Loop over centroids, not points, if you loop at all.
Hint 2
Stack the k distance columns into an (n, k) array.
Hint 3
argmin along axis 1.
Common mistakes
- argmin along axis 0.
- Using the expansion ||x||^2 - 2 x.c + ||c||^2, which can break exact ties because of rounding.
- Taking sqrt (not needed for argmin).
Understand the idea
The loop costs one NumPy call per point. Looping over the k centroids instead (k is small) and computing all n distances in each pass gives an (n, k) distance matrix with only k NumPy calls. Full broadcasting X[:, None] - C[None] also works but builds an (n, k, d) array.
Shapes and data flow
X: (n, d). C: (k, d). distances: (n, k). Output: (n,).