Vectorized K-Means with Lloyd's Algorithm

Quick Overview

Implement k-means with Lloyd's algorithm in NumPy using broadcasting: nearest-centroid assignment with lowest-index ties, a vectorized mean update that keeps empty clusters in place, and a per-iteration inertia history. It tests array shapes, exact iteration semantics, and how the result compares with scikit-learn.

Vectorized K-Means with Lloyd's Algorithm

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `assign_clusters(X, centroids)`, which returns each row's nearest-centroid index by squared Euclidean distance, using broadcasting with no Python loops over points. Ties go to the lowest centroid index. Then implement `kmeans(X, init_centroids, max_iter=100, tol=1e-4)`, which runs Lloyd's algorithm and returns `(labels, centroids, inertia, inertia_history)`. `kmeans` follows these rules: - Each iteration assigns the points, sets every centroid to the mean of its points, then appends to `inertia_history` the inertia (a float) of that iteration's labels measured against the new centroids. - An empty cluster keeps its previous centroid. - The loop stops when the largest L2 centroid shift is `<= tol`, or after `max_iter` iterations. - The returned `labels` (an int array) and `inertia` (a float, the sum of squared distances) are recomputed against the final centroids. - `init_centroids` must not be mutated. ```python X = [[0], [1], [2], [9], [10]] kmeans(X, init_centroids=[[0], [1]], max_iter=1, tol=0.0) # labels -> [0, 0, 0, 1, 1] # centroids -> [[0.0], [5.5]] # inertia -> 37.5 # history -> [65.0] (one entry: iteration-1 labels against the new centroids) ``` In the single iteration, point 1 sits exactly on the second initial centroid, so that iteration's labels are `[0, 1, 1, 1, 1]` and the second centroid moves to `22 / 4 = 5.5`. The history entry scores those labels against `[[0], [5.5]]`, which gives `0 + 20.25 + 12.25 + 12.25 + 20.25 = 65`. The returned labels are recomputed against the final centroids, which moves points 1 and 2 back to cluster 0, so the inertia is `0 + 1 + 4 + 12.25 + 20.25 = 37.5`. ```hint Shapes first Write down the shape of every array before writing code. Distances to all centroids fit in one `(n, k)` array, and the per-cluster sums fit in one `(k, d)` array. ``` ```hint Empty clusters Count each cluster's members before you divide. A count of zero is exactly the case where the old centroid has to survive. ``` ### Constraints & Assumptions - `X` has shape `(n, d)` and `init_centroids` has shape `(k, d)`, with `n` up to a few hundred. - With `tol=0`, the same `max_iter`, no cluster going empty and no exact distance ties, the result should match scikit-learn's `KMeans(n_clusters=k, init=init_centroids, n_init=1, algorithm="lloyd", tol=0, max_iter=max_iter)` within `1e-6`. ### What a Strong Answer Covers - A broadcast distance computation with lowest-index tie-breaking and no loop over points. - A vectorized mean update from per-cluster counts and sums that leaves empty clusters at their previous centroid and never mutates the input. - History entries computed from each iteration's labels against its updated centroids, and the stopping rule on the largest L2 shift. - Final labels and inertia recomputed against the final centroids, with the right types. - The time and memory cost, and the places where the result can differ from scikit-learn. ### Follow-up Questions - The `(n, k, d)` broadcast uses too much memory for large inputs. How would you fix it? - How would you handle empty clusters other than keeping the old centroid? - How would you choose initial centroids instead of taking them as input?

Overview: Implement k-means with Lloyd's algorithm in NumPy using broadcasting: nearest-centroid assignment with lowest-index ties, a vectorized mean update that keeps empty clusters in place, and a per-iteration inertia history. It tests array shapes, exact iteration semantics, and how the result compares with scikit-learn.

PracHub logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement assign_clusters(X, centroids), which returns each row's nearest-centroid index by squared Euclidean distance, using broadcasting with no Python loops over points. Ties go to the lowest centroid index. Then implement kmeans(X, init_centroids, max_iter=100, tol=1e-4), which runs Lloyd's algorithm and returns (labels, centroids, inertia, inertia_history).

kmeans follows these rules:

  • Each iteration assigns the points, sets every centroid to the mean of its points, then appends to inertia_history the inertia (a float) of that iteration's labels measured against the new centroids.
  • An empty cluster keeps its previous centroid.
  • The loop stops when the largest L2 centroid shift is <= tol , or after max_iter iterations.
  • The returned labels (an int array) and inertia (a float, the sum of squared distances) are recomputed against the final centroids.
  • init_centroids must not be mutated.
X = [[0], [1], [2], [9], [10]]
kmeans(X, init_centroids=[[0], [1]], max_iter=1, tol=0.0)
# labels    -> [0, 0, 0, 1, 1]
# centroids -> [[0.0], [5.5]]
# inertia   -> 37.5
# history   -> [65.0]   (one entry: iteration-1 labels against the new centroids)

In the single iteration, point 1 sits exactly on the second initial centroid, so that iteration's labels are [0, 1, 1, 1, 1] and the second centroid moves to 22 / 4 = 5.5. The history entry scores those labels against [[0], [5.5]], which gives 0 + 20.25 + 12.25 + 12.25 + 20.25 = 65. The returned labels are recomputed against the final centroids, which moves points 1 and 2 back to cluster 0, so the inertia is 0 + 1 + 4 + 12.25 + 20.25 = 37.5.

Constraints & Assumptions

  • X has shape (n, d) and init_centroids has shape (k, d) , with n up to a few hundred.
  • With tol=0 , the same max_iter , no cluster going empty and no exact distance ties, the result should match scikit-learn's KMeans(n_clusters=k, init=init_centroids, n_init=1, algorithm="lloyd", tol=0, max_iter=max_iter) within 1e-6 .

What a Strong Answer Covers Guidance

  • A broadcast distance computation with lowest-index tie-breaking and no loop over points.
  • A vectorized mean update from per-cluster counts and sums that leaves empty clusters at their previous centroid and never mutates the input.
  • History entries computed from each iteration's labels against its updated centroids, and the stopping rule on the largest L2 shift.
  • Final labels and inertia recomputed against the final centroids, with the right types.
  • The time and memory cost, and the places where the result can differ from scikit-learn.

Follow-up Questions Guidance

  • The (n, k, d) broadcast uses too much memory for large inputs. How would you fix it?
  • How would you handle empty clusters other than keeping the old centroid?
  • How would you choose initial centroids instead of taking them as input?