Implement the Gap Statistic With the One-Standard-Error Rule for k-Means

Quick Overview

Implement the gap statistic for choosing the number of k-means clusters in NumPy, with deterministic farthest-first seeding, uniform reference datasets and the one-standard-error rule. It tests reproducible clustering, Monte Carlo error estimates and careful 1-based indexing.

Implement the Gap Statistic With the One-Standard-Error Rule for k-Means

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Given data `X` of shape `(n, d)`, compute the gap statistic for `k = 1..k_max` using a deterministic k-means and uniform reference datasets, then choose `k` with the one-standard-error rule. Implement these four functions: ```python def within_dispersion(X, labels): """Return W_k as a float.""" def kmeans_farthest_first(X, k, max_iter=100): """Return (labels, centroids).""" def choose_k_one_se(gap, sk): """Return the chosen k (1-based).""" def gap_statistic(X, k_max, n_refs=10, seed=0): """Return the result dictionary described below.""" ``` The functions must behave as follows. - `within_dispersion(X, labels)` returns, as a `float`, the sum over clusters of the squared Euclidean distances from each point to its cluster mean. - `kmeans_farthest_first(X, k, max_iter=100)` seeds with `X[0]`. Each next seed is the point at the first `argmax` of the squared distance to its nearest chosen seed. It then runs Lloyd's algorithm (assign each point to its nearest centroid, with ties going to the lowest centroid index as with `argmin`, then move each centroid to the mean of its points) until the labels stop changing or `max_iter` is reached. An empty cluster keeps its centroid. It returns the final int labels, computed with `argmin` against the final centroids, and the `(k, d)` centroids. - `choose_k_one_se(gap, sk)` returns the smallest 1-based `k` with `gap[k] >= gap[k+1] - sk[k+1]` (ties accepted), or `k_max` if no `k` qualifies. - `gap_statistic` first computes the observed $\log W_k$ (natural log) for every $k$ from 1 to `k_max`. Then, with `rng = np.random.default_rng(seed)`, it draws each reference in turn as `rng.uniform(X.min(0), X.max(0), size=X.shape)` and clusters it with the same k-means for every `k`. - `gap_statistic` returns a dict with `ks`, `log_wk`, `ref_log_wk` (shape `(n_refs, k_max)`), `expected_log_wk` (the mean over references), `gap` (expected minus observed), `sk` (equal to `std(ddof=0) * sqrt(1 + 1/n_refs)`, taken over references) and `optimal_k` (an `int`). Examples: ```python within_dispersion([[0, 0], [0, 2], [5, 5], [7, 5]], [0, 0, 1, 1]) # 4.0 kmeans_farthest_first([[0, 0], [1, 0], [10, 0], [11, 0]], 2) # labels [0, 0, 1, 1], centroids [[0.5, 0], [10.5, 0]] choose_k_one_se([0.25, 0.5, 1.0, 1.125, 1.25], [0.125] * 5) # 3 (1.0 >= 1.125 - 0.125) choose_k_one_se([0.0, 1.0, 2.0, 3.0], [0.1] * 4) # 4 ``` ```hint Mind the indexing The rule is written with 1-based `k`, while NumPy arrays are 0-based. Check your loop against both `choose_k_one_se` examples, including the one where no `k` qualifies. ``` ```hint Where the randomness lives The seeding rule removes all randomness from k-means. Think about the exact order in which values are drawn from `rng`, since that order is the only thing that fixes the reference datasets. ``` ### Constraints & Assumptions - `X` has shape `(n, d)`. - `1 <= k_max <= n` and `n_refs >= 1`. - Use NumPy only (no scikit-learn). ### What a Strong Answer Covers - A within-cluster dispersion and a k-means that follow the seeding, tie, stopping and empty-cluster rules exactly, so every run is reproducible. - Reference datasets drawn in order from one generator over the bounding box of `X`, each clustered for every `k`. - The expected log-dispersion, the gap and `sk`, using the `ddof=0` standard deviation and the $\sqrt{1 + 1/B}$ factor, where $B$ is `n_refs`. - The one-standard-error rule with correct 1-based indexing, accepted ties and the `k_max` fallback. - The total cost of the procedure and the degenerate case where some $W_k$ is 0. ### Follow-up Questions - Why use the bounding box of the data as the reference distribution, and when would you use a box aligned with the principal components? - Why is `sk` scaled by $\sqrt{1 + 1/B}$? - How would you scale this to a large `n` or a large `k_max`?

Overview: Implement the gap statistic for choosing the number of k-means clusters in NumPy, with deterministic farthest-first seeding, uniform reference datasets and the one-standard-error rule. It tests reproducible clustering, Monte Carlo error estimates and careful 1-based indexing.

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

Given data X of shape (n, d), compute the gap statistic for k = 1..k_max using a deterministic k-means and uniform reference datasets, then choose k with the one-standard-error rule. Implement these four functions:

def within_dispersion(X, labels):
    """Return W_k as a float."""

def kmeans_farthest_first(X, k, max_iter=100):
    """Return (labels, centroids)."""

def choose_k_one_se(gap, sk):
    """Return the chosen k (1-based)."""

def gap_statistic(X, k_max, n_refs=10, seed=0):
    """Return the result dictionary described below."""

The functions must behave as follows.

  • within_dispersion(X, labels) returns, as a float , the sum over clusters of the squared Euclidean distances from each point to its cluster mean.
  • kmeans_farthest_first(X, k, max_iter=100) seeds with X[0] . Each next seed is the point at the first argmax of the squared distance to its nearest chosen seed. It then runs Lloyd's algorithm (assign each point to its nearest centroid, with ties going to the lowest centroid index as with argmin , then move each centroid to the mean of its points) until the labels stop changing or max_iter is reached. An empty cluster keeps its centroid. It returns the final int labels, computed with argmin against the final centroids, and the (k, d) centroids.
  • choose_k_one_se(gap, sk) returns the smallest 1-based k with gap[k] >= gap[k+1] - sk[k+1] (ties accepted), or k_max if no k qualifies.
  • gap_statistic first computes the observed log⁡Wk\log W_k (natural log) for every kk from 1 to k_max . Then, with rng = np.random.default_rng(seed) , it draws each reference in turn as rng.uniform(X.min(0), X.max(0), size=X.shape) and clusters it with the same k-means for every k .
  • gap_statistic returns a dict with ks , log_wk , ref_log_wk (shape (n_refs, k_max) ), expected_log_wk (the mean over references), gap (expected minus observed), sk (equal to std(ddof=0) * sqrt(1 + 1/n_refs) , taken over references) and optimal_k (an int ).

Examples:

within_dispersion([[0, 0], [0, 2], [5, 5], [7, 5]], [0, 0, 1, 1])  # 4.0
kmeans_farthest_first([[0, 0], [1, 0], [10, 0], [11, 0]], 2)
# labels [0, 0, 1, 1], centroids [[0.5, 0], [10.5, 0]]
choose_k_one_se([0.25, 0.5, 1.0, 1.125, 1.25], [0.125] * 5)  # 3 (1.0 >= 1.125 - 0.125)
choose_k_one_se([0.0, 1.0, 2.0, 3.0], [0.1] * 4)            # 4

Constraints & Assumptions

  • X has shape (n, d) .
  • 1 <= k_max <= n and n_refs >= 1 .
  • Use NumPy only (no scikit-learn).

What a Strong Answer Covers Guidance

  • A within-cluster dispersion and a k-means that follow the seeding, tie, stopping and empty-cluster rules exactly, so every run is reproducible.
  • Reference datasets drawn in order from one generator over the bounding box of X , each clustered for every k .
  • The expected log-dispersion, the gap and sk , using the ddof=0 standard deviation and the 1+1/B\sqrt{1 + 1/B} factor, where BB is n_refs .
  • The one-standard-error rule with correct 1-based indexing, accepted ties and the k_max fallback.
  • The total cost of the procedure and the degenerate case where some WkW_k is 0.

Follow-up Questions Guidance

  • Why use the bounding box of the data as the reference distribution, and when would you use a box aligned with the principal components?
  • Why is sk scaled by 1+1/B\sqrt{1 + 1/B} ?
  • How would you scale this to a large n or a large k_max ?