Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningUnsupervised Learning

k-Means Clustering

P3.C140 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

k-means is the simplest way to find groups in data that has no labels. It is also a clean example of a pattern used all over machine learning: alternate between two easy steps, each of which cannot make a loss worse.

Before this: k-Nearest Neighbors, Norms and distances, NumPy broadcasting and einsum

After this lesson you can

  • Explain what a cluster is, why clustering has no single correct answer, and write the k-means objective (within-cluster sum of squares, also called inertia)
  • Run the assign and update steps by hand, and prove that neither step can increase the objective, so the loop stops
  • Explain why the result depends on the starting centres, and how k-means++ seeding and restarts reduce bad outcomes
  • Choose k with the elbow plot and the silhouette score, say why both can be ambiguous, and name the cases where k-means fails

A shop has thousands of customers and a record of what each bought. It wants a few groups of similar customers, so that each group can get a suitable offer. Nobody has labelled the customers with a “right” group. The data itself has to suggest the groups.

That is clustering: split the examples into groups of similar ones, using no labels. It is the first lesson on unsupervised learning (P0.3). Supervised methods such as k-NN (P3.B1) are trained against labels. Here there is no yy, so the loss has to be computed from the data alone.

k-means is the best-known clustering method. Its idea fits in one sentence: assign each point to the nearest centre, then move each centre to the mean of its group, and repeat. This lesson explains why that works, where it fails, and how to choose the number of groups. All data here is made up, and the lesson says so wherever it matters.

What is a cluster, and why is it ill-posed?

A cluster is a group of points that are more similar to each other than to the rest. That is an idea, not a definition, and different definitions give different answers. Look at the customers: you could split them into 2 groups (big spenders and small), into 5 (by product type), or into 50 (one per shop district). None of these is wrong. A classifier can be scored against known labels; a clustering has no answer sheet.

So a clustering result is always a combination of choices you made:

  • the distance between points (here, ordinary straight-line distance, P1.B4);
  • the scale of every feature, since distance adds up all features;
  • the number of groups kk, which k-means needs before it starts.

Keep this in mind for the whole lesson: k-means finds the best grouping for one precise definition of best, and whether that definition suits your data is up to you.

The objective: sum of squared distances to the centre

k-means describes each cluster by a single point, its centre (also called centroid), μj\boldsymbol{\mu}_j for cluster j=1,…,kj=1,\dots,k. Each point xi\mathbf{x}_i belongs to exactly one cluster; write cic_i for the number of the cluster of point ii. How good is a choice of centres and groups? Add up the squared distance from every point to the centre of its own cluster:

J=∑i=1N∥xi−μci∥2.J=\sum_{i=1}^{N}\lVert\mathbf{x}_i-\boldsymbol{\mu}_{c_i}\rVert^2 .

This is the within-cluster sum of squares (WCSS). Scikit-learn calls it inertia. Small JJ means every point is close to its centre, so the clusters are tight. Dividing by NN gives the average loss of P0.3: each point’s loss is its squared distance to the nearest centre, and the parameters θ\boldsymbol{\theta} are the centres. This lesson uses the sum, which is what the libraries report.

The goal is to choose the groups and the centres to make JJ as small as possible. Trying every possible grouping is hopeless: there are up to kNk^N of them. The next section gives a fast shortcut.

Lloyd’s algorithm: two easy steps, repeated

  1. Start: choose kk starting centres (how to choose them well comes later).
  2. Assign: give every point to its nearest centre.
  3. Update: move every centre to the mean of the points assigned to it.
  4. Repeat steps 2 and 3 until an Assign step changes no point’s group.

This is called Lloyd’s algorithm, and people usually mean it when they say “k-means”.

A hand-worked example

Six made-up points on a line: 1, 2, 4, 8, 10, 111,\ 2,\ 4,\ 8,\ 10,\ 11. Take k=2k=2 and start with the centres 11 and 44.

  • Assign 1. Points 11 and 22 are nearer to centre 11 (distances 00 and 11; to centre 44 they are 33 and 22). Points 4,8,10,114,8,10,11 are nearer to centre 44. The WCSS is the sum of the squared distances to the assigned centre:

    0+1+0+16+36+49=102.0+1+0+16+36+49=102 .

  • Update 1. Centre 1 moves to the mean of {1,2}\{1,2\}, which is 1.51.5. Centre 2 moves to the mean of {4,8,10,11}\{4,8,10,11\}, which is 8.258.25. The first group adds 0.52+0.52=0.50.5^2+0.5^2=0.5. The four squared distances of the second group are 18.062518.0625, 0.06250.0625, 3.06253.0625 and 7.56257.5625, which add to 28.7528.75. The WCSS is 0.5+28.75=29.250.5+28.75=29.25.

  • Assign 2. Point 44 is now nearer to 1.51.5 (distance 2.52.5) than to 8.258.25 (distance 4.254.25). It switches group. Groups: {1,2,4}\{1,2,4\} and {8,10,11}\{8,10,11\}. WCSS with the old centres: 17.437517.4375.

  • Update 2. The centres become 7/3≈2.3337/3\approx2.333 and 29/3≈9.66729/3\approx9.667. WCSS: 9.3339.333.

  • Assign 3. No point changes group, so the algorithm stops.

The WCSS went from 102102 to 29.2529.25, then 17.437517.4375, then 9.3339.333: it fell at every step. The next section shows that this is no accident.

Try it: the six points, by code

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

See it: step through the algorithm

The widget runs the same two steps on 2-D made-up points. Before the first Assign the points are grey and the large marks are the starting centres. Assign colours every point by its nearest centre. Update moves each centre to the mean of its colour, and a dashed trail shows where each centre has been. Marks differ in shape as well as colour. The readout shows the WCSS after every step.

Start from:
iteration: 0 Assign steps
WCSS: not yet

Start 1 of 12 (random points as centres): the large marks are the 3 starting centres and the points are not assigned yet. Press Assign.

  • blue circles, no points assigned yet, centre (4.99, 8.58)
  • vermilion squares, no points assigned yet, centre (1.86, 2.90)
  • green triangles, no points assigned yet, centre (6.14, 5.91)

Made-up points. Small marks are the data points, large marks with a thick outline are the centres, and the dashed path behind each centre is where it has been. Marks differ in shape as well as colour. Rules used: ties go to the centre with the lower number; a centre that loses all its points stays where it is (scikit-learn instead moves it onto a far-away point). In Lite Mode, Play goes to the end at once.

k-means step by step. Choose a data set and k, press Assign and Update in turn (or Play), and watch the centres move and the WCSS fall. Choose how the starting centres are picked (k random points or k-means++), and press New start to try one of 12 fixed starts. Run to the end finishes the loop at once, and in Lite Mode Play does that too. The chart under the plane shows the WCSS after each step; it never goes up.

Things to try (the data and the starts are fixed, so these numbers repeat):

  1. Well-separated blobs, k=3k=3, random start 1. Press Assign, Update and so on: the loop stops after 4 Assign steps, with all three blobs found (25 points each) and a WCSS of 82.24.
  2. Same data, still k=3k=3, random start 6. The loop also stops after 4 Assign steps, but at a WCSS of 362.10, with clusters of 10, 50 and 15 points. Two centres started in the top blob and none in the lower left one, so one centre has to cover two blobs. The algorithm cannot see that this is worse, because no single Assign or Update helps. Switch to k-means++ with the same start number: it takes 2 Assign steps and ends at 82.24.
  3. Unequal sizes, k=3k=3. The lowest WCSS the starts reach is 164.89 (for example random start 2), and some starts end at 229.38 (random start 5). The clusters of the best result have 18, 40 and 16 points although the data were drawn as groups of 50, 10 and 14: k-means follows distances, not the way the data was made.
  4. Two moons, k=2k=2. Whatever the start, the result has a WCSS of 198.84: a straight cut that slices both moons. The method cannot bend around a moon. A short section below returns to this.
  5. Raise kk to 6 on the blobs. The best WCSS you can reach keeps falling, but the extra clusters just cut up groups that were fine.

Why each step cannot make things worse

The two steps each solve a small problem exactly. Think of JJ as a function of two things: the assignment (which cluster each point is in) and the centres.

The assign step is the best assignment for fixed centres. With the centres held fixed, JJ is a sum of one term per point, ∥xi−μci∥2\lVert\mathbf{x}_i-\boldsymbol{\mu}_{c_i}\rVert^2, and each point chooses its cluster separately. The smallest term for point ii comes from choosing the nearest centre. So the Assign step minimizes JJ over all assignments, and the new JJ is less than or equal to the old one.

The update step is the best centre for a fixed group. With the assignment held fixed, JJ splits into one sum per cluster, and each centre only affects its own sum. Take a group SS of points with mean μ\boldsymbol{\mu} (their sum divided by ∣S∣|S|), and let T(m)T(\mathbf{m}) be the group’s total squared distance to a centre placed at the point m\mathbf{m}. Then

T(m)=T(μ)+∣S∣ ∥μ−m∥2.T(\mathbf{m})=T(\boldsymbol{\mu})+|S|\,\lVert\boldsymbol{\mu}-\mathbf{m}\rVert^2 .

(Here T(m)T(\mathbf{m}) is the sum of ∥xi−m∥2\lVert\mathbf{x}_i-\mathbf{m}\rVert^2 over the points of SS. Write xi−m\mathbf{x}_i-\mathbf{m} as the sum of xi−μ\mathbf{x}_i-\boldsymbol{\mu} and μ−m\boldsymbol{\mu}-\mathbf{m} and expand the square. The cross term contains ∑i(xi−μ)\sum_i(\mathbf{x}_i-\boldsymbol{\mu}), which is zero by the definition of the mean.) The last term is never negative and is zero only for m=μ\mathbf{m}=\boldsymbol{\mu}. So the mean is the one best centre for the group, and moving a centre there lowers JJ or leaves it unchanged. That is why the algorithm uses the mean (and not, say, the median).

So the loop stops. JJ never increases, and it does not change at all once an Assign step changes no group. There are only finitely many ways to split NN points into kk groups, and every pass that changes the grouping lowers JJ strictly, so no grouping can be visited twice. The loop therefore reaches a grouping that the Assign step no longer changes, in a finite number of steps. (Exact ties are rare with real-valued data. The argument assumes that a point keeps its group unless another centre is strictly nearer.) In practice the loop usually needs a few to a few dozen iterations.

What the argument does not say: it does not say the final grouping has the smallest possible JJ over all groupings. It only says that no single step can improve it.

Local minima: the start matters

The stopping point is a local minimum: no Assign or Update can improve it, yet a better grouping may exist. Which minimum you reach depends on the starting centres. You saw that in the widget (WCSS 82.24 versus 362.10 on the same blobs). The cell below runs the algorithm on made-up data with four round blobs, and uses the same code for two random starts, then for 200 starts of each kind of seeding.

Try it: Lloyd's algorithm with different starts

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Two random starts, seeded so that the result repeats, reach WCSS 351.6 and 159.7. The worse one merges two real blobs into one cluster (sizes 40, 60, 18, 22: the 60 is the blob of 40 and the blob of 20 at the top right joined together, and the blob of 40 at the lower left has been cut into 18 and 22). Finding the grouping with the lowest possible JJ is a hard problem in general, so no method is guaranteed to find it on every data set. The standard defences are two cheap habits.

Seed with k-means++. The simplest start, k random data points as centres, can put two centres into one blob. k-means++ (Arthur and Vassilvitskii, 2007) spreads the centres out:

  1. Choose the first centre uniformly at random from the data points.
  2. For each point, find D(x)2D(\mathbf{x})^2, the squared distance to the nearest centre chosen so far.
  3. Choose the next centre from the data points with probability proportional to D(x)2D(\mathbf{x})^2: far-away points are the most likely, and points already chosen can never be chosen again, since their D2D^2 is zero.
  4. Repeat steps 2 and 3 until there are kk centres, then run Lloyd’s algorithm as usual.

The authors proved that this seeding alone gives an expected WCSS within a factor of order log⁡k\log k of the best possible. In the cell, the random starts end within 1% of the best result in 66% of the 200 runs and k-means++ in 88%. The worst runs of both are bad (670.0 and 666.6), so a lucky start is not guaranteed.

Restart and keep the best. Run the whole algorithm several times from different starts, and keep the run with the lowest WCSS. In scikit-learn this is the parameter n_init. Restarts cost several times the running time, but the quality of a single run is hard to judge by eye.

Choosing k

kk is a hyperparameter (P3.A4), and there is no labelled validation set to choose it. A tempting idea, the lowest WCSS, fails: the best JJ never rises as kk grows (and in practice it falls), and it is zero at k=Nk=N (every point is its own cluster). Three tools help.

The elbow plot. Plot the best WCSS against kk, and look for the bend where adding a cluster stops paying off. The cell below does this for two made-up data sets: four tight blobs and the same four blobs spread out much more. For the tight blobs, the drop from k=3k=3 to k=4k=4 is large (366.5 to 159.7) and the drop to k=5k=5 is small (138.3), so k=4k=4 is the elbow. For the loose blobs the WCSS falls in a smooth curve, 1400 to 909 to 632 to 520, and no bend is clear. The elbow is a visual rule, and many data sets look like the second one.

The silhouette score. This asks, for each point, whether it is nearer to its own cluster than to the next one. For point ii let

  • a(i)a(i) be its mean distance to the other points of its own cluster;
  • b(i)b(i) be the smallest, over the other clusters, of its mean distance to the points of that cluster.

Then s(i)=b(i)−a(i)max⁡{a(i),b(i)},s(i)=\dfrac{b(i)-a(i)}{\max\{a(i),b(i)\}}, which lies between −1-1 and 11 (and is 00 by convention for a cluster of one point). Close to 11 means the point is well inside its cluster; near 00 means it sits on the border; negative means it is probably in the wrong cluster. The silhouette score is the mean of s(i)s(i) over all points; choose the kk with the highest one.

By hand, on the final grouping of the six points above, {1,2,4}\{1,2,4\} and {8,10,11}\{8,10,11\}: for the point 11, a=(1+3)/2=2a=(1+3)/2=2 and b=(7+9+10)/3=8.667b=(7+9+10)/3=8.667, so s=0.769s=0.769. The six values are 0.769, 0.804, 0.559, 0.559, 0.804 and 0.769, and the mean is 0.7110.711 (scikit-learn gives the same).

Try it: elbow and silhouette for k = 1 to 8

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

For the tight blobs the silhouette peaks at k=4k=4 (0.685), in line with the elbow. For the loose blobs it is almost flat at 0.428, 0.416, 0.419 for k=2,3,4k=2,3,4: the data does not say clearly how many groups it has. Computing the score needs all pairwise distances, so its cost grows with N2N^2.

What the groups are for. The most useful rule is often outside the data. A marketing team that can run four campaigns wants k=4k=4; a colour palette of 16 colours means k=16k=16. Also check that the clusters are stable: if re-running with different starts or on half the data gives very different groups, the structure is weak. In the end, the number is a decision backed by evidence, not a measurement.

Assumptions and failure modes

Minimizing the sum of squared distances to centres implicitly assumes clusters that are round, of similar size and similar spread. Three ways it breaks, all in the cell below.

  • Scale. Distances add up all features, so a feature in large units decides everything (the same issue as in k-NN, P3.A11). In the cell, two groups differ clearly in one feature, and a second, useless feature is measured in thousands. On the raw numbers, k-means recovers the true groups for only 51% of the points (about chance); after standardizing both features (P3.A11, using the mean and standard deviation of the data), it recovers 100%.
  • Shape. The boundary between two clusters is a straight line, the set of points equally close to both centres. Two interleaved half-circles (“moons”) cannot be separated by a straight line, and k-means gets only 76% of the points right on made-up moons. Gaussian mixtures (P3.C2) give each cluster its own elliptical shape, and density-based clustering (P3.C6) follows curved clusters.
  • Size. A blob of 150 points and a smaller one of 15 points four units apart: k-means cuts the big blob (clusters of 142 and 23 points), because that lowers the sum of squares more than keeping the small blob apart.

Also, because every centre is a mean, a few far-away outliers drag centres towards them. Remove obvious outliers first, or use a variant based on medians or real data points (named below).

Try it: scale, shape and size failures

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What a run costs

Each iteration measures the distance from every one of NN points to every one of kk centres in dd dimensions, so it costs about N k dN\,k\,d operations (P1.G4); in NumPy this is the pairwise-distance table of P2.3, with N×kN\times k numbers of memory. For N=106N=10^6, k=100k=100 and d=50d=50 that is about 5×1095\times10^9 steps per iteration, and large data sets use mini-batch k-means, which updates the centres from small random batches.

Go deeper Compressing colours: vector quantization

Take an image with 24 bits per pixel (8 bits each for red, green and blue). Treat every pixel as a point in 3-D colour space and run k-means with k=16k=16. Now store, for every pixel, only the number of its nearest centre (4 bits, since 24=162^4=16), plus a table of the 16 centre colours. The picture needs about 4/24=1/64/24=1/6 of the memory, six times smaller, plus 16 colours of 24 bits each for the table, and the colours are the means of the groups, so the squared colour error is kept small. This is vector quantization: replace each vector by the nearest vector of a small code book. The same idea compresses collections of feature vectors.

Go deeper Variants and neighbours of k-means

k-medoids uses real data points as centres and can use any distance, which makes it more robust to outliers but slower. k-means is also a “hard” form of expectation-maximization for Gaussian mixtures, where every point is shared among the clusters with probabilities (P3.C2).

k-means in scikit-learn

Scikit-learn is not available in the browser, so this block is shown, not run. It was run locally (scikit-learn 1.8.0) on the same four-blob data as the cells above (make_data() with seed 5).

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

km = KMeans(n_clusters=4, random_state=0).fit(X)   # k-means++ seeding, n_init="auto"
print("inertia    :", round(km.inertia_, 1))
print("iterations :", km.n_iter_)
print("sizes      :", np.bincount(km.labels_))
print("centres    :", km.cluster_centers_.round(2).tolist())
print("silhouette :", round(silhouette_score(X, km.labels_), 3))
for k in range(2, 7):
    m = KMeans(n_clusters=k, random_state=0).fit(X)
    print(k, round(m.inertia_, 1), round(silhouette_score(X, m.labels_), 3))
inertia    : 159.7
iterations : 3
sizes      : [40 39 40 21]
centres    : [[6.99, 2.93], [4.46, 7.63], [1.98, 1.75], [8.31, 8.2]]
silhouette : 0.685
2 896.0 0.516
3 366.5 0.634
4 159.7 0.685
5 137.7 0.607
6 122.0 0.488

The inertia (159.7) and silhouette (0.685) match the NumPy cells. Things to know about the defaults:

  • n_init. Since scikit-learn 1.4 the default is "auto": one run with the default "k-means++" seeding and ten runs with "random". Older tutorials may assume 10.
  • Scikit-learn’s k-means++ is a greedy version: for each new centre it tries a few candidates and keeps the best. That is why its inertia for k=5k=5 and k=6k=6 (137.7 and 122.0) is slightly lower than the cell’s table (138.3 and 123.4).
  • Empty clusters. If a centre ends up with no points, the mean of nothing does not exist, so an implementation needs a rule. The widget leaves the centre where it is. Scikit-learn moves it onto a point far from its own centre. A frequent empty cluster can mean that kk is too large.

Depth: three ways to see it

Intuition

Imagine opening kk post offices in a town. Every house goes to its nearest office (Assign). Then each office moves to the middle of the houses it serves, to cut the total walking (Update). Houses may now be nearer to a different office, so repeat. Each move cannot increase the total walking distance squared, and eventually nothing moves. The analogy breaks when the real areas are not round or the walking is not straight-line: k-means draws straight borders and treats every direction the same.

Math

Objective:

J(c,μ)=∑i=1N∥xi−μci∥2.J(c,\boldsymbol{\mu})=\sum_{i=1}^{N}\lVert\mathbf{x}_i-\boldsymbol{\mu}_{c_i}\rVert^2 .

Assign:

ci←arg⁡min⁡j∥xi−μj∥2.c_i\leftarrow\arg\min_j\lVert\mathbf{x}_i-\boldsymbol{\mu}_j\rVert^2 .

Update, with Sj={i:ci=j}S_j=\{i:c_i=j\}:

μj←1∣Sj∣∑i∈Sjxi.\boldsymbol{\mu}_j\leftarrow\frac{1}{|S_j|}\sum_{i\in S_j}\mathbf{x}_i .

Neither step increases JJ, so the sequence of values J0≥J1≥⋯≥0J_0\ge J_1\ge\dots\ge0 converges, and with finitely many assignments the loop ends. Cost: O(Nkd)O(Nkd) per iteration. Silhouette: s(i)=b(i)−a(i)max⁡{a(i),b(i)}s(i)=\frac{b(i)-a(i)}{\max\{a(i),b(i)\}}.

Code

import numpy as np

def kmeans_step(X, C):
    d2 = ((X[:, None, :] - C[None, :, :]) ** 2).sum(axis=2)   # (N, k), as in P2.3
    labels = d2.argmin(axis=1)                                 # assign
    C_new = np.array([X[labels == j].mean(axis=0) if np.any(labels == j) else C[j]
                      for j in range(len(C))])                 # update
    return labels, C_new

Repeat kmeans_step until labels stops changing. In scikit-learn, use KMeans(n_clusters=k).fit(X).

Common mistakes

Quiz

Check your understanding

  1. Why can an Update step never increase the WCSS?

  2. Two runs of k-means on the same data with different random starting centres end with different WCSS values. What is the best explanation?

  3. Two features describe each customer: age in years (about 20 to 70) and yearly spending in dollars (about 100 to 50,000). You run k-means on the raw numbers. What happens?

  4. You plot the best WCSS against k for k = 1 to 10 and the curve falls smoothly with no bend. What should you conclude?

  5. k-means with k = 2 is run on two interleaved half-circles (moons). What is the main reason it does not separate them?

Exercises

  1. Points 0, 2, 6, 8, 90,\ 2,\ 6,\ 8,\ 9 on a line, k=2k=2, starting centres 00 and 99. Run the algorithm and give the WCSS after each step.
    Show answerAssign 1: 0,20,2 go to centre 00, and 6,8,96,8,9 to centre 99 (the point 66 is 33 from 99 and 66 from 00). The squared distances are 0,4,9,1,00, 4, 9, 1, 0, so the WCSS is 1414. Update: centres 11 and 7.6677.667. The two groups add 22 and 4.6674.667, so the WCSS is 6.6676.667. Assign 2 changes nothing, so the algorithm stops with WCSS 6.6676.667.
  2. For the grouping {0,2}\{0,2\} and {6,8,9}\{6,8,9\} of exercise 1, compute the silhouette value of the point 22.
    Show answera=2a=2, the distance to the point 00. b=(4+6+7)/3=5.667b=(4+6+7)/3=5.667, the mean distance to 6,8,96,8,9. So s=(5.667−2)/5.667=0.647s=(5.667-2)/5.667=0.647.
  3. Points 0, 1, 100,\ 1,\ 10 on a line. k-means++ has chosen the point 00 as its first centre. What is the probability of each point being the second centre?
    Show answerThe squared distances are 0,1,1000,1,100, which add up to 101101. The probabilities are 00, 1/101≈0.00991/101\approx0.0099 and 100/101≈0.9901100/101\approx0.9901. The point 00 cannot be chosen again.
  4. Roughly how many multiply-and-add steps does one Assign step cost for N=106N=10^6 points, k=100k=100 centres and d=50d=50 features?
    Show answerAbout N k dN\,k\,d, which is 5×1095\times10^9.
  5. What is the WCSS at k=Nk=N, and why is it useless for choosing kk?
    Show answerZero: every point is its own cluster and its own centre, so every distance is zero. The WCSS never rises as kk grows, so it always favours the largest kk, and it says nothing about whether the groups are meaningful.

Next: P3.C2 softens k-means: Gaussian mixtures give every point a probability of belonging to each cluster, and fit with expectation-maximization. P3.C3 turns to principal component analysis, which reduces the number of features; P3.C6 covers density-based clustering for shapes k-means cannot follow. P3.A11 returns to scaling, which every distance-based method needs.

Key takeaways

  • Clustering groups unlabelled points. There is no single right answer: the groups depend on the distance, the scale of the features and the number of clusters k.
  • k-means chooses k centres to make the sum of squared distances from each point to its nearest centre (WCSS, inertia) small. Lloyd's algorithm alternates two steps: assign every point to its nearest centre, then move every centre to the mean of its points.
  • Each step can only lower or keep the WCSS: the assign step picks the best groups for the current centres, and the mean is the best centre for a given group. There are finitely many ways to group the points, so the loop stops, but only at a local minimum.
  • The result depends on the start. k-means++ spreads the starting centres out by choosing far-away points with higher probability, and running several starts and keeping the lowest WCSS is standard practice.
  • The best WCSS never rises as k grows, so choose k with the elbow, the silhouette score and what the groups are for. k-means works best on roughly round, similar-sized clusters of scaled features, and fails on shapes such as two moons.
Found a mistake? Tell us