K-Means Restarts with ARI Stability

Quick Overview

Implement Lloyd's k-means with reproducible random restarts, keep the lowest-inertia run, and score run-to-run stability with the mean pairwise adjusted Rand index. It tests seeded initialisation, local optima, the tie and empty-cluster rules, and an ARI that matches sklearn on its edge cases.

K-Means Restarts with ARI Stability

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `adjusted_rand_index(labels_a, labels_b)` and `kmeans_restarts(X, k, n_init, seed, max_iter=300, tol=1e-10)` in Python with NumPy. Run Lloyd's k-means `n_init` times and return a dict summarising every run, the best (lowest-inertia) run, and the mean ARI over all run pairs `i < j`. The dict has these keys: - `inertias`, shape `(n_init,)` - `labels`, shape `(n_init, n)` - `best_index`, `best_labels`, `best_centroids` (shape `(k, d)`) and `best_inertia` - `mean_pairwise_ari` Example: ```python X = [[0,0],[0,1],[10,0],[10,1]] res = kmeans_restarts(X, k=2, n_init=10, seed=0) res["best_inertia"] # 1.0 res["best_centroids"] # [[0, 0.5], [10, 0.5]] (any row order) ``` ```hint Where a run can stall Trace the example by hand from the starting rows `[0, 0]` and `[0, 1]`. Where does Lloyd's algorithm stop, and what is its inertia? ``` ```hint ARI from counts Every term of ARI is a sum of "n choose 2" over the cells, the row sums or the column sums of the contingency table between two labelings. ``` ### Constraints & Assumptions - `X` is a 2-D float array of shape `(n, d)`. - Create `rng = np.random.default_rng(seed)` once. Each run initialises centroids as `X[rng.choice(n, size=k, replace=False)]`. - Assign by squared Euclidean distance (ties go to the lowest index). An empty cluster keeps its previous centroid. - Stop when the max centroid shift is `<= tol` or after `max_iter`. Then reassign and compute inertia (sum of squared distances). - `best_index` is the first argmin of inertias. `mean_pairwise_ari` is `1.0` when `n_init == 1`. - ARI must match `sklearn`'s `adjusted_rand_score`. Return `1.0` when `n < 2` or the denominator is zero. ### What a Strong Answer Covers - One generator created from `seed`, with each run drawing its starting rows in the specified way so the results are reproducible. - A Lloyd loop that follows the tie, empty-cluster, stopping and final-reassignment rules. - An ARI built from a contingency table that matches `sklearn`, including the `n < 2` and zero-denominator cases. - Best-run selection with first-argmin ties, and the pairwise mean with the single-run case. - Why restarts reach different inertias, and what a low mean pairwise ARI says about the clustering. ### Follow-up Questions - Why do different initialisations give different inertias? - How would k-means++ initialisation change these results? - How does the cost of the pairwise ARI step grow with `n_init`, and how would you cut it for hundreds of restarts?

Overview: Implement Lloyd's k-means with reproducible random restarts, keep the lowest-inertia run, and score run-to-run stability with the mean pairwise adjusted Rand index. It tests seeded initialisation, local optima, the tie and empty-cluster rules, and an ARI that matches sklearn on its edge cases.

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

Implement adjusted_rand_index(labels_a, labels_b) and kmeans_restarts(X, k, n_init, seed, max_iter=300, tol=1e-10) in Python with NumPy. Run Lloyd's k-means n_init times and return a dict summarising every run, the best (lowest-inertia) run, and the mean ARI over all run pairs i < j.

The dict has these keys:

  • inertias , shape (n_init,)
  • labels , shape (n_init, n)
  • best_index , best_labels , best_centroids (shape (k, d) ) and best_inertia
  • mean_pairwise_ari

Example:

X = [[0,0],[0,1],[10,0],[10,1]]
res = kmeans_restarts(X, k=2, n_init=10, seed=0)
res["best_inertia"]    # 1.0
res["best_centroids"]  # [[0, 0.5], [10, 0.5]] (any row order)

Constraints & Assumptions

  • X is a 2-D float array of shape (n, d) .
  • Create rng = np.random.default_rng(seed) once. Each run initialises centroids as X[rng.choice(n, size=k, replace=False)] .
  • Assign by squared Euclidean distance (ties go to the lowest index). An empty cluster keeps its previous centroid.
  • Stop when the max centroid shift is <= tol or after max_iter . Then reassign and compute inertia (sum of squared distances).
  • best_index is the first argmin of inertias. mean_pairwise_ari is 1.0 when n_init == 1 .
  • ARI must match sklearn 's adjusted_rand_score . Return 1.0 when n < 2 or the denominator is zero.

What a Strong Answer Covers Guidance

  • One generator created from seed , with each run drawing its starting rows in the specified way so the results are reproducible.
  • A Lloyd loop that follows the tie, empty-cluster, stopping and final-reassignment rules.
  • An ARI built from a contingency table that matches sklearn , including the n < 2 and zero-denominator cases.
  • Best-run selection with first-argmin ties, and the pairwise mean with the single-run case.
  • Why restarts reach different inertias, and what a low mean pairwise ARI says about the clustering.

Follow-up Questions Guidance

  • Why do different initialisations give different inertias?
  • How would k-means++ initialisation change these results?
  • How does the cost of the pairwise ARI step grow with n_init , and how would you cut it for hundreds of restarts?