KatInterview

Build a Clustering Algorithm and Analyze Its Behavior

Machine LearningModel answer
MediumModel answerMachine Learningclusteringunsupervised-learningoptimization

Last updated

Write a clustering algorithm that groups data points iteratively, then explain the cost function it optimizes and why it terminates.

Problem

Write a function that partitions a dataset into k groups by iteratively assigning points to nearby centers and repositioning those centers. Your implementation should work with numerical data in any dimension.

Function Interface

def cluster_points(data, k, max_iters=100):
    """
    Partition data into k clusters.
    
    Args:
        data: array-like of shape (n_samples, n_features)
        k: number of clusters to form
        max_iters: maximum iterations before stopping
    
    Returns:
        centers: array of shape (k, n_features) — final cluster centers
        labels: array of shape (n_samples,) — cluster index for each point
    """

Requirements

  • Measure distance using the standard Euclidean metric
  • Initialize centers by randomly selecting k distinct points from the dataset
  • Alternate between two steps:
    1. Assign each point to its closest center
    2. Recompute each center as the average of its assigned points
  • Stop when centers stabilize or max_iters is reached
  • Handle the case where a center has no assigned points (re-initialize it)

Constraints

  • Up to 10,000 samples, up to 50 features
  • 1 ≤ k ≤ n_samples

Example

data = [[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]
centers, labels = cluster_points(data, k=2)
# centers will typically converge near [1, 2] and [10, 2]
# labels might be [0, 0, 0, 1, 1, 1] (exact indices depend on initialization)

Conceptual Questions

After implementing the function, address these points:

  1. Objective function: What quantity does this algorithm minimize? Write it mathematically.

  2. Convergence guarantee: Why must the algorithm reach a stopping point in finite steps? Does it find the global optimum?

  3. Computational cost: What is the time complexity of one iteration in terms of n (samples), k (clusters), and d (features)?

  4. Practical considerations: What initialization strategies improve results? How would you choose k for real data?

Hints

Hint 1

Compute all pairwise distances at once using matrix operations rather than nested loops

Hint 2

The squared distance ||x - c||² can be expanded as ||x||² - 2·x·c + ||c||² to avoid computing square roots

Hint 3

Each iteration decreases (or keeps constant) a well-defined cost, and there are only finitely many possible partitions

Hint 4

If a cluster becomes empty, reassign its center to the point that is currently farthest from its assigned center