Motivation
Assigning each observation to its nearest centre does not completely specify a clustering method. The remaining question is what to do with the assignment distances. Squaring and summing them gives k-means, summing their ordinary lengths gives a median objective, and taking their maximum gives k-center. These objectives agree about the nearest centre for fixed centres under the same Euclidean distance, but they generally disagree about the best locations of the centres.
The distinction becomes visible when a cluster contains an isolated observation far from the others. Its squared distance has a large effect on the k-means loss and pulls the mean toward it. An absolute-distance objective has a different minimizing representative. Restricting representatives to actual observations imposes another mathematical constraint. A centre update must minimize the objective that was defined, rather than being selected solely because it is called a centroid.
Lloyd's algorithm alternates between assignments and centre updates. Each step is easy once the other part is held fixed. Understanding its descent therefore begins with two small optimization problems, not with an assertion that the entire joint problem is easy. The termination argument also needs rules for ties and empty clusters, which are legitimate states of the iteration.
Definitions
Definition 4.2.1
(Assignment loss and nearest-centre loss)
Let be observations, let be a list of centres, and let be labels. Define
The labels specify a hard clustering. Some labels may have no observations, and centres in the list may coincide.
For fixed centres, choosing a nearest centre independently for every observation minimizes . Tied nearest centres give the same contribution to the loss. For a fixed assignment, write . When is nonempty, its mean is .
The k-median objective uses instead of squared distances. In one dimension its fixed-cluster minimizers are medians. In several dimensions, ordinary Euclidean distances require a geometric median. For Manhattan distance the coordinates separate and coordinatewise medians do minimize the corresponding objective. A medoid must additionally be one of the allowed observations and minimize the sum of distances to them.
On the line, moving a proposed median slightly to the right increases the distance to observations on its left and decreases the distance to those on its right. A minimizer balances these counts. With an even number of observations, every point between the two middle ordered values can minimize the sum. In higher-dimensional Euclidean distance, the square root couples the coordinates. For a proposed geometric median not coinciding with an observation, its gradient condition is . Coordinatewise medians instead exploit the separability of Manhattan distance; these are distinct mathematical justifications for different centre updates.
Theorem/proposition
Proposition 4.2.2
(The mean minimizes squared Euclidean distance)
For a nonempty cluster of observations with mean and any ,
Thus the unique minimizing centre is . An empty cluster contributes zero for every centre and has no mean to compute.
Proposition 4.2.3
(A Lloyd iteration decreases the loss)
Starting from nearest-centre labels, hold those labels fixed, replace every nonempty cluster centre by its mean, and keep an empty cluster's centre unchanged. Then reassign observations to nearest centres. Neither step increases , and the resulting nearest-centre loss does not exceed its preceding value.
Proposition 4.2.4
(Finite termination with a specified tie rule)
Use exact arithmetic and the preceding mean/empty-cluster rule. During reassignment, retain an observation's old label whenever it is among the nearest centres; otherwise choose the smallest nearest index. Stop when the labels no longer change. Only finitely many label changes occur, and the final centres and labels form a Lloyd fixed point.
Proof sketch or proof idea
Write and expand the squared norm. The cross terms sum to zero because . This proves the mean identity. Its second term is strictly positive for , giving uniqueness. The calculation uses the Euclidean inner product; replacing it by an arbitrary distance does not preserve the identity.
The mean is an average of the observations with nonnegative equal weights, so it lies in their convex hull, although it need not be an observed point. The multiplier in the decomposition also matters: moving a large cluster's centre a given distance from its mean costs more than making the same displacement in a small cluster. The full objective weights individual observations equally, not clusters equally. For the same reason, the mean of several cluster means should use their cluster sizes as weights to recover the overall sample mean. Equal weighting is justified by equal cluster sizes, but is not a general identity for unequal sizes.
The mean step minimizes each nonempty cluster's contribution to . The assignment step then minimizes every observation's contribution with those centres fixed. If an empty cluster retains its centre, its zero contribution causes no difficulty. Since the starting labels are nearest-centre labels, at the start of the round. These two inequalities establish descent, but non-increasing values alone do not yet establish finite termination.
For the stronger conclusion, let be the loss after setting all nonempty centres to the means determined by . Empty centres do not enter that value. If reassignment changes any label under the specified rule, the old label was not nearest, so that observation's squared distance strictly decreases. If is the new assignment and the mean-updated centres,
There are at most labelled assignments, and hence finitely many possible values of . Strict decrease at every label change prevents an assignment from recurring. Eventually labels stop changing. The nonempty centres are already their means, and the empty centres were retained, so another round leaves the state unchanged. This proves a fixed point, without identifying it as the global minimum of .
This algorithm uses a list of available centres; it does not assert that all clusters stay nonempty. Repeated centres or an unfavourable initial placement can leave a label unused. Requiring exactly nonempty clusters would add a constraint to the optimization problem. Moving an observation to an empty label simply to satisfy that constraint can increase the held assignment loss, so it is not part of the descent proof above. Keeping the empty centre unchanged is a complete specified rule for the version being analyzed here.
Proof X-ray
Where finite termination really comes from
Descent alone gives a non-increasing sequence of losses, and such a sequence can repeat one value forever. The proof avoids this with two choices. First, it measures progress by , which depends on the labels alone and therefore takes at most values. Second, the retained-old-label tie rule ensures that a label changes only when the old centre is strictly farther, so every label change makes strictly smaller. A strictly decreasing sequence in a finite set must stop. Without the tie rule the strict inequality can fail, and Exercise 4 describes labels that keep changing at constant loss.
Worked examples
Worked example 4.2.5
(Example 1: Trace mean updates and reassignment separately)
Take observations on the line and choose with initial centres . The observations never move: only their labels and the two centres change. In each table, compare the two squared distances in a row and put the smaller-distance centre's index in the last column. Do not update a centre halfway through a table; finish assigning all observations before taking any means.
Step 0: Assign using the initial centres
The clusters are and . Add the selected entries, not both distance columns: .
Step 1: Update the means, then compare distances again
Hold those clusters fixed and calculate
With these centres but the old labels, the loss is . Now use the new centres to assign every point again:
Point changes from label to label because . Point is tied, so it keeps its old label , as specified in the tie rule. The clusters become and , and . Thus and use the same centres but different labels.
Step 2: Recompute both means from the new clusters
The held-label loss is . Compare distances again:
Point now changes to label because . The new loss is , and the clusters are and .
Step 3: Update once more and verify that no label changes
The labels stay ; taking their means again also leaves the centres unchanged. We have reached a Lloyd fixed point and may stop. The final loss is
There was no empty cluster in this run. The earlier empty-cluster rule is still needed for other initializations. A stable assignment certifies that this run has stopped, not a general guarantee that every initialization reaches a globally optimal solution.
Worked example 4.2.6
(Example 2: A larger-k local run can return a worse loss)
Use . With three centres , the first two clusters are singletons and the final cluster is . Every centre is its cluster mean. Each observation strictly prefers its assigned centre, so this is a Lloyd fixed point. Its loss is
For comparison, two centres produce clusters and and loss . Thus this converged three-centre result is worse than a feasible two-centre result. A different three-centre initialization at gives three nearby pairs and loss .
The example demonstrates both the role of initialization and the meaning of restarts. Repeating a run and keeping its lowest loss can improve the best observed result, while a particular fixed point is not an optimality certificate. Comparisons across independent local runs also need not be monotone in .
Worked example 4.2.7
(Example 3: Means, medians, and medoids answer different questions)
For one cluster with observations , the squared-distance minimizer is the mean , with squared loss . Centre has squared loss . For the sum of ordinary absolute distances, however, the median gives loss , while the mean gives . Restricting the centre to an observed point gives the medoid , whose distance sum is again .
In the plane, consider , , and . Their coordinatewise median is and has Euclidean-distance sum . The feasible point gives
Thus the coordinatewise median is not a Euclidean geometric median for this dataset. Coordinatewise minimization instead solves the Manhattan-distance problem, where the coordinate absolute differences add separately.
Counterexample mode
Mean updates do not descend for the median objective
The descent proposition uses the fact that the mean exactly minimizes the held-label squared cost. Keep the alternation but change the objective to , the sum of ordinary distances. Take a single cluster with observations and start at the centre , a median, whose distance sum is . The mean update moves the centre to , and the distance sum becomes . A step that is optimal for squared distances has increased the absolute-distance loss, so alternating nearest assignments with means is not a descent method for k-median. Replacing the mean by a median restores the argument in one dimension, because a median minimizes the held-label distance sum.
A reproducible Lloyd calculation
The code follows Example 1. It prints after reassignment, rather than the loss for labels held over from the preceding round. Empty centres are left in place, and an old label is preserved on an exact distance tie.
import numpy as np
X = np.array([0.0, 2.0, 3.0, 9.0, 10.0])[:, None]
C = np.array([[0.0], [3.0]])
rows = np.arange(len(X))
def distances2():
return np.sum((X[:, None, :] - C[None, :, :]) ** 2, axis=2)
D = distances2()
labels = np.argmin(D, axis=1)
print(f"initial cost={D[rows, labels].sum():.6f}")
round_number = 0
while True:
round_number += 1
for j in range(len(C)):
members = X[labels == j]
if len(members):
C[j] = members.mean(axis=0)
D = distances2()
nearest = np.argmin(D, axis=1)
new_labels = np.where(D[rows, labels] <= D[rows, nearest], labels, nearest)
cost = float(D[rows, new_labels].sum())
centre_text = ", ".join(f"{centre[0]:.6f}" for centre in C)
print(f"{round_number}: centres=({centre_text}), cost={cost:.6f}")
if np.array_equal(new_labels, labels):
break
labels = new_labels
print("labels:", labels.tolist())
initial cost=86.000000
1: centres=(0.000000, 6.000000), cost=38.000000
2: centres=(1.000000, 7.333333), cost=15.888889
3: centres=(1.666667, 9.500000), cost=5.166667
labels: [0, 0, 0, 1, 1]
Initialization and the elbow curve
An initialization chooses a basin for the alternating updates. Farthest-first selection spreads centres by always taking a current farthest observation. The k-means++ initialization instead selects a first observation uniformly at random and then samples a new one with probability proportional to its squared distance from the chosen centres. For a positive sum of squared distances, those probabilities are
When every is zero, every input is already represented by a chosen centre. Otherwise the sampling favors currently poorly represented observations, but does not simply select the single farthest one. Lloyd updates follow after the initialization.
Let denote the globally smallest loss using at most centres. Appending a centre cannot increase any observation's nearest distance, so . With one centre at each observation the loss is zero. An elbow plot examines where extra centres give a substantially smaller improvement. The feasible-set argument concerns global optima; Example 2 shows why losses from arbitrary local runs need not inherit that ordering. An elbow is a modelling aid for balancing simplicity and fit, not a theorem that a unique number of clusters can be recovered from every dataset.
Choose the objective before choosing the algorithm
For the same observations and the same number of centres, three different questions produce three different objectives:
- k-means: minimize the total squared Euclidean distortion. With a cluster held fixed, its arithmetic mean is the unique best unrestricted centre. Lloyd alternates nearest-centre assignments and these means; it can stop at a local solution.
- Euclidean k-median: minimize the total ordinary Euclidean distance. With a cluster held fixed, use a geometric median. In one dimension this is an ordinary median. In higher dimensions, taking a median separately in each coordinate instead minimizes the sum of Manhattan () distances, not generally the sum of Euclidean distances.
- k-center: minimize the largest nearest-centre distance, so even the most poorly represented observation matters. For a fixed one-dimensional group and unrestricted centres, the midpoint of its smallest and largest observations is optimal. In higher dimensions the corresponding fixed-group problem is a smallest enclosing ball; the coordinatewise midrange is not a general solution. Farthest-first gives an approximation to the multi-centre problem, rather than performing Lloyd's mean updates.
For fixed centres, squared and ordinary Euclidean distances select the same nearest centre because squaring preserves their order. This does not make the objectives or centre updates interchangeable. Restrictions also matter: if each centre must be an observed point or an approved site, an unrestricted mean, median, or midpoint may not be admissible. Optimize over the allowed sites instead.
A decision example: four locations, one service point
Suppose four equally weighted demand locations lie on a straight road at , measured in kilometres, and one service point may be placed anywhere on the road. Before calculating a centre, state what cost the service is trying to reduce.
- If the model assigns a cost proportional to squared distance, choose the mean . Its squared cost is .
- If each location generates one equally weighted trip and total travel distance is the cost, choose a median. Every point of is optimal; choosing gives total distance .
- If the requirement is the smallest possible worst travel distance, choose the endpoints' midpoint . The largest distance is . A radius smaller than cannot cover both endpoints, so this solution has a matching lower-bound certificate.
Evaluate all three candidate centres under all three costs:
Compare entries within one column, not across columns: squared distance has units of square kilometres, while the other two columns have units of kilometres and answer different service questions. The median reduces total travel but leaves location seven kilometres away. The k-center choice improves that worst distance, at the expense of total travel. Neither is universally “better”; the service requirement decides. With unequal demand, use the appropriate weights for the sum objectives. If a site's accessibility is constrained, the permitted centre set must also change.
For more than one service point, each location first uses its nearest point, and the same choice of how to aggregate costs remains. The one-dimensional k-center calculation shows why endpoint midpoints and contiguous splits solve that particular covering problem. The Lloyd trace above instead optimizes squared-distance sums with cluster means.
Clustering is not labelled classification
Here the input consists of feature vectors, without a supplied correct class for each observation. Clustering constructs groups from the chosen geometry and objective. A supervised classifier instead learns from feature–class pairs and is evaluated on its ability to predict those classes. Giving a new observation its nearest cluster ID is a possible assignment rule, but does not turn the groups into verified class predictions.
Labels and merely name two groups. Swapping those IDs and their centres leaves the partition and all three costs unchanged. Do not interpret “cluster 1” as a particular real category without a separate, supported interpretation. If external class labels are available for evaluation, account for arbitrary cluster numbering; raw equality of cluster IDs and class numbers is not a valid accuracy calculation.
A useful end-to-end answer therefore states the features and their scaling, the objective, the allowed centres and chosen , then reports the resulting groups and objective value. Finally distinguish what was proved: a Lloyd fixed point, a best result among restarts, an approximation guarantee, or a global optimum established by upper and lower bounds.
Common mistakes
Common mistake
(Changing the update while keeping the old objective)
The arithmetic mean minimizes squared Euclidean distances. A one-dimensional absolute-distance objective uses medians; a multidimensional Euclidean absolute-distance objective uses a geometric median. A medoid must minimize the distance sum over allowed observed representatives, not just select an observation that looks close to the arithmetic mean.
The loss can remain unchanged at a tie, so non-increase and finitely many assignments alone do not exclude cycles of equal-cost states. The retained old-label rule makes every actual label change a strict improvement. Likewise, keeping an empty centre is an explicit valid operation because its fixed-assignment contribution is zero; taking the mean of an empty set is not a defined replacement.
Summary
Specify the distance, the aggregation of assignment costs, and the allowed centre locations before choosing an update. Lloyd's mean and nearest-centre steps decrease the squared Euclidean objective. With explicit tie and empty cluster rules the assignments eventually stabilize, although their fixed point can have a large loss. Initialization, restarts, and elbow comparisons should be interpreted relative to that distinction.
For repeated runs at one fixed , retain the smallest objective value actually obtained. That retained value cannot increase as further runs are added, because the earlier candidates remain available. This is a statement about the best observed result, rather than the quality of each random initialization. Cluster index numbers also have no intrinsic meaning: permuting labels and the corresponding centres leaves the loss unchanged. Comparing two runs by their objectives and represented groups avoids mistaking different index names for a difference in clustering quality.
Exercises
Quick check
(Exercise 1: For one cluster containing , , and , find the mean, the minimum squared loss, and the extra loss from choosing centre .)
Use the squared-distance decomposition rather than differentiating again.
Quick check
(Exercise 2: For observations , , , and on the line, find all centres minimizing the absolute-distance sum. Which observed points are medoids?)
Every point between the two middle observations is a median.
Quick check
(Exercise 3: Let observations be , , and current centres be . Use nearest assignments and the stated mean/empty-cluster rule. Find the updated centres and loss.)
The third cluster is empty; its centre is retained.
Quick check
(Exercise 4: Two observations both equal , and both centres equal . How could arbitrary tie changes keep loss zero while changing labels? What does the stated tie rule do?)
Separate a fixed objective value from a fixed labelled state.
Solutions
Solution · Exercise 1 solution
The mean is and the minimum squared loss is . At centre the loss is ; the extra loss is , matching the difference.
Solution · Exercise 2 solution
All real centres in minimize the absolute-distance sum, with value . Restricting the centre to observed points leaves and as medoids, each attaining that value.
Solution · Exercise 3 solution
The clusters are , , and the empty set. Their updated centres are . Reassignment leaves them the same, and the loss is .
Solution · Exercise 4 solution
One could keep swapping labels and : both assigned means remain zero and every distance is zero. This changes the labelled state without improving the objective. Retaining each old label when it is tied prevents these swaps, so the state stops changing.
Related notes
Voronoi cells and k-center derives nearest-site geometry and a maximum-distance objective. Model validation and ridge regression explains the separate task of comparing fitted models. The course reading list collects further reading on these clustering objectives.