KatInterview

Build a Centroid-Based Point Grouper Using Numpy

Machine LearningModel answer
MediumModel answerMachine Learningk-meansclusteringnumpy

Last updated

Write a vectorized k-means routine that groups N points into k clusters by alternating nearest-centroid assignment with mean updates, handling empty clusters and convergence.

Group Points Into Clusters

You are given a numpy array of points and a target number of groups k. Write a function that partitions the points into k clusters using the classic iterative centroid method (Lloyd's algorithm), without using any clustering library.

Signature

import numpy as np

def kmeans(points, k, max_iters=100):
    # points: numpy array of shape (N, D)
    # k: number of clusters
    # returns: (centroids, labels)
    #   centroids has shape (k, D)
    #   labels has shape (N,), the cluster index of each point
    pass

Required behavior

  • Seeding: pick k points from the input at random to serve as the starting centroids.
  • Assignment: each point goes to the centroid with the smallest Euclidean distance.
  • Update: each centroid moves to the arithmetic mean of the points currently assigned to it.
  • Stopping: stop when the centroids no longer move meaningfully, or after max_iters rounds.
  • Empty clusters: if a cluster ends up with no points after an assignment, give it a new centroid by choosing a random point from the dataset.

Example

points = np.array([[1, 2], [1, 4], [1, 0],
                   [10, 2], [10, 4], [10, 0]])
k = 2

Two groups should emerge: one centered near (1, 2) and the other near (10, 2). Which group receives label 0 may vary from run to run.

Constraints

  • 1 <= k <= N
  • N is between 1 and 10,000

Expected in your answer

  1. A working, preferably vectorized, implementation.
  2. An explanation of why the procedure converges and what it converges to.
  3. Time and space complexity.
  4. Discussion of the edge cases: stalled centroids, empty clusters, k == N, k == 1, duplicate points, integer input.
  5. Brief remarks on weaknesses (initialization sensitivity, choosing k) and how you would address them.

Hints

Hint 1

Think of the algorithm as two alternating moves that both reduce the total squared distance from points to their assigned centroids: reassign points with centroids fixed, then recompute centroids with assignments fixed.

Hint 2

Avoid looping over points and centroids in Python. Compute an (N, k) matrix of squared distances with array operations (for example expanding ||x - c||^2 into three terms), then take argmin along axis 1. Squared distances give the same nearest centroid as true distances.

Hint 3

For the update, count points per cluster with bincount and accumulate sums with np.add.at, since plain fancy-index += drops repeated indices. Counts of zero identify empty clusters to re-seed.

Hint 4

Cast the input to float, and after the loop run one more assignment so the returned labels match the returned centroids, even if you exited because of max_iters.