Simple Algorithm
Machine Learning · Descent · 22 min

Clustering

Grouping similar points: k-means and beyond.

k-means fits in three lines of pseudocode and hides a surprising amount of mathematics: one objective with three equivalent faces, a proof that the algorithm never makes it worse, a randomized seeding with a provable guarantee, and a built-in idea of what a cluster is that real data often violate. This lesson derives all of it, then shows how to choose the number of clusters and when to switch to mixtures, hierarchies or density-based methods.

What you’ll learn

  • Write the k-means objective as distances to centroids, as within-cluster pairwise distances and as between-cluster scatter, and prove the three forms equivalent.
  • Prove that Lloyd's algorithm never increases the objective and terminates, and explain why its fixed points can be poor.
  • Implement k-means++ seeding and state its O(log⁡k)\order{\log k} guarantee.
  • Choose the number of clusters with the elbow, the silhouette and the gap statistic, and explain why the objective alone cannot.
  • Recognize when k-means' assumptions fail, choose among Gaussian mixtures, hierarchical clustering and DBSCAN, and evaluate a clustering with and without labels.

The k-means objective, three ways

A clustering of points x1,…,xn∈Rd\mathbf x_1,\dots,\mathbf x_n\in\R^d into kk groups is a partition C1,…,CkC_1,\dots,C_k of the indices {1,…,n}\{1,\dots,n\}. Most clustering methods pick the partition that optimizes a criterion, and the criterion is where a method's idea of "a cluster" lives. k-means minimizes the within-cluster sum of squares, also called the inertia:

W(C1,…,Ck)=∑j=1k∑i∈Cj∥xi−μj∥2,μj=1∣Cj∣∑i∈Cjxi,W(C_1,\dots,C_k)=\sum_{j=1}^k\sum_{i\in C_j}\norm{\mathbf x_i-\boldsymbol\mu_j}^2,\qquad\boldsymbol\mu_j=\frac1{\abs{C_j}}\sum_{i\in C_j}\mathbf x_i,

where μj\boldsymbol\mu_j is the centroid of cluster jj. Equivalently, it chooses kk centers c1,…,ck\mathbf c_1,\dots,\mathbf c_k to minimize ∑imin⁡j∥xi−cj∥2\sum_i\min_j\norm{\mathbf x_i-\mathbf c_j}^2: for fixed centers each point goes to its nearest center, and for a fixed partition the best centers are the centroids, by the first identity below.

DerivationThree faces of one objective
  1. ∑i∈C∥xi−c∥2=∑i∈C∥xi−μ∥2+∣C∣ ∥μ−c∥2\sum_{i\in C}\norm{\mathbf x_i-\mathbf c}^2=\sum_{i\in C}\norm{\mathbf x_i-\boldsymbol\mu}^2+\abs{C}\,\norm{\boldsymbol\mu-\mathbf c}^2

    Centroids are optimal. For a group CC with centroid μ\boldsymbol\mu and any point c\mathbf c, expand xi−c=(xi−μ)+(μ−c)\mathbf x_i-\mathbf c=(\mathbf x_i-\boldsymbol\mu)+(\boldsymbol\mu-\mathbf c). The cross term vanishes because ∑i∈C(xi−μ)=0\sum_{i\in C}(\mathbf x_i-\boldsymbol\mu)=\mathbf 0:

  2. ∑i∈C∑l∈C∥xi−xl∥2=2∣C∣∑i∈C∥xi−μ∥2⟹W=∑j=1k12∣Cj∣∑i,l∈Cj∥xi−xl∥2\sum_{i\in C}\sum_{l\in C}\norm{\mathbf x_i-\mathbf x_l}^2=2\abs{C}\sum_{i\in C}\norm{\mathbf x_i-\boldsymbol\mu}^2\quad\Longrightarrow\quad W=\sum_{j=1}^k\frac{1}{2\abs{C_j}}\sum_{i,l\in C_j}\norm{\mathbf x_i-\mathbf x_l}^2

    Pairwise form. Put c=xl\mathbf c=\mathbf x_l in the identity and sum over l∈Cl\in C: the left side becomes the sum over all ordered pairs, the right side 2∣C∣2\abs C times the cluster's scatter. So WW can be written with pairwise distances alone: each cluster contributes the sum of squared distances over its unordered pairs of members, divided by its size. No centroids are needed, which is what kernel k-means exploits:

  3. T=∑i=1n∥xi−xˉ∥2=∑j=1k∑i∈Cj∥xi−μj∥2⏟W+∑j=1k∣Cj∣ ∥μj−xˉ∥2⏟BT=\sum_{i=1}^n\norm{\mathbf x_i-\bar{\mathbf x}}^2=\underbrace{\sum_{j=1}^k\sum_{i\in C_j}\norm{\mathbf x_i-\boldsymbol\mu_j}^2}_{W}+\underbrace{\sum_{j=1}^k\abs{C_j}\,\norm{\boldsymbol\mu_j-\bar{\mathbf x}}^2}_{B}

    Between-cluster form. Apply the identity to each cluster with c=xˉ\mathbf c=\bar{\mathbf x}, the mean of all the data, and add. The total scatter TT does not depend on the clustering, so minimizing the within-cluster scatter WW is the same as maximizing the between-cluster scatter BB:

Predict before you look

One cluster holds four points on a line: 0,2,4,100, 2, 4, 10. What is its within-cluster sum of squares?

Show the answer

56

The centroid is 16/4=416/4=4, and the squared deviations are 16+4+0+36=5616+4+0+36=56. The pairwise form agrees: the six distinct pairs have squared distances 4+16+100+4+64+36=2244+16+100+4+64+36=224, the ordered pairs twice that, 448448, and 448/(2⋅4)=56448/(2\cdot4)=56. The point at 10 contributes most of the total: squared distances make k-means sensitive to outliers.

Other criteria encode other ideas of a cluster. k-medians replaces squared distances by ℓ1\ell_1 distances, and its optimal centers are coordinatewise medians, less sensitive to outliers. k-medoids restricts centers to data points, so it works with any dissimilarity, not just Euclidean distance. A Gaussian mixture maximizes a likelihood with soft memberships, graph methods minimize cuts of a similarity graph, and density-based methods look for dense regions separated by sparse ones. The last step of this lesson compares them.

Lloyd's algorithm and why it stops

text
LLOYD(points x_1..x_n, initial centers c_1..c_k)
  repeat
      for i = 1..n:   a_i = argmin_j ||x_i - c_j||^2       # assignment, O(nkd)
                      (keep the current a_i if it is among the nearest)
      for j = 1..k:   c_j = mean of { x_i : a_i = j }       # update, O(nd)
                      (an empty cluster keeps its old center, or is re-seeded)
  until no a_i changed
  return assignments a, centers c

The batch algorithm usually called Lloyd's algorithm. Lloyd devised the alternation in 1957 to design a one-dimensional quantizer for a known signal density; it was published in 1982. The sample version on points became standard in clustering.

DerivationProof
  1. W(a′,c)=∑imin⁡j∥xi−cj∥2≤W(a,c)W(\mathbf a',\mathbf c)=\sum_i\min_j\norm{\mathbf x_i-\mathbf c_j}^2\le W(\mathbf a,\mathbf c)

    Assignment. For fixed centers, WW is a sum of one term per point, and each term is minimized by the nearest center. So reassigning can only lower each term:

  2. ∑i: ai=j∥xi−cj∥2=∑i: ai=j∥xi−μj∥2+∣Cj∣ ∥μj−cj∥2 ≥ ∑i: ai=j∥xi−μj∥2\sum_{i:\,a_i=j}\norm{\mathbf x_i-\mathbf c_j}^2=\sum_{i:\,a_i=j}\norm{\mathbf x_i-\boldsymbol\mu_j}^2+\abs{C_j}\,\norm{\boldsymbol\mu_j-\mathbf c_j}^2\ \ge\ \sum_{i:\,a_i=j}\norm{\mathbf x_i-\boldsymbol\mu_j}^2

    Update. For fixed assignments, WW splits into one sum per cluster, and by the first identity of the previous step each sum is smallest at the centroid:

  3. W(P0)>W(P1)>W(P2)>⋯(partitions Pt all distinct, at most kn of them)W(P_0)>W(P_1)>W(P_2)>\cdots\qquad\text{(partitions }P_t\text{ all distinct, at most }k^n\text{ of them)}

    Termination. After every update the centers are the centroids of the current partition, so WW is then a function of the partition alone. An assignment step that changes anything moves some point to a strictly nearer center (ties do not move points), so WW strictly drops and the previous partitions can never recur. There are at most knk^n partitions, so the algorithm stops.

Each iteration costs O(nkd)\order{nkd}, and in practice a few dozen iterations usually suffice. The worst case is far worse: there are inputs in the plane on which Lloyd's algorithm takes exponentially many iterations (Vattani, 2011), although under small random perturbations of the input the expected number is polynomial (Arthur, Manthey & Röglin, 2011). The bigger issue is quality. A fixed point is only a local minimum in a weak sense, and its cost can be arbitrarily worse than the optimum; the Convergence lesson k-Means: Hardness & Guarantees gives a four-point example.

Think first At a fixed point of Lloyd's algorithm every point is nearest to its own centroid. Can moving a single point to another cluster still lower WW?

Yes, because the move also shifts both centroids. Removing x\mathbf x from cluster AA (size nAn_A) lowers WW by nAnA−1∥x−μA∥2\frac{n_A}{n_A-1}\norm{\mathbf x-\boldsymbol\mu_A}^2, and adding it to BB raises WW by nBnB+1∥x−μB∥2\frac{n_B}{n_B+1}\norm{\mathbf x-\boldsymbol\mu_B}^2. With nA=2n_A=2, nB=10n_B=10, and distances 11 and 1.21.2 to the two centroids, the move gains 2⋅1=22\cdot1=2 and costs 1011⋅1.44≈1.31\tfrac{10}{11}\cdot1.44\approx1.31: it lowers WW although the point is nearer to μA\boldsymbol\mu_A. Hartigan's variant of k-means makes exactly these single-point moves, and its fixed points are a subset of Lloyd's.

Seeding with k-means++

Where Lloyd's algorithm ends depends on where it starts. Seeding with kk random data points often puts two seeds in one true cluster and none in another, and no sequence of assign and update steps can repair that. Restarting many times and keeping the lowest WW helps; seeding well helps more.

k-means++ (Arthur & Vassilvitskii, 2007) picks the first center uniformly at random from the data. Each further center is a data point x\mathbf x drawn with probability proportional to D(x)2D(\mathbf x)^2, the squared distance from x\mathbf x to the nearest center chosen so far. Points far from every current center are likely picks, so the seeds spread across the clusters. An unseeded cluster carries the combined weight of all its points, while an isolated outlier carries the weight of one, although a sufficiently distant outlier can still be picked.

python
import numpy as np

def kmeans_pp_seeds(X, k, seed=0):
    rng = np.random.default_rng(seed)
    n = X.shape[0]
    centers = [X[rng.integers(n)]]                    # first seed: uniform
    d2 = ((X - centers[0]) ** 2).sum(axis=1)          # squared distance to nearest seed
    for _ in range(1, k):
        i = rng.choice(n, p=d2 / d2.sum())            # D^2 sampling
        centers.append(X[i])
        d2 = np.minimum(d2, ((X - X[i]) ** 2).sum(axis=1))
    return np.array(centers)

Seeding costs O(nkd)\order{nkd}, the same as one Lloyd iteration. scikit-learn's KMeans(n_clusters=k, init='k-means++', n_init=10) uses a greedy variant of this seeding (it draws several candidates at each step and keeps the one that lowers the cost most) and keeps the best of several runs.

Predict before you look

For k=10k = 10 clusters, how large is the guarantee factor 8(ln⁡k+2)8(\ln k + 2)?

Show the answer

34.4

ln⁡10≈2.303\ln10\approx2.303, so the factor is 8×4.303≈34.48\times4.303\approx34.4. It is a worst-case bound on the expected cost, valid for every data set, and in practice k-means++ does far better: on the widget's blobs it lands within 5% of the best clustering in about 98% of draws. The Convergence lesson proves the two lemmas behind the bound.

At scale, three refinements are common. Mini-batch k-means (Sculley, 2010) updates the centroids from small random batches, trading a little accuracy for large speedups. k-means|| (Bahmani, Moseley, Vattani, Kumar & Vassilvitskii, 2012) oversamples candidate seeds in a few parallel rounds instead of kk sequential ones. And the triangle inequality lets exact Lloyd iterations skip most distance computations once centroids stop moving much (Elkan, 2003).

How many clusters?

The objective cannot choose kk. Let Wk⋆W_k^\star be the optimal inertia with kk clusters. Take an optimal kk-clustering, pick a point x\mathbf x that differs from its cluster's centroid, and give it a cluster of its own: removing x\mathbf x from its cluster AA lowers WW by ∣A∣∣A∣−1∥x−μA∥2>0\frac{\abs A}{\abs A-1}\norm{\mathbf x-\boldsymbol\mu_A}^2>0, and a singleton costs nothing. So Wk+1⋆<Wk⋆W_{k+1}^\star<W_k^\star until every point has its own cluster. The three standard aids look at the shape of the curve instead, or compare it with a reference.

  • The elbow. Plot Wk⋆W_k^\star against kk and look for the bend after which extra clusters buy little. On the blobs of the widget above the best values are 66.7,32.7,8.12,6.86,5.8466.7, 32.7, 8.12, 6.86, 5.84 for k=1,…,5k=1,\dots,5: a sharp bend at 3. Many data sets show no clear bend.
  • The silhouette (Rousseeuw, 1987). For point ii, let a(i)a(i) be its mean distance to the other points of its own cluster, and b(i)b(i) the smallest mean distance from ii to the points of another cluster. Then s(i)=b(i)−a(i)max⁡{a(i), b(i)}∈[−1,1]s(i)=\dfrac{b(i)-a(i)}{\max\{a(i),\,b(i)\}}\in[-1,1]: near 1 the point sits well inside its cluster, near 0 on a border, and below 0 it is closer to another cluster. Choose the kk with the largest average silhouette. Computing it takes O(n2)\order{n^2} distances.
  • The gap statistic (Tibshirani, Walther & Hastie, 2001). Compare log⁡Wk\log W_k with its expected value under a reference distribution with no clusters, uniform over the range of each feature (or over a box aligned with the principal components), estimated from BB simulated data sets: Gap(k)=E∗[log⁡Wk]−log⁡Wk\mathrm{Gap}(k)=\E^*[\log W_k]-\log W_k. Choose the smallest kk with Gap(k)≥Gap(k+1)−sk+1\mathrm{Gap}(k)\ge\mathrm{Gap}(k+1)-s_{k+1}, where sks_k is the simulation standard deviation times 1+1/B\sqrt{1+1/B}. Unlike the elbow and the silhouette, it can answer k=1k=1.
Check your understanding

A point's mean distance to the other members of its cluster is a(i)=3a(i)=3, and its mean distance to the nearest other cluster is b(i)=2b(i)=2. What is its silhouette, and what does it suggest?

  1. s(i)=1/3s(i)=1/3: the point is well clustered
  2. s(i)=−1s(i)=-1: the point is an outlier
  3. s(i)=−1/3s(i)=-1/3: the point is probably in the wrong cluster
  4. s(i)=2/3s(i)=2/3: the point sits on a border
Show the answer

C. s(i)=−1/3s(i)=-1/3: the point is probably in the wrong cluster

s(i)=(2−3)/max⁡{3,2}=−1/3s(i)=(2-3)/\max\{3,2\}=-1/3. A negative silhouette means the point is, on average, closer to another cluster than to its own. A few such points are normal at borders; many suggest a poor choice of kk or a method whose idea of a cluster does not fit the data.

Two more tools are common. Stability: recluster bootstrap samples or subsamples and keep a kk whose clusterings agree with each other. It is weaker evidence than it looks: for large samples an algorithm that finds the global optimum is stable exactly when the optimum is unique, which depends on the symmetries of the data rather than on the true number of groups (Ben-David, von Luxburg & Pál, 2006). Likelihood criteria such as BIC choose the number of components of a mixture model; the Probabilistic Machine Learning topic covers them. In practice the decisive question is often which kk makes the clusters useful.

When k-means is the wrong tool

Nearest-centroid assignment builds in four assumptions:

  • Convex clusters. The cells {x:∥x−μj∥≤∥x−μl∥ ∀l}\{\mathbf x:\norm{\mathbf x-\boldsymbol\mu_j}\le\norm{\mathbf x-\boldsymbol\mu_l}\ \forall l\} are convex polygons (a Voronoi diagram). On two interleaved half-moons, k-means with k=2k=2 reaches practically the same answer from every start, inertia 31.73, and it agrees with the true moons on only about 75–76% of the points (try it below).
  • One shared, round spread. Every cluster is measured with the same Euclidean ruler. k-means is the limit of EM for a Gaussian mixture with equal weights and a shared covariance σ2I\sigma^2I as σ→0\sigma\to0 (the Descent lesson Latent Variables & EM shows how the responsibilities harden into nearest-centroid assignments). Stretched clusters get cut across, and a large, spread-out cluster is often split while two small ones are merged.
  • No noise. Every point must join some cluster, and squared distances let one far outlier drag its centroid or claim a cluster of its own.
  • Meaningful units. Distances add up squared differences across features, so features need comparable scales: standardize them, or weight them deliberately.

A Gaussian mixture relaxes the first two assumptions. Each component has its own mean, covariance matrix and weight; the EM algorithm alternates computing each point's responsibilities and refitting the components by weighted averages, and the log-likelihood never decreases.

Hierarchical clustering builds a whole tree instead of one partition. The agglomerative version starts with every point on its own and repeatedly merges the two closest clusters, where "closest" is set by a linkage: single (closest pair of points), complete (farthest pair), average (mean over all pairs) or Ward (smallest increase in WW). The merges form a dendrogram, and cutting it at a height gives a flat clustering for any kk. Single linkage follows chains of nearby points, so it can trace the moons, and it can also leak across a thin bridge of noise; Ward behaves much like k-means.

DBSCAN (Ester, Kriegel, Sander & Xu, 1996) defines clusters by density. With a radius ε\varepsilon and a count minPts\mathit{minPts}, a point is a core point if its ε\varepsilon-neighborhood, which includes the point itself, holds at least minPts\mathit{minPts} points. Clusters are the maximal sets of points that are density-connected through chains of core points; non-core points within ε\varepsilon of a core point are border points, and everything else is labeled noise. DBSCAN finds clusters of any shape and needs no kk, but one ε\varepsilon cannot fit clusters of very different densities.

MethodWhat a cluster isNeeds kk?NoiseCost
k-meanspoints nearest one centroid: convex, round, similar spreadyesnone: every point is assignedO(nkd)\order{nkd} per iteration
Gaussian mixture (EM)a Gaussian cloud: elliptical, soft membershipyes (BIC can help)low-density points stand out, but still get responsibilitiesO(nkd2)\order{nkd^2} per iteration with full covariances
Agglomerativea branch of the merge tree; shape depends on the linkageno: cut the dendrogram anywheresingle linkage chains through itO(n2)\order{n^2} memory, O(n2)\order{n^2} to O(n3)\order{n^3} time
DBSCANa dense region bounded by sparse ones: any shapeno (ε\varepsilon and minPts\mathit{minPts} instead)labeled explicitlyfast with a spatial index in low dimension; O(n2)\order{n^2} in the worst case
Spectrala well-connected part of a similarity graphyesvia the grapheigenvectors of an n×nn\times n matrix
No method dominates: each is right when the data match its idea of a cluster. The Convergence lessons develop the last three.

Judging a clustering, and the road ahead

When some reference labels exist, compare partitions pair by pair. The Rand index is the fraction of pairs of points on which two partitions agree, both putting the pair together or both splitting it. Chance agreement can be high, so the adjusted Rand index (Hubert & Arabie, 1985) rescales it to have expected value 0 for random partitions with the same cluster sizes and value 1 for identical ones. It ignores how the clusters are named, which is essential: cluster 2 of one run may be cluster 3 of another.

Without labels, the evidence is internal (silhouettes, stability across restarts and subsamples) and practical (do the clusters help the task?). Different groupings of the same data can all be legitimate: photos can be grouped by who is in them or by where they were taken. Kleinberg (2002) turned this into a theorem: no clustering rule satisfies three natural requirements at once.

Think first Partition PP groups four points as {1,2},{3,4}\{1,2\},\{3,4\} and partition QQ as {1,2,3},{4}\{1,2,3\},\{4\}. On how many of the 6 pairs do they agree, and what is the Rand index?

They agree on (1,2)(1,2) (together in both), (1,4)(1,4) and (2,4)(2,4) (apart in both), and disagree on (1,3)(1,3), (2,3)(2,3) and (3,4)(3,4). So the Rand index is 3/6=0.53/6=0.5. The adjusted Rand index subtracts what random partitions with these cluster sizes would score and divides by the room above that, so the same disagreement looks worse once chance is accounted for: here the adjusted Rand index is exactly 0, the value chance alone would give.

Key takeaways

  • k-means minimizes W=∑j∑i∈Cj∥xi−μj∥2W=\sum_j\sum_{i\in C_j}\norm{\mathbf x_i-\boldsymbol\mu_j}^2, which can be written with within-cluster pairwise distances alone (each cluster's sum over its pairs, divided by its size) and, because T=W+BT=W+B, is the same as maximizing the between-cluster scatter.
  • Lloyd's algorithm alternates nearest-center assignment and centroid updates. Neither step increases WW, so it terminates, but at a fixed point that can be a poor local optimum. Seed with k-means++, whose expected cost is at most 8(ln⁡k+2)8(\ln k+2) times the optimum, and keep the best of several runs.
  • The optimal WW always falls as kk grows. Choose kk with the elbow, the silhouette s(i)=(b−a)/max⁡{a,b}s(i)=(b-a)/\max\{a,b\}, the gap statistic's comparison with uniform data, stability or usefulness, and remember that clustering algorithms return clusters even when there are none.
  • k-means assumes convex, round clusters of similar spread, no noise and comparable feature scales. Gaussian mixtures give soft, elliptical clusters, hierarchical clustering gives a whole tree, and DBSCAN finds arbitrary shapes and labels noise.
  • With reference labels, compare partitions with the adjusted Rand index; without them, rely on stability and usefulness, since no single criterion defines the right clustering.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which statement about Lloyd's algorithm for k-means is true?

  1. It always finds the clustering with the smallest inertia
  2. Neither the assignment step nor the update step can increase the inertia, so it terminates, but possibly at a poor local optimum
  3. The update step can increase the inertia when clusters have very different sizes
  4. Each iteration needs all n2n^2 pairwise distances
Show the answer

B. Neither the assignment step nor the update step can increase the inertia, so it terminates, but possibly at a poor local optimum

Nearest-center assignment minimizes each point's term for fixed centers, and centroids minimize each cluster's sum for fixed assignments, so WW never rises; with consistent tie-breaking no partition repeats, and there are finitely many. The fixed point depends on the start, and finding the global optimum is NP-hard.

Question 2

In k-means++ seeding, how is each center after the first chosen?

  1. As the data point farthest from all centers chosen so far
  2. Uniformly at random among the data points
  3. At random, with probability proportional to the distance D(x)D(\mathbf x) to the nearest chosen center
  4. At random, with probability proportional to D(x)2D(\mathbf x)^2
Show the answer

D. At random, with probability proportional to D(x)2D(\mathbf x)^2

D2D^2 sampling favors distant points, which spreads the seeds over the clusters, yet stays random: a whole unseeded cluster usually carries far more total weight than one stray point. The squared distance matches the k-means cost, which is what makes the 8(ln⁡k+2)8(\ln k+2) analysis work.

Question 3

A data set has total scatter T=100T=100 around its overall mean. A new clustering lowers the within-cluster scatter WW from 40 to 25. What happens to the between-cluster scatter BB?

  1. It rises from 60 to 75
  2. It falls from 60 to 45
  3. It stays at 60, because BB depends only on the data
  4. It cannot be determined without the cluster sizes
Show the answer

A. It rises from 60 to 75

T=W+BT=W+B for every partition, and TT is fixed by the data. So B=T−WB=T-W goes from 100−40=60100-40=60 to 100−25=75100-25=75: lowering the within-cluster scatter and raising the between-cluster scatter are the same move.

Question 4

A data set has two dense, curved, interleaved groups plus about 5% of points scattered as background noise. Which method fits it best?

  1. k-means with k=2k=2
  2. DBSCAN with a radius ε\varepsilon matched to the groups' density
  3. A Gaussian mixture with two spherical components
  4. k-means with kk chosen by the elbow
Show the answer

B. DBSCAN with a radius ε\varepsilon matched to the groups' density

DBSCAN's clusters are density-connected regions of any shape, and points in sparse areas are labeled noise instead of being forced into a cluster. Methods built on centroids or Gaussian clouds favor compact, convex groups and must assign every point.

Question 5

Why is k-means sensitive to outliers?

  1. Because k-means++ always chooses outliers as seeds
  2. Because outliers make Lloyd's algorithm fail to converge
  3. Because the objective sums squared distances, so one far point can pull a centroid a long way or claim a cluster of its own
  4. Because outliers change the number of clusters kk
Show the answer

C. Because the objective sums squared distances, so one far point can pull a centroid a long way or claim a cluster of its own

An outlier at distance rr adds r2r^2 to the objective, so the algorithm will move a centroid toward it, or devote a whole cluster to it, rather than pay that cost. k-medians, k-medoids and DBSCAN, which treats isolated points as noise, are less sensitive.

Go deeper

Further reading

  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), §14.3.
  • D. Arthur & S. Vassilvitskii, "k-means++: the advantages of careful seeding," Proceedings of the 18th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), 1027–1035 (2007).
  • P. J. Rousseeuw, "Silhouettes: a graphical aid to the interpretation and validation of cluster analysis," Journal of Computational and Applied Mathematics 20, 53–65 (1987).
  • R. Tibshirani, G. Walther & T. Hastie, "Estimating the number of clusters in a data set via the gap statistic," Journal of the Royal Statistical Society B 63(2), 411–423 (2001).