AI Wiki中文/EN

k-means clustering

k-means 聚类

Derive Lloyd updates, compare two local solutions, and implement exact small-data clustering with explicit tie and empty-cluster policies.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same four points can produce two answers

Imagine four kiosks on a small map, at A=(−2,−1), B=(−2,1), C=(2,−1), and D=(2,1). We want two representative locations, and score a representation by the sum of squared Euclidean distances from each kiosk to its representative. This is an invented geometry problem: squared distance is the stated objective, not a claim about actual travel cost.

Grouping the two left kiosks together and the two right kiosks together puts the representatives at (−2,0) and (2,0). Every point is one unit from its representative, giving total squared error 4. Grouping the bottom pair and the top pair instead puts them at (0,−1) and (0,1). Every point is two units away, giving error 16. A drawing makes the first arrangement look preferable.

Lloyd’s k-means algorithm can nevertheless stop at either arrangement. Start its two centers at A and B and it settles into the horizontal grouping. Start at A and C and it finds the vertical grouping. The algorithm improves its current answer; its stopping rule does not compare every possible grouping.

Alternate the part that is easy to solve

Given n finite vectors in d-dimensional Euclidean space and a chosen positive integer K, let ci∈{1,…,K}c_i\in\{1,\ldots,K\} name the center assigned to point i. The objective is

J(c,μ)=∑i=1n∥xi−μci∥22,Φ(μ)=min⁡cJ(c,μ).J(c,\mu)=\sum_{i=1}^n\|x_i-\mu_{c_i}\|_2^2,\qquad \Phi(\mu)=\min_c J(c,\mu).

This article uses the sum, often called SSE or inertia. Dividing by n gives a mean with the same minimizers. Cluster numbers are names: permuting them changes no grouping or cost. The finite-data optimization needs no probability model or i.i.d. sampling assumption. CS229, pp.1–3

Lloyd’s method alternates two exact subproblems. With centers fixed, choose the closest center independently for each point. With assignments fixed, replace every nonempty cluster’s center by the arithmetic mean of its points:

cinew∈arg⁡min⁡j∥xi−μj∥22,μjnew=1∣Cj∣∑i∈Cjxi(∣Cj∣>0).c_i^{\mathrm{new}}\in\arg\min_j\|x_i-\mu_j\|_2^2,\qquad \mu_j^{\mathrm{new}}=\frac1{|C_j|}\sum_{i\in C_j}x_i\quad (|C_j|>0).

Why the mean? Write each displacement from a candidate center z as a displacement from the cluster mean plus the mean’s displacement from z. The cross terms sum to zero because the centered vectors sum to zero. Therefore

∑i∈C∥xi−z∥2=∑i∈C∥xi−xˉC∥2+∣C∣∥xˉC−z∥2.\sum_{i\in C}\|x_i-z\|^2=\sum_{i\in C}\|x_i-\bar x_C\|^2+|C|\|\bar x_C-z\|^2.

The last term is nonnegative and vanishes at the mean. This proves the update minimizes the fixed-cluster objective, rather than merely pointing in an improving direction. Arthur and Vassilvitskii, §2.1, Lemma 2.1

Putting the two subproblems together gives

J(cnew,μnew)≤J(cnew,μ)≤J(c,μ).J(c^{\mathrm{new}},\mu^{\mathrm{new}})\le J(c^{\mathrm{new}},\mu)\le J(c,\mu).

This nonincrease assumes nearest-center assignments, arithmetic means, and a compatible treatment of empty clusters. It does not promise a strict drop at every step. The objective is bounded below by zero, so the sequence of objective values converges; that fact alone does not prove that an arbitrary tie policy makes the assignments converge. Use a consistent rule for ties and an explicit stopping condition. Moving occupied centers by another heuristic, imposing balancing constraints, or switching the distance function changes the argument.

For the four kiosks, there are only seven unordered partitions into two nonempty groups. Their mean-center costs are 4, 16, 20, and four copies of 40/3. Thus 4 is globally best here. At the horizontal solution every nearest-center choice is strict, and each center is its group’s mean. Small center perturbations preserve the assignments and increase the cost: 16 is a local minimum, not an unfinished iteration. CS229, p.3, local optima and restarts

Expose ties, empty clusters, and the stopping rule

The complete program uses integers or Fraction coordinates so the small examples have exact comparisons and exact costs. Supply the initial centers explicitly. Python’s min chooses the first index when distances tie; an empty cluster keeps its old center. That center contributes nothing to the current assigned cost, so retaining it preserves the descent argument.

The trace begins with the cost after the first assignment, then records a mean update and a new assignment on every iteration. We return only when the assignments stabilize after a mean update. Reaching the iteration limit raises an error rather than claiming convergence.

from fractions import Fraction

def rational_points(rows):
    points = tuple(tuple(row) for row in rows)
    if not points or not points[0]:
        raise ValueError("nonempty points with positive dimension required")
    d = len(points[0])
    if any(len(p) != d for p in points):
        raise ValueError("all points must have the same dimension")
    if any(isinstance(v, bool) or not isinstance(v, (int, Fraction))
           for p in points for v in p):
        raise ValueError("use integers or exact Fraction coordinates")
    return tuple(tuple(Fraction(v) for v in p) for p in points)

def squared_distance(p, q):
    return sum((a-b)**2 for a, b in zip(p, q))

def lloyd(rows, initial, max_steps=100):
    points, centers = rational_points(rows), rational_points(initial)
    n, d, k = len(points), len(points[0]), len(centers)
    if len(centers[0]) != d or not 1 <= k <= n:
        raise ValueError("aligned centers and 1 <= k <= n required")
    if type(max_steps) is not int or max_steps < 1:
        raise ValueError("positive integer iteration limit required")
    def assign(cs):
        return tuple(min(range(k), key=lambda j: squared_distance(p, cs[j]))
                     for p in points)
    def objective(labels, cs):
        return sum(squared_distance(p, cs[j]) for p, j in zip(points, labels))
    labels = assign(centers)
    trace = [objective(labels, centers)]
    for step in range(1, max_steps+1):
        totals = [[Fraction(0) for _ in range(d)] for _ in range(k)]
        counts = [0]*k
        for p, j in zip(points, labels):
            counts[j] += 1
            for axis in range(d):
                totals[j][axis] += p[axis]
        updated = tuple(tuple(v/counts[j] for v in totals[j])
                        if counts[j] else centers[j] for j in range(k))
        trace.append(objective(labels, updated))
        next_labels = assign(updated)
        trace.append(objective(next_labels, updated))
        if next_labels == labels:
            return {"centers": updated, "labels": next_labels,
                    "sse": trace[-1], "trace": tuple(trace), "steps": step}
        centers, labels = updated, next_labels
    raise RuntimeError("iteration limit reached before assignments stabilized")

points = [(-2,-1), (-2,1), (2,-1), (2,1)]
horizontal = lloyd(points, [points[0], points[1]])
vertical = lloyd(points, [points[0], points[2]])
assert horizontal["sse"] == 16 and vertical["sse"] == 4
assert all(a >= b for a, b in zip(horizontal["trace"], horizontal["trace"][1:]))
assert lloyd([(3,3)]*4, [(3,3),(3,3)])["labels"] == (0,0,0,0)
print("horizontal:", horizontal["trace"], "vertical:", vertical["trace"])

The printed traces are (32,16,16) and (8,4,4), with exact rational entries. With duplicate centers, some clusters can remain empty; the identical-points assertion deliberately demonstrates this. Even K≤n does not ensure K occupied clusters. A policy that must produce K nonempty groups needs additional rules and its own verification.

For T iterations, nearest-center comparisons cost O(TnKd) arithmetic operations; accumulating means costs O(Tnd). The input copy, assignments, centers, accumulators, and trace store O(nd+n+Kd+T) numbers. There is no n-by-K distance matrix. Exact fractions have numerator and denominator bit costs beyond this arithmetic-operation count, so this is teaching code for small rational datasets, not a throughput implementation.

A useful grouping depends on the geometry

Changing a feature from meters to centimeters multiplies its squared-distance contribution by 10,000. Choose feature transformations according to the intended meaning of similarity. Standardization can be appropriate when scales are arbitrary; it also changes the objective. Integer codes for unordered categories do not automatically create a meaningful distance between them.

Nearest-center regions are intersections of half-spaces. They suit some compact groups and cannot trace every curved or interlocking shape. Squaring distances also gives remote points substantial influence on means. A low SSE does not establish a hidden biological type, a customer motive, or even a stable grouping under another sample. Density-based clustering, mixtures, and robust representatives address different assumptions.

The globally optimal SSE cannot increase when an extra center is allowed, so training SSE alone cannot choose K. A particular run with K+1 can still finish worse than a better-initialized run with K. Inspect stability, alternative K values, and evidence relevant to the intended use; keep these judgments separate from whether the implementation minimizes its stated subproblems.

Predict a step before running it

  1. Initialize the kiosk example at A and B. What happens after assignment and one mean update? Answer: the bottom and top rows form separate groups. The centers become (0,−1),(0,1), and SSE falls from 32 to 16. Reassignment changes nothing.
  2. A cluster has three points with mean m. Its old center is two Euclidean units from m. How much does a mean update reduce its assigned SSE? Answer: exactly 3×22=123\times2^2=12, by the centroid identity, regardless of the within-cluster spread.
  3. Four identical points are clustered with two identical initial centers. What does this program return? Answer: all labels are 0, the second cluster is empty, and SSE is zero. It has not produced two distinguishable groups.
  4. Does a lower optimal SSE with K=3 than with K=2 prove there are three real groups? Answer: no. Extra centers can improve squared-error representation even without such a structure. Also distinguish an optimum from the cost of one local run.

Separate the objective, the iteration, and the initialization

“k-means” can name the optimization problem or an algorithm used to approximate it. Lloyd’s batch iteration is the version implemented here. Research on initialization changes its starting point; research on faster assignment changes its computation; neither distinction should disappear under the same short name.

k-means++ chooses the first center uniformly from the observations, then samples each new center with probability proportional to the squared distance to the nearest chosen center. The original analysis bounds expected seeded cost by 8(log⁡K+2)8(\log K+2) times optimal cost; monotone Lloyd steps preserve that bound. It is an expectation over initialization, not a promise that each run is optimal. If every distance is zero, the data are already represented at zero cost and the sampling denominator needs a separate convention. Arthur and Vassilvitskii, §2.2 and Theorem 3.1

The k-means++ directory entry (article pending) reserves a separate treatment of that sampling method. For an experiment here, compare the two fixed seeds, enumerate the seven partitions, then perturb one kiosk and predict which assignment boundary it crosses. A cost trace, a partition oracle, and a picture answer different questions about the result.

Make a prediction, then check

On the same four points, Lloyd stops at SSE=16 and SSE=4 from two initializations. What follows merely from the first cost no longer decreasing?

Choose one answer

Learning objectives

  • Derive both Lloyd subproblems from the centroid identity and state the conditions for objective nonincrease.
  • Distinguish local fixed points from the global optimum using all seven partitions of four points, including initialization, ties, and empty clusters.
  • Run exact rational clustering, check assignments, centers, and cost traces, and identify the effects of units, K, and geometry.

Prerequisites & connections

Explore related knowledge →

References

  1. CS229 — The k-means clustering algorithm
    Andrew Ng
  2. k-means++: The Advantages of Careful Seeding
    David Arthur; Sergei Vassilvitskii · 2007

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Independently enumerated all seven unordered nonempty bipartitions using pairwise within-cluster distances, checking costs 4,16,20 and four 40/3 values plus both iteration traces.
  • Checked cost nonincrease, centroid and nearest-center fixed points on 60 rational six-point datasets against exact bipartition optima; checked exact rotation, translation, and uniform scaling.
  • Checked duplicate centers, identical points, K=1, K=n, one-dimensional inputs, invalid dimensions/coordinates/iteration limits, and rational bit-cost and storage qualifications.
  • Aligned the bilingual six anchors, four answered exercises, display equations, and identical executable code; no claim of human peer review.
  • The parent reviewed both local outcomes, the seven-partition oracle, centroid identity, empty-cluster/tie policies, convergence and expected initialization bounds. The unwritten k-means++ article link now points to an explicitly pending directory entry.
  • The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.

Source locations checked:

  • CS229 — The k-means clustering algorithm · Actual three-page PDF read: pp.1–2 assignments and mean updates; pp.2–3 coordinate descent, objective convergence versus assignments, local optima, multiple starts. Publication year not supplied because PDF does not state it.
  • k-means++: The Advantages of Careful Seeding · Actual original paper §2.1, Lemma 2.1, §2.2, Theorem 3.1 (PDF pp.2–3): consistent tie breaking, centroid identity, D² initialization, expected 8(ln k+2) bound valid after seeding. Publication year confirmed from coauthor's Stanford publication list https://theory.stanford.edu/~sergei/ under 2007; no unverified Lloyd 1957 historical claim included.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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