Notes
All notes

Deriving k-Means (ML #11)

You have 30,000 unlabeled customer records and a mandate to “find segments”. You run k-means, get \(k = 8\), and the eight groups look like eight different sizes of the same thing: seven tight blobs and one enormous smear containing everyone with a zero. The algorithm worked exactly as specified. The specification was wrong.

k-means is the most-used unsupervised algorithm in industry and one of the few whose internals fit in twenty lines, so it is worth deriving exactly — because the derivation tells you the precise conditions under which it will fail, and those conditions describe your data, not the algorithm.

This chapter derives the objective, proves the key identity that reframes clustering as variance decomposition, derives Lloyd’s algorithm as coordinate descent with a convergence guarantee, and derives why the initialization is the hard part.

The objective, and the two terms it hides

Before the algebra, name what the two summands of the objective mean in plain terms:

term what it penalizes reduced by
\(\sum_i \lVert \tilde{x}_i - \mu_{c_i}\rVert^2\) (within) points disagreeing with their own centroid more, finer clusters (\(k \to n\) gives 0)
\(n_c\lVert \mu_c \rVert^2\) (between) centroids sitting on top of each other fewer, better-placed clusters

k-means is a negotiation between these two forces, and every hyperparameter is a setting on that negotiation. Small \(k\) lets the between term win (underfitting); large \(k\) lets the within term win (overfitting). There is no third option, because the identity proves the total variance is conserved between them.

The objective

Cluster \(n\) points into \(k\) groups with centroids \(\mu_1, \dots, \mu_k\). Each point \(x_i\) is assigned to some cluster \(c_i\). Minimize the total within-cluster scatter:

\[ \text{WCSS} = \sum_{c=1}^{k} \sum_{i \in c} \lVert x_i - \mu_c \rVert_2^2 \]

Everything about k-means — its speed, its guarantees, its failures — follows from the algebraic structure of this expression.

The identity that reframes the problem

Expand each squared norm and use the bias–variance-style decomposition:

\[ \lVert x_i - \mu_c \rVert^2 = \lVert x_i \rVert^2 - 2x_i^\top \mu_c + \lVert \mu_c \rVert^2 \]

Sum over all points and all clusters, then use the definition of the centroid, \(\mu_c = \frac{1}{n_c}\sum_{i\in c} x_i\). Two terms simplify:

Collecting the \(n_c\lVert\mu_c\rVert^2\) terms:

\[ \boxed{\; \text{WCSS} \;=\; \sum_{i=1}^{n}\lVert x_i\rVert^2 \;-\; \sum_{c=1}^{k} n_c \lVert \mu_c \rVert^2 \;} \]

This is the whole idea. The first term is a constant — it depends only on the data, not on the clustering. So minimizing WCSS is identical to maximizing \(\sum_c n_c\lVert\mu_c\rVert^2\), the between-cluster scatter.

k-means is therefore a variance-decomposition algorithm: it partitions the data to squeeze as much total squared spread as possible into the cluster means. Concretely, it is trying to make centroids far apart from the origin, weighted by cluster size. This immediately explains two behaviours that otherwise look like quirks:

  1. Clusters get pushed toward the tails, where there is more absolute spread to capture.
  2. Outliers get their own cluster. An extreme point contributes a huge \(\lVert x_i\rVert^2\); giving it a singleton cluster makes that term’s own centroid “carry” its spread, which reduces WCSS more than burying it in a dense cluster would. This is not a bug — it follows directly from the identity.

Total variance also decomposes as

\[ \sum_i \lVert x_i - \bar{x} \rVert^2 = \underbrace{\text{WCSS}}_{\text{within}} + \underbrace{\sum_c n_c\lVert \mu_c - \bar{x}\rVert^2}_{\text{between}} \]

so minimizing within-cluster scatter is exactly maximizing the between-cluster fraction of total variance — the quantity silhouette score (a standard validation metric) is built on.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.4cm, minimum height=0.66cm, align=center, font=\rmfamily\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (tot) at (0,3.1) {total scatter\\$\sum_i\lVert x_i-\bar{x}\rVert^2$};
  \node[b, fill=blue!10] (w) at (-2.7,0.9) {within\\WCSS\\minimize this};
  \node[b, fill=orange!16] (btw) at (2.7,0.9) {between\\$\sum_c n_c\lVert\mu_c-\bar{x}\rVert^2$\\maximize this};
  \draw[a] (tot) -- (w); \draw[a] (tot) -- (btw);
  \node[font=\rmfamily\scriptsize, text=black!65, align=center] at (0,-0.9) {the two add to the total, so pushing\\one down forces the other up: no free lunch};
\end{tikzpicture}

Deriving Lloyd’s algorithm

We have a joint objective over both assignments \(c_i\) and centroids \(\mu_c\). Alternate between optimizing each, holding the other fixed.

Step 1 (assignment), holding \(\mu\) fixed. The objective separates over points — each \(i\) contributes \(\lVert x_i - \mu_{c_i}\rVert^2\) independently. So the minimum for point \(i\) alone is the nearest centroid:

\[ c_i = \arg\min_{c} \lVert x_i - \mu_c \rVert_2^2 \]

Step 2 (centroid update), holding assignments fixed. Now group by cluster and differentiate. Minimize \(\sum_{i \in c}\lVert x_i - \mu_c\rVert^2 = \sum_{i\in c}\lVert x_i\rVert^2 - 2\mu_c^\top\sum_{i\in c}x_i + n_c\lVert\mu_c\rVert^2\). Set the gradient to zero:

\[ \frac{\partial}{\partial\mu_c} = -2\sum_{i\in c}x_i + 2n_c\mu_c = 0 \;\Longrightarrow\; \mu_c = \frac{1}{n_c}\sum_{i \in c} x_i \]

So the optimal centroid is the arithmetic mean of its members — the same “fit a constant by least squares” result as Chapter 1’s intercept-only model.

Alternating these two steps is k-means (Lloyd’s algorithm, 1957). Two consequences, one good and one routinely overstated:

import numpy as np

def kmeans(X, k, iters=100, seed=0):
    rng = np.random.default_rng(seed)
    centroids = X[rng.choice(len(X), k, replace=False)]

    for _ in range(iters):
        # Step 1: assign each point to the nearest centroid
        d2 = ((X[:, None, :] - centroids[None, :, :]) ** 2).sum(-1)
        labels = d2.argmin(axis=1)

        # Step 2: move each centroid to the mean of its members
        new = centroids.copy()
        for c in range(k):
            members = X[labels == c]
            if len(members):                      # guard: empty cluster
                new[c] = members.mean(axis=0)
            else:                                # reseed onto the worst-fit point
                new[c] = X[d2[np.arange(len(X)), labels].argmax()]

        if np.allclose(new, centroids):         # convergence: assignment stable
            break
        centroids = new
    return centroids, labels

The good: WCSS decreases monotonically. Each step is an exact coordinate-wise minimization, so neither can increase the objective — it is non-increasing and bounded below, so it converges. The weak part: it converges to a local optimum, not a global one. Monotonic decrease guarantees a fixed point, not the best fixed point. Everything about k-means’s practical quality is therefore a story about initialization, because the objective’s landscape has many basins.

Initialization is the hard part

Random initialization frequently lands in a poor basin. k-means++ fixes this with a specific rule, and its logic is worth deriving. Instead of choosing all \(k\) centers uniformly, choose them one at a time, each time with probability proportional to its squared distance from the nearest center chosen so far:

\[ p(x_i) = \frac{D(x_i)^2}{\sum_{x_j} D(x_j)^2}, \qquad D(x_i) = \min_{c \in \text{chosen}} \lVert x_i - \mu_c \rVert \]

Each draw places a new centroid preferentially in the region of space that is least covered so far. The \(D^2\) weighting is not arbitrary — it’s the standard analysis showing this yields a set of centers with \(O(\log k)\) expected approximation to the optimum, versus \(O(k)\) for random selection. The intuition: uniform random centers can all land in one dense cluster, leaving an entire region with no representation; \(D^2\)-weighted sampling is compelled to cover the spread.

The consequence in practice is a large reduction in “bad local optima” and therefore in the number of restarts you need. \(D^2\)-weighting matters because distance already grows with spread; squaring further upweights remote points.

def kmeanspp(X, k, seed=0):
    rng = np.random.default_rng(seed)
    centers = [X[rng.integers(len(X))]]         # first: uniform at random
    while len(centers) < k:
        D = np.min(((X[:, None, :] - np.array(centers)[None]) ** 2).sum(-1), axis=1)
        p = D / D.sum()                          # D^2 weighting
        centers.append(X[rng.choice(len(X), p=p)])
    return np.array(centers)

Restarting k-means from several initializations and keeping the lowest WCSS remains good practice even with k-means++, because the guarantee is \(O(\log k)\) expected — variance still matters, and WCSS is a legitimate model-selection criterion you can compute directly.

Choosing k

There is no closed-form criterion. Three standard approaches and their honest trade-offs:

method idea limitation
elbow plot WCSS vs \(k\), bend the curve subjective; WCSS always decreases
silhouette compare within-cluster to nearest-other-cluster separation penalizes elongated clusters
gap statistic compare WCSS to a uniform null reference needs Monte Carlo null; assumption-heavy

Note from the identity above that WCSS is monotonically decreasing in \(k\) — with \(k = n\) it hits zero, trivially “perfect”. So any criterion must penalize \(k\) explicitly, and the elbow is exactly the eyeball version of such a penalty. In practice: prefer a domain-motivated \(k\), and if you must choose, silhouette over elbow.

The failure modes, all structural

Non-spherical clusters. k-means minimizes Euclidean distance to a centroid, so it implicitly assumes clusters are roughly spherical and similar in spread. It cannot find a ring, a crescent, or an elongated manifold — those get chopped into pieces. If your data has such structure, k-means is the wrong tool by construction: use spectral clustering, or a density method (DBSCAN) whose assumption is connectivity rather than sphericality.

Unequal densities and sizes. The centroid of a dense cluster barely moves when a sparse cluster joins it, because WCSS is a sum over points, not a mean — a 1,000-point cluster dominates a 5-point cluster by a factor of 200. k-means will therefore merge sparse small clusters and carve outliers off. This is the smear-versus-tight-blobs pattern from the opening, and it’s a property of the objective, not of the initialization.

Feature scale (again). Since distance is summed over features, unscaled columns are catastrophic here for the same reason they were for k-NN (Chapter 5). Standardize. Unlike trees, k-means needs it.

Empty clusters. If every point leaves cluster \(c\) during an assignment step, its centroid is undefined. Options: reseed it to the point currently worst served (farthest from its centroid), keep it fixed, or drop \(k\) by one. The code above reseeds.

Connection: k-means as hard-assignment EM

Worth stating because it unifies the course. The two-step alternation has an obvious parallel to expectation–maximization:

E-step M-step
k-means assign to nearest centroid (hard 0/1) recompute means
EM for GMM compute posterior responsibilities \(\gamma_{ic}\) (soft, in \([0,1]\)) recompute means, covariances, weights

k-means is EM for a Gaussian mixture model in the limit where responsibilities are hard assignments and covariances are isotropic and shared. The consequence is immediate: k-means’s weaknesses (spherical assumption, dead centroids) are exactly the places where dropping EM’s extra flexibility — soft assignments and per-cluster covariance — costs you. Soft-assignment GMM fixes the first; per-cluster covariance fixes the second; k-means is the cheap special case that is exactly right when the assumptions hold.

Pitfalls

QQuestionSelf-check

Derive \(\text{WCSS} = \sum_i\lVert x_i\rVert^2 - \sum_c n_c\lVert\mu_c\rVert^2\) and explain why this makes k-means a maximum-between-cluster-scatter problem. Show that the centroid update is the exact minimizer for a fixed assignment. Why does Lloyd’s algorithm’s monotone decrease prove convergence but not optimality, and how does k-means++ address this? Your 30k-customer clustering yields seven tight blobs and one huge smear — use the identity to explain both features.

ASolution

Expanding \(\lVert x_i-\mu_c\rVert^2 = \lVert x_i\rVert^2 - 2x_i^\top\mu_c + \lVert\mu_c\rVert^2\) and summing, the cross term uses \(\sum_{i\in c}x_i = n_c\mu_c\) so that \(\sum_{i\in c}x_i^\top\mu_c = n_c\lVert\mu_c\rVert^2\), which cancels the standalone \(\sum_c \lVert\mu_c\rVert^2\) term up to the weighting \(n_c\); the first sum is data-only, so minimizing WCSS equals maximizing \(\sum_c n_c\lVert\mu_c\rVert^2\). Since total scatter splits into within + between, this is equivalently maximizing the between fraction — silhouette’s basis. For the update: with assignments fixed the objective is \(\sum_{i\in c}(\lVert x_i\rVert^2 - 2\mu_c^\top x_i + \lVert\mu_c\rVert^2)\); setting \(\partial/\partial\mu_c = -2\sum_{i\in c}x_i + 2n_c\mu_c = 0\) gives \(\mu_c = \frac{1}{n_c}\sum_{i\in c}x_i\), the arithmetic mean. Monotone decrease follows because each step is exact coordinate-wise minimization and the objective is bounded below by 0 — that guarantees a fixed point, but a non-convex objective in \(k\)-dimensional partition space has many fixed points, so the guarantee is convergence to a local optimum only. k-means++ attacks this by sampling centers with probability proportional to \(D(x)^2\) to the nearest chosen center, which forces early centers into under-covered regions and gives \(O(\log k)\) expected approximation versus \(O(k)\) for uniform. For the seven-blobs-plus-smear result: a tight cluster yields large \(\lVert\mu_c\rVert^2\) from dense interior points, so carving it off wins a lot of between-cluster scatter; the smear is one connected diffuse region that no centroid can capture without leaving a large residual, so it stays as a single catch-all, and because WCSS is a sum over points, tiny sparse clusters are absorbed into it while an extreme outlier benefits more from a singleton cluster (where its own spread is captured by \(\sum_c n_c\lVert\mu_c\rVert^2\)) than from being averaged into a dense group.

Next: Deriving PCA (ML #12) — starting from reconstruction error and ending up with eigenvectors, by way of a Lagrange multiplier.