BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Unsupervised learning8 of 15 in topic

144. Run k-means to convergence and re-seed empty clusters

MediumUnsupervised learning Pro
Asked atAmazonAnthropicByteDanceMeta

Why it matters k-means is used for customer segmentation, vector quantisation and IVF indexes in vector databases, and the empty-cluster rule is a common production bug.

A full k-means loop repeats assign and update until the centers stop moving. Real implementations also need a rule for a cluster that loses all its points.

Write kmeans_fit(X, init_centers, max_iter=100). Each iteration: assign every point to its nearest center by squared Euclidean distance (lowest center index on ties), then recompute each center as the mean of its points. If a cluster is empty, move its center onto a point that is far from its own center: sort points by their squared distance to their assigned center, largest first (stable), and give the empty clusters (in index order) the points in that order. Stop when the new centers equal the old ones exactly or after max_iter iterations. Return (centers, labels, n_iter, inertia) where labels and inertia (sum of squared distances to the nearest center) are computed from the final centers and n_iter counts the iterations run.

Functiondef kmeans_fit(X, init_centers, max_iter=100)

Example 1

Input: X [[0, 0], [0, 1], [5, 5], [6, 5]], init_centers [[0, 0], [5, 5]]

Output: centers [[0, 0.5], [5.5, 5]], labels [0, 0, 1, 1], n_iter 2 and inertia 1.0

Example 2

Input: X = [[0, 0], [1, 0], [0, 1], [9, 9]], init_centers = [[0, 0], [50, 50]]

Output: ([[0.333333, 0.333333], [9.0, 9.0]], [0, 0, 0, 1], 3, 1.333333)

Constraints

  • Python 3 with NumPy. Code runs in your browser.
  • Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1

Write an assign helper; call it inside the loop and once more at the end.

Hint 2

Broadcast X[:, None, :] - C[None, :, :] for all squared distances.

Hint 3

np.array_equal(newC, C) is the stopping test.

Hint 4

For empty clusters use the points sorted by distance to their own center, largest first.

Common mistakes
  • Taking the mean of an empty cluster, which gives NaN.
  • Leaving a dead center in place.
  • Reporting labels from before the last update.
Understand the idea

k-means alternates two easy steps. Assign: each point joins the nearest center. Update: each center moves to the average of its points. Each step can only lower the total squared distance (the inertia), so the loop settles down, usually in a few iterations.

Worked example

points (0, 0), (0, 1), (5, 5), (6, 5) with centers (0, 0) and (5, 5). The first two points join center 0 and the last two join center 1. The new centers are (0, 0.5) and (5.5, 5). Repeating gives the same assignment and the same centers, so we stop. Inertia = 0.25 + 0.25 + 0.25 + 0.25 = 1.

Empty clusters happen when a center starts far from every point. A good fix is to move it to the point that is currently served worst, the one farthest from its own center, so the dead center becomes useful.

repeat { labels = argmin_k ||x - c_k||^2; c_k = mean of its points } until the centers stop changing

Vector databases use k-means to build IVF indexes, and marketers use it to segment customers.

Shapes and data flow
X (n, d), C (K, d) -> d2 (n, K) -> labels (n,)
Topics
Unsupervised learning
Companies6
  • Amazon a candidate reported this question Amazon AI Research Scientist interview experience (February 2025)
  • Anthropic the topic appears in interview reports Coding Exercises & ML System Design: Real AI Interview Questions (landedjobs)
  • ByteDance a candidate reported this question ByteDance Machine Learning Engineer Interview Process
  • Meta a candidate reported this question Meta Research Engineer Interview Guide (Dataford)
  • Microsoft a candidate reported this question Microsoft Senior Applied Scientist (L63) Interview Experience
  • OpenAI a candidate reported this question OpenAI interview questions, page 54 (Screna)

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Compute soft cluster memberships for a Gaussian mixtureMedium
  • Merge points bottom-up with single linkage clusteringMedium
  • Pick k-means++ starting centers deterministicallyMedium
  • Move points one mean-shift stepMedium
All Unsupervised learning problems
Report
144 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def kmeans_fit(X, init_centers, max_iter=100):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS