K-Means Clustering
Splitting data into K clusters by repeating the steps of assignment and updating the centres.
The algorithm
- Choose \(K\) initial centres.
- Assign each point to the nearest centre.
- Update each centre to be the mean of its points.
- 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
-
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.
-
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
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate