AI Wiki中文/EN

k-means++ initialization: sample what the current centers miss

k-means++ 初始化

Follow exact D-squared probabilities, distinguish expected guarantees from individual runs, and handle repeated points and zero potential explicitly.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The first two centers can miss half the picture

Five calibration settings lie at (−2,0), (−1,1), (0,0), (8,0) and (9,1). We want two representatives. Taking the first two records places both on the left and leaves a squared-distance cost of 184. Choosing records 0 and 4 instead gives cost 8. Before any iterative refinement, the starting positions have already changed the problem faced by the next step.

k-means++ makes the second choice depend on what the first center still represents poorly. A distant point gets more probability, but is not certain to be chosen. This chapter follows those probabilities exactly. The k-means algorithm explains the later assignment and mean-update steps; initialization chooses where those steps begin.

Sample the current squared error

For n equally weighted records in Euclidean space, define the potential of a nonempty center set C as

DC(xi)2=min⁡c∈C∥xi−c∥22,Φ(C)=∑i=1nDC(xi)2,Φk∗=min⁡c1,…,ck∈Rd∑imin⁡j∥xi−cj∥22.D_C(x_i)^2=\min_{c\in C}\|x_i-c\|_2^2,\qquad \Phi(C)=\sum_{i=1}^n D_C(x_i)^2,\qquad \Phi_k^*=\min_{c_1,\ldots,c_k\in\mathbb R^d}\sum_i\min_j\|x_i-c_j\|_2^2.

The optimum permits centers anywhere in the space. It is not the best set of k observed records. Repeated coordinates remain separate observations and count repeatedly in the sum.

Choose the first record uniformly. While the potential is positive, draw each later center using

Pr⁡(c1=xi)=1n,Pr⁡(ct+1=xi∣Ct)=DCt(xi)2Φ(Ct).\Pr(c_1=x_i)=\frac1n,\qquad \Pr(c_{t+1}=x_i\mid C_t)=\frac{D_{C_t}(x_i)^2}{\Phi(C_t)}.

These are probabilities over record indices; equal coordinates contribute their combined multiplicity. Once a coordinate is represented exactly, every record at that coordinate has zero weight. Thus positive-potential sampling cannot select that coordinate again. The squared distance is already the weight: squaring it once more would implement D⁴ sampling.

The numerator measures distance to the nearest existing center, not the last chosen center. Saving each point’s nearest squared distance and replacing it by the minimum of its old value and its distance to the new center preserves this invariant. Adding a center cannot increase the potential. The original procedure uses one sampled candidate per new center. Arthur and Vassilvitskii, §2.2

What the logarithmic guarantee actually says

For the ordinary randomized procedure on finite Euclidean data, the original analysis proves

E[Φ(Ck)]≤8(ln⁡k+2)Φk∗.\mathbb E[\Phi(C_k)]\le 8(\ln k+2)\Phi_k^*.

The expectation is over the prescribed random choices, with the dataset and k fixed. The bound already holds after seeding, before Lloyd refinement. It does not bound every run or certify a global optimum. Exact Lloyd steps that preserve or decrease this same objective preserve the upper bound. Original paper, Theorem 3.1

One part of the argument is easy to see. For a cluster A with mean μ, expand the square and use the vanishing sum of centered vectors:

∑x∈A∥x−z∥2=∑x∈A∥x−μ∥2+∣A∣∥z−μ∥2.\sum_{x\in A}\|x-z\|^2=\sum_{x\in A}\|x-\mu\|^2+|A|\|z-\mu\|^2.

A uniformly sampled z from A therefore has expected cluster cost twice its mean-centered cost. The full proof also bounds the cost of newly covered optimum clusters under D² sampling; accounting for clusters still uncovered produces the harmonic, hence logarithmic, factor. This paragraph explains the proof’s structure, not all of its inequalities.

If the potential reaches zero before k choices, all observed coordinates are represented and the optimum is also zero. Our implementation stops, reporting fewer than k centers. Extra duplicate centers could pad the list without changing its objective, but would not create additional nonempty geometric groups. For k=1, the uniform-center identity directly gives twice the optimum in expectation. No cost ratio should be formed by dividing by a zero optimum.

Replay one draw, then enumerate its alternatives

This complete standard-library program uses two-dimensional integer or Fraction coordinates. seed receives exactly k numbers in [0,1), so the draw-to-center mapping can be inspected without depending on a random-number generator. An index owns a half-open interval of that length in the cumulative probability table; an exact boundary belongs to the next positive-mass interval. Zero-weight records are skipped even when the draw is zero.

The supplied numbers are deterministic input, not evidence that a run was randomly sampled. Independent ideal uniform draws induce the probability law above. The program’s separate seeding_law follows every positive-probability branch and computes that law exactly for tiny datasets. It retains ordered record-index paths, including distinct paths that yield the same geometric centers.

All draws, including a tail unused after zero potential, are validated before execution. Coordinates, k and draws reject booleans and floats. Helpers operate on the validated internal data. complete means exactly k centers were selected; zero-potential means the loop stopped earlier. Neither status means Lloyd iterations were run.

from fractions import Fraction as F
from itertools import combinations


def rational(x):
    if type(x) not in (int, F):
        raise ValueError('use integer or Fraction values')
    return F(x)


def dataset(points, k):
    if type(points) not in (list, tuple) or not points:
        raise ValueError('nonempty point sequence required')
    clean = []
    for point in points:
        if type(point) not in (list, tuple) or len(point) != 2:
            raise ValueError('each point must have two coordinates')
        clean.append(tuple(rational(v) for v in point))
    if type(k) is not int or not 1 <= k <= len(clean):
        raise ValueError('k must be an integer between one and n')
    return tuple(clean)


def squared(x, y):
    return sum(((a-b)**2 for a, b in zip(x, y)), F())


def extend(points, nearest, j):
    distances = tuple(squared(x, points[j]) for x in points)
    return distances if nearest is None else tuple(min(a, b) for a, b in zip(nearest, distances))


def draw_index(weights, u):
    threshold, cumulative = u*sum(weights), F()
    for i, weight in enumerate(weights):
        cumulative += weight
        if threshold < cumulative:
            return i
    raise AssertionError('positive mass and u in [0,1) required')


def seed(points, k, draws):
    points = dataset(points, k)
    if type(draws) not in (list, tuple) or len(draws) != k:
        raise ValueError('provide exactly k draws, including unused tail draws')
    draws = tuple(rational(u) for u in draws)
    if any(not 0 <= u < 1 for u in draws):
        raise ValueError('draws must lie in [0,1)')
    chosen, trace, nearest = [], [], None
    for u in draws:
        weights = (F(1),)*len(points) if nearest is None else nearest
        total = sum(weights)
        if total == 0:
            break
        j = draw_index(weights, u)
        nearest = extend(points, nearest, j)
        chosen.append(j)
        trace.append((tuple(w/total for w in weights), u, j, sum(nearest)))
    return {'indices': tuple(chosen), 'centers': tuple(points[j] for j in chosen),
            'potential': sum(nearest), 'trace': tuple(trace),
            'status': 'complete' if len(chosen) == k else 'zero-potential'}


def seeding_law(points, k):
    # Exact probability-tree audit for tiny inputs; not a scalable sampler.
    points = dataset(points, k)
    outcomes = []
    def visit(chosen, nearest, probability):
        if len(chosen) == k or nearest is not None and sum(nearest) == 0:
            status = 'complete' if len(chosen) == k else 'zero-potential'
            outcomes.append((chosen, probability, sum(nearest), status))
            return
        weights = (F(1),)*len(points) if nearest is None else nearest
        total = sum(weights)
        for j, weight in enumerate(weights):
            if weight:
                visit(chosen+(j,), extend(points, nearest, j), probability*weight/total)
    visit((), None, F(1))
    return {'outcomes': tuple(outcomes),
            'mass': sum((p for _, p, _, _ in outcomes), F()),
            'expected_potential': sum((p*v for _, p, v, _ in outcomes), F())}


if __name__ == '__main__':
    points = [(-2, 0), (-1, 1), (0, 0), (8, 0), (9, 1)]
    report = seed(points, 2, [F(1, 10), F(1, 2)])
    print('indices / potential:', report['indices'], report['potential'])
    print('second probabilities:', tuple(map(str, report['trace'][1][0])))
    law = seeding_law(points, 2)
    print('outcomes / mass:', len(law['outcomes']), law['mass'])
    print('D2 expected potential:', law['expected_potential'])
    uniform = []
    for a, b in combinations(range(len(points)), 2):
        uniform.append(sum((min(squared(x, points[a]), squared(x, points[b])) for x in points), F()))
    print('uniform pair expected potential:', sum(uniform)/len(uniform))
    repeat = seed([(0, 0), (0, 0), (3, 0)], 3, [0, 0, 0])
    print('duplicate indices / status / potential:', repeat['indices'], repeat['status'], repeat['potential'])

The output is

indices / potential: (0, 4) 8
second probabilities: ('0', '1/114', '1/57', '25/57', '61/114')
outcomes / mass: 20 1
D2 expected potential: 1595888/150195
uniform pair expected potential: 77
duplicate indices / status / potential: (0, 2) zero-potential 0

With first center (−2,0), squared distances are 0, 2, 4, 100 and 122, totaling 228. The draw 1/2 falls in record 4’s interval; the resulting potential is 8. Drawing zero in the second step instead selects record 1 and gives 184. That poor path has probability 1/570 under genuine sampling, so it cannot be ruled out by an expectation guarantee.

Across all 20 ordered two-center paths, the expected seed cost is 1595888/150195, about 10.63. A uniformly chosen unordered pair of distinct records has expected cost 77 here. This compares two complete laws on this dataset, not two lucky runs. Enumerating its 15 unordered nonempty bipartitions and placing each group’s center at its mean gives the global two-means optimum 11/3. The best pair of observed records costs 6: the distinction between a seed and an unconstrained mean matters.

The duplicate example stops with indices (0,2). The other record at the origin already has distance zero, so giving it another center would change neither representation nor cost.

For n points and s selected centers, seed costs O(n+k+ns) arithmetic/comparison operations in fixed dimension two. Its retained trace stores n probabilities per selection, so total storage is O(n+k+ns); without the trace, working storage could be O(n+k). In d dimensions, distance updates cost O(nsd). Rational bit growth adds cost. Let A be the number of visited probability-tree nodes and L its terminal paths. The exhaustive audit costs O(nA+kL) operations and O(nk+kL) storage; A can grow exponentially with k. It is an explanation tool, not an alternative fast seeder.

A better start does not define a useful clustering

D² sampling favors unexplained squared distance. An isolated recording error may therefore attract a center. It does not identify which observations deserve attention, choose k, or establish that Euclidean distance matches the application. Scaling one coordinate changes the objective and the sampling law; translating or uniformly scaling all coordinates by a nonzero factor preserves the index probabilities, apart from the all-coincident zero-cost case.

A deterministic farthest-first rule always takes a maximizer; k-means++ samples from all positive weights. Replacing one with the other changes the algorithm. Similarly, the fixed scikit-learn 1.7.2 interface offers several local candidate trials and greedily retains the best. n_local_trials=1 selects the ordinary version; the default uses multiple trials. The original one-candidate theorem is not automatically a proof for every modification sharing the name.

Restart comparisons should fix the preprocessing, k, refinement rule and total trial budget. Report the distribution of the chosen objective, not just the lowest value that happened to appear. Selecting the lowest training potential among starts does not measure performance on new records or recover a known scientific grouping. Duplicate removal also changes weights unless multiplicities are retained.

Our code neither runs Lloyd iterations nor handles weighted observations, missing coordinates, approximate distances or large distributed data. Its fractions make a small sampling law exact; they do not remove the need for numerical care in a floating-point implementation.

Read the random choice precisely

  1. The first center is (−2,0). What is the probability of selecting record 4 next, and why is it not the probability of the farthest-first rule?
Show answer

Answer: It is 122/228=61/114. Record 4 is the farthest here, so farthest-first would choose it with probability one. D² sampling still permits every other positive-distance record.

  1. Why can a cost-184 run coexist with an expected cost about 10.63? Does the theorem compare either value to the best observed-record pair?
Show answer

Answer: The bad path has small but positive probability, 1/570. An expectation averages all paths. The theorem compares the expected cost with the unrestricted mean-center optimum, 11/3 here, rather than the best observed-record pair’s cost 6.

  1. For records (0,0), (0,0), (3,0) and k=3, why does the program return only two centers? What changes if duplicate rows are silently removed before the first draw?
Show answer

Answer: After selecting both coordinates the potential is zero, and no D² probability can be normalized. The early-return convention reports that fact. Originally the origin has first-center probability 2/3; deleting its duplicate changes it to 1/2 and changes the weighted data problem.

  1. If all coordinates are multiplied by a nonzero scalar a, what happens to D² probabilities, seed indices under the same draws, and the potential?
Show answer

Answer: Every squared distance is multiplied by a², which cancels between numerator and denominator. The same draws select the same indices, and all potentials are multiplied by a². Scaling only one coordinate generally does not have that invariance.

Initialization became an approximation algorithm

Arthur and Vassilvitskii’s 2007 contribution was a sampling rule with a worst-case expected objective guarantee before local refinement. This gives initialization a mathematical role beyond trying arbitrary starting points. The original paper separates seeding analysis from later local improvement; that distinction is useful when comparing implementations.

The versioned API exposes how a practical variant adds candidate trials. Read it alongside the original algorithm, recording both the sampling rule and any extra greedy selection. Continue with hierarchical clustering for a method organized around merges rather than initialization, and clustering evaluation for questions that a low squared-distance cost cannot answer alone.

Make a prediction, then check

Does the logarithmic approximation guarantee rule out every high-cost initialization?

Choose one answer

Learning objectives

  • Compute successive nearest-center squared-distance probabilities with explicit duplicate and zero-cost conventions.
  • State exactly which expectation and optimum appear in the k-means++ guarantee.
  • Compare a complete seeding distribution with individual paths and with an unrestricted mean-center optimum.

Prerequisites & connections

Explore related knowledge →

References

  1. k-means++: The Advantages of Careful Seeding
    David Arthur; Sergei Vassilvitskii · 2007
  2. kmeans_plusplus — scikit-learn 1.7.2
    scikit-learn contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Eight tests pass. Gram-polarization distances and direct ordered-index path products independently verify 10 complete probability laws and 112 terminal paths. Every path is replayed with interval-midpoint draws and all returned fields checked, including early stop, probabilities, centers and potential; this reference does not recursively extend nearest-distance vectors.
  • Independent mean-center enumeration of all 15 unordered nonempty bipartitions gives optimum 11/3; the ten observed-record pairs have minimum 6 and uniform mean 77. Checked exact cumulative boundaries, duplicate mass, zero-potential status priority, k=1 centroid identity, rotation/translation/scaling, 60-digit rational coordinates, invalid unused tail draws and input preservation.
  • Original complete bilingual prose, identical Python and six stdout lines; four matching display equations, six anchors and four answered exercises pass strict MDX/KaTeX/React HTML, actual MathML and emphasis checks. Only article_text controls test paths. Humanizer reread. Status written records AI author checks; no human review, library execution, full-site build or browser acceptance.
  • Ran all eight author tests. Independent unordered-center-subset Markov propagation merges histories before each transition, instead of recursively extending nearest vectors or multiplying probabilities of ordered paths. Six complete laws (71 subset states, 30 terminal subsets) match the aggregate of 108 author outcomes, all terminal costs/statuses, total mass and expected potential. Includes duplicates, all-coincident data, one point, and third-center choices sensitive to all prior centers.
  • Independently checked zero draws skipping leading duplicate zero weights, the successive potential trace 29,9,0, and rejection of an invalid unused tail draw. Reviewed half-open cumulative intervals, deterministic inputs versus ideal IID uniform draws, record multiplicity, positive-potential non-reselection and exact-k status priority. The unrestricted mean-center optimum, observed-record optimum and a single sampled cost are not conflated.
  • Read complete English/Chinese prose, formulas, code, exercises and metadata. The expectation theorem and zero-optimum handling are correctly scoped; mean identity and proof outline agree with the source. Sampler and exhaustive-law time/storage bounds include retained traces, recursion and path output, with rational bit costs qualified. No automatic semantic-clustering or per-run guarantee is claimed.
  • Strict MDX/KaTeX and actual React HTML pass: four displays, six anchors and four answers per language, with all four math annotations equal. Executable fence equals example.py; author tests verify both languages and six actual stdout lines. Five SHA and source IDs/URLs match the frozen metadata exactly. No revision requested.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • k-means++: The Advantages of Careful Seeding · Actually opened the nine-page author-hosted PDF. Read §2.1–2.2 (pages 2–3), objective and center-mean identity, uniform first seed and D-squared sampling; §3 Theorem 3.1 and its explicit statement that the bound already holds after seeding; Lemmas 3.1–3.2 (page 3), uniform-cluster factor two and conditional covered-cluster factor eight; Lemma 3.3 statement and theorem conclusion (pages 4–5), harmonic factor. Research statement of SODA 2007 independently matches author publication page and Google Research record. Text extraction only; no visual PDF inspection, benchmark reproduction or new proof of every lemma. Repeated-record weighting and the zero-potential early-return convention are explicitly derived for the original teaching example.
  • kmeans_plusplus — scikit-learn 1.7.2 · Actually read fixed 1.7 API displayed as 1.7.2, lines 620–665: inputs, sample weights, reproducible random_state, and n_local_trials. The page says one local trial recovers vanilla sampling, while its default uses multiple candidate trials. This chapter does not transfer the original theorem to that default or claim to have executed scikit-learn.
  • k-means++: The Advantages of Careful Seeding · Actually opened the nine-page author-hosted PDF and read section 2.1–2.2 (PDF pages 2–3) for the mean identity, nearest-center distance and single D-squared candidate; section 3 Theorem 3.1 and Lemmas 3.1–3.2 (page 3), plus the theorem conclusion on pages 4–5: expectation bounded by 8(ln k+2) times unrestricted optimum already after seeding, with the harmonic factor. The Google Research official publication record additionally confirms SODA 2007, pages 1027–1035. This is a scope/statement and proof-outline review, not a new proof of every lemma or visual PDF audit. The article distinguishes repeated records and its explicit zero-potential early-stop convention.
  • kmeans_plusplus — scikit-learn 1.7.2 · Actually opened the fixed 1.7 API, rendered 1.7.2. Read lines 620–654 for input signature, sample weights, reproducible random_state and n_local_trials: one trial recovers vanilla sampling, while the default considers multiple candidates and selects a lower-inertia candidate. No source-code or runtime equivalence claimed, and the original bound is not automatically transferred to that practical variant.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.