Pick k-means++ starting centers deterministically

Why it matters Embedding clustering for topic discovery and IVF index training starts from k-means++.

k-means++ spreads the starting centers out: each new center is chosen with probability proportional to its squared distance from the nearest center chosen so far.

Write kmeanspp_init(X, k, u). To make it testable, randomness is given: u is a list of k numbers in [0, 1). The first center is X[floor(u[0] * n)]. For each next center i, compute D2 (squared distance of every point to its nearest chosen center), form the cumulative sum c of D2 / sum(D2), and pick the first index where c > u[i]. Return the (k, d) array of centers.

Signaturedef kmeanspp_init(X, k, u)

Example

X = [[0], [1], [10]], k = 2, u = [0.0, 0.5]: first center 0, D2 = [0, 1, 100], cumulative [0, 0.0099, 1], so the second center is [10].

Understand the idea

Plain k-means can start with all centers bunched together and end up stuck. k-means++ picks each new center at random, but with probability proportional to the squared distance from the nearest center already chosen, so far-away uncovered points are likely picks. Here the randomness is passed in as numbers u so results are testable. Worked example: X = [[0], [2], [5]], k = 2, u = [0.5, 0.3]. The first center is X[floor(0.5 * 3)] = X[1] = [2]. D2 = [4, 0, 9], sum 13, so the normalised weights are [0.308, 0, 0.692] and the cumulative sum is [0.308, 0.308, 1.0]. The first index where the cumulative sum exceeds 0.3 is 0, so the second center is [0]. With u[1] = 0.4 it would be [5]. Rule: first center X[floor(u[0] * n)]; then D2_j = min over chosen centers of squared distance, c = cumsum(D2 / sum(D2)), pick the first j with c_j > u[i]. Used in: the default initialisation in scikit-learn KMeans and in codebook training for vector quantisation.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplekmeanspp_init([[0], [1], [10]], 2, [0.0, 0.5])
  • Sample 2: three centerskmeanspp_init(_X, 3, [0.1, 0.4, 0.8])