A service records two usage measures for each account and wants a handful of representative profiles that summarize all of them. K-means picks centers, gives each account to its nearest center, and places the centers so that the total squared distance from the accounts to their centers is as small as possible. This lesson writes down that objective, runs the two alternating steps of Lloyd’s algorithm by hand on six points, and shows why the result depends on the starting centers and on the chosen , and why a cluster is not automatically a natural category.
Key terms
K-means clustering
Definition Let be points in and an integer with . K-means clustering seeks an assignment of each point to a cluster and centers in that minimize the within-cluster sum of squares
Finding the global minimum is computationally hard in general. The standard method, Lloyd’s algorithm, starts from initial centers and alternates the assignment step and the update step until the centers stop changing. With a fixed tie rule and no empty clusters, never increases and the algorithm stops after finitely many iterations, because there are finitely many partitions and every update that moves a center strictly lowers . It stops at a partition that neither step can improve, a local optimum in this sense, which need not be the global minimum. The method assumes that squared Euclidean distance in the chosen feature representation is a useful notion of closeness.
In plain words K-means summarizes the data by representative points and judges the summary by how far, in squared distance, each point lies from its representative. It favors compact, roughly round groups of similar spread in the chosen units. It returns a partition for any data and any , whether or not the data contain distinct groups.
Example Six constructed usage profiles in a common dimensionless scale are , , , , and . With the obvious candidate puts the first three points in one cluster and the last three in the other. The next cards compute the centers and the objective of this partition, run the algorithm, and compare starting points.
Centroid and within-cluster sum of squares
Definition The centroid of a nonempty cluster with points is the coordinatewise mean
The within-cluster sum of squares of the cluster is , in squared feature units, and the objective of a partition with every center at its centroid is the sum of over the clusters. For any point in ,
so the centroid is the unique center that minimizes the cluster’s sum of squared distances. An empty cluster has no centroid.
In plain words The centroid is the average member, the balance point of the cluster, and it need not be one of the observed points. Because the distances are squared, one far point pulls the centroid toward it.
Example The cluster , , has centroid . The squared distances to it are , and , so . Measured from instead, the sum is , and the identity agrees, since .
Assignment step and update step
Definition Given current centers , the assignment step gives each point the index of a nearest center,
with a stated tie rule, which on this page is the lower center index. Given the assignments, the update step replaces each center by the centroid of the points assigned to it. Each step minimizes over its own variables with the others held fixed. In the assignment step every term of depends only on its own point’s choice, so the nearest center minimizes each term separately. In the update step splits into one sum per cluster, and for cluster with points and coordinate of its center
which is zero at the coordinate mean. Hence neither step can increase . If a cluster receives no points, its mean is undefined and the algorithm needs a declared policy, such as stopping with an error or moving that center to a poorly represented point, and the objective has to be rechecked after any such move.
In plain words Each point goes to its nearest center, and then each center moves to the middle of its points. The two steps repeat, and each round lowers the total squared distance or leaves it unchanged. A new point is assigned by comparing it with every center, not by its resemblance to one member of a cluster.
Example Start the six points with centers and . The first three points are nearer the first center and the last three nearer the second, with squared distances 0, 4, 4, 0, 4 and 4, so . The update moves the centers to and , each cluster now contributes , and
The next assignment step keeps every point in its cluster, so the update reproduces the same centers and the algorithm stops at a fixed point.
K-means initialization
Definition K-means initialization is the choice of the starting centers, and the end point of Lloyd’s algorithm depends on it. Common choices are distinct data points drawn at random and k-means++ seeding. That seeding draws the first center uniformly from the data points and each further center from the data points with probability proportional to , the squared distance from to the nearest center already chosen. The expected objective of the k-means++ seeds alone is at most times the optimal value. Because one run can end at a poor local optimum, implementations usually run several initializations and keep the run with the smallest . That improves the result in practice without guaranteeing the global minimum. A fixed random seed makes the runs reproducible.
In plain words The algorithm only walks downhill from where it starts. Two starting centers inside one group can end in a split that a better start would avoid, and spreading the starting centers out and trying several starts lowers that risk.
Example On the six points, the starting centers and both lie in the lower-left group. The first assignment gives and to the first center and the other four points to the second, with . The objective is then 97 after the update, after the next assignment moves to the first cluster, and after the next update, which reaches the same partition and centers as the first run. That agreement holds for these six points only. The four constructed points , , and show a failure. Starting at and gives the bottom pair and the top pair with centers and , a fixed point with . Starting at and gives the left pair and the right pair with . The code below records after each assignment step.
import numpy as np
def lloyd(X, centers, max_iter=100):
C = np.array(centers, dtype=float)
history = []
for _ in range(max_iter):
d2 = ((X[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)
labels = d2.argmin(axis=1) # ties go to the lower index
history.append(d2[np.arange(len(X)), labels].sum())
if len(np.unique(labels)) < len(C):
raise ValueError("empty cluster, a declared policy is needed")
new = np.array([X[labels == j].mean(axis=0) for j in range(len(C))])
if np.array_equal(new, C):
return C, labels, history
C = new
raise RuntimeError("no fixed point within max_iter")
X = np.array([[0, 0], [0, 2], [2, 0], [8, 8], [8, 10], [10, 8]], dtype=float)
for start in ([[0, 0], [8, 8]], [[0, 0], [0, 2]]):
C, labels, history = lloyd(X, start)
print(labels, np.round(history, 3)) # [16. 10.667] and [368. 34.75 10.667]Number of clusters
Definition The number of clusters is a choice made by the analyst, not a quantity the algorithm discovers. Let be the smallest achievable within-cluster sum of squares with clusters. For it satisfies , since adding a center at a data point cannot raise the total, and once reaches the number of distinct points. So the smallest training objective always favors the largest , and separate local runs need not even decrease with , because each can stop at a different local optimum. Common diagnostics are an elbow plot of against , which looks for the point after which extra centers bring small reductions, the silhouette, which compares each point’s average distance to the other members of its cluster with its average distance to the nearest other cluster, and the stability of the clusters across resamples. None of them establishes true categories in a population. When the clusters feed a prediction, is a hyperparameter chosen on validation data, never on the test set.
In plain words More centers always fit the training points at least as closely, so the objective alone cannot choose . The useful question is which number of groups gives a summary that is stable and serves the purpose at hand. Calling a cluster “high value” or “high risk” needs evidence beyond the algorithm, which never saw what such a name means.
Example For the six points the smallest objectives are for , for , for , then 4, 2 and 0 for , 5 and 6. Nearly all of the reduction comes from the second center. A local run can still misbehave. With , the starting centers , , and are already a fixed point with , which is above the best three-cluster value .
Check yourself
- A proposed cluster contains , and . Find its centroid and its within-cluster sum of squares. Another cluster has centroid . The new point is only 1 unit from the member of the first cluster. Which cluster does the assignment step give it?
Show the answer
The coordinate means are and , so the centroid is . The squared distances to it are , and , so the within-cluster sum of squares is 8.
The new point has squared distance to the center and to the center , so the assignment step gives it to the second cluster. K-means compares a point with the centers, not with individual members. If the point joins the data, the next update moves the second center toward it, and the two steps continue until nothing changes.
- Run k-means with on the six profiles of this lesson, starting from the centers , and . Find the first assignment and its objective. What happens in the update step?
Show the answer
The center is far from every point, so the first assignment is the same as with two centers. The points , and go to the first center, the other three go to the second, and .
The third cluster is empty, and the mean of no points is undefined, so the update step cannot be carried out as written. An implementation needs a declared policy, for example stopping with an error, restarting from new seeds, or moving the empty center to a point far from its current center and then recomputing the objective. A center placed outside the data is a poor start. Seeds chosen as distinct data points, as in k-means++, cannot give an empty cluster in the first assignment, because each seed is at distance zero from its own point and at a positive distance from the other seeds.
- The points 0, 1, 2, 3 and 20 lie on a line. Find the partition into two clusters with the smallest within-cluster sum of squares, and explain what it says about k-means and outliers. In one dimension an optimal partition can be found among the splits into a left group and a right group.
Show the answer
The four splits give the following sums, each the left group’s sum of squares plus the right group’s.
| Left group | Right group | Sum of squares |
|---|---|---|
The best partition puts 20 alone and summarizes the other four points by the single center 1.5. One of the only two centers is spent on one extreme point, because squared distance makes a far point very expensive. With all five points in one cluster the centroid would be 5.2, pulled far from where most points lie. With the best partition is , , with . An outlier should be investigated and handled by a documented rule before the clusters are read, and naming the singleton cluster as a group of customers would claim far more than one point supports.