Machine Learning Intermediate 12 minutes

K-Means Clustering

Splitting data into K clusters by repeating the steps of assignment and updating the centres.

Your progress in the track0%

The algorithm

  1. Choose \(K\) initial centres.
  2. Assign each point to the nearest centre.
  3. Update each centre to be the mean of its points.
  4. Repeat steps 2 and 3 until the centres stabilise.

The objective:

$$\min_{C_1,\dots,C_K} \sum_{k=1}^{K} \sum_{\mathbf{x} \in C_k} \|\mathbf{x} – \boldsymbol{\mu}_k\|^2$$

Example

from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, _ = make_blobs(n_samples=500, centers=4, random_state=0)
X = StandardScaler().fit_transform(X)
for k in range(2, 8):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    print(k, round(km.inertia_, 1), round(silhouette_score(X, km.labels_), 3))

Choosing K

  • The elbow method: plot inertia against K and look for the point after which the decrease slows down.
  • The silhouette coefficient: choose the K that gives a higher average.
  • Domain knowledge: the number of segments that is useful in practice.

Limitations

  • It assumes convex clusters of similar size; it fails with crescent-shaped or overlapping shapes (try DBSCAN or a Gaussian mixture).
  • Sensitive to feature scale and outliers.
  • K must be set in advance.

Lesson terms

Inertia
The sum of squared distances between the points and the centres of their clusters, which K-Means minimizes.
Centroid
The average of a cluster's points, which represents the cluster in the K-Means algorithm.
Silhouette coefficient
A measure between -1 and 1 that compares how close a point is to its own cluster with how close it is to the nearest other cluster.

Abstract

The K-Means algorithm splits data into K clusters by minimizing the sum of squared distances between the points and the centres of their clusters (inertia). Two steps repeat: assigning each point to the nearest centre, then updating each centre to be the mean of its points. The result depends on the initialization (k-means++ improves it) and on the choice of K, and it assumes roughly spherical clusters of similar size.

Review questions

  1. What are the two repeated steps in K-Means?

    Assigning each point to the nearest centre, then recomputing each centre as the mean of its points.

  2. Why don't we choose K by minimizing inertia alone?

    Because inertia always decreases as K increases, reaching zero when K equals the number of points.

Sources and references

  1. scikit-learn — Clustering: K-means
  2. Lloyd (1982) Least squares quantization in PCM — IEEE Trans. Information Theory
  3. Arthur & Vassilvitskii (2007) k-means++: The advantages of careful seeding — SODA

Complete the lesson