Sub topic 11
Mini-batch k-means and other clustering methods
This chapter assumes you can run KMeans in scikit-learn, know that k-means minimizes inertia, and understand its limitations from the previous chapter. Here you will see how to speed k-means up on large data, and which algorithms to try when its assumptions fail.
Mini-batch k-means
Standard k-means computes distances from every point to every centroid on each iteration. With millions of rows, that cost adds up. Mini-batch k-means changes the update step. Each iteration draws a small random batch of points, assigns only those points to centroids, and moves each centroid a small step toward the batch points assigned to it. The step size shrinks as a centroid collects more points, so centroids settle over time.
The result is much faster and uses less memory. The price is a slightly higher inertia, because the updates are noisy estimates of the full-data means. In practice the clusters are often close to those of full k-means.
import time
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans, MiniBatchKMeans
X, _ = make_blobs(n_samples=200_000, centers=8, cluster_std=1.5, random_state=0)
for name, model in [
("KMeans", KMeans(n_clusters=8, n_init=3, random_state=0)),
("MiniBatchKMeans", MiniBatchKMeans(n_clusters=8, n_init=3,
batch_size=2048, random_state=0)),
]:
start = time.perf_counter()
model.fit(X)
elapsed = time.perf_counter() - start
print(f"{name:16s} time={elapsed:.2f}s inertia={model.inertia_:.0f}")Timings depend on your machine. Expect MiniBatchKMeans to be faster and to report an inertia a little above KMeans.
MiniBatchKMeans also offers partial_fit, which lets you feed data in chunks when the full matrix does not fit in memory.
When to leave k-means behind
Mini-batch k-means is still k-means. It keeps the same assumptions: roughly round clusters of similar size, a fixed k, and Euclidean distance. If those fail, a different algorithm fits better than any tuning of k-means.
DBSCAN
DBSCAN groups points that sit in dense regions and marks isolated points as noise. You do not choose k. You set eps, the neighborhood radius, and min_samples, the number of neighbors needed to count a point as dense. It finds clusters of arbitrary shape, such as two interleaved crescents, which k-means splits incorrectly. Its weakness is data whose clusters have very different densities, since one eps cannot suit all of them.
Gaussian mixture models
A Gaussian mixture model (GMM) describes the data as a blend of k Gaussian distributions. Each point gets a probability of belonging to each component, so assignments are soft. Components can be elongated and tilted because each has its own covariance. K-means is the special case where all components are round and equal in size.
Hierarchical clustering
Agglomerative clustering starts with each point alone and repeatedly merges the closest pair of clusters. The merge history forms a tree that you cut at the level you want. It gives a view at every scale, but its cost grows quickly with the number of points, so it suits small to medium datasets.
Comparing them on non-spherical data
This example uses two crescent shapes, where k-means fails and DBSCAN succeeds. The adjusted Rand index (ARI) compares the clusters to the true grouping. A score of 1.0 is a perfect match, and a score near 0 is no better than chance.
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans, DBSCAN
from sklearn.mixture import GaussianMixture
from sklearn.metrics import adjusted_rand_score
X, y = make_moons(n_samples=500, noise=0.05, random_state=0)
results = {
"KMeans": KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X),
"GMM": GaussianMixture(n_components=2, random_state=0).fit_predict(X),
"DBSCAN": DBSCAN(eps=0.2, min_samples=5).fit_predict(X),
}
for name, labels in results.items():
print(f"{name:8s} ARI={adjusted_rand_score(y, labels):.2f}")DBSCAN should score near 1.0 here, while k-means and the mixture model score much lower. Remember that ARI needs true labels, which you rarely have in real clustering work. Here they exist only because the data is synthetic.
Choosing a method
| Situation | Try |
|---|---|
| Large data, round clusters | Mini-batch k-means |
| Unknown number of clusters, odd shapes, noise | DBSCAN |
| Overlapping or elongated clusters, need probabilities | Gaussian mixture |
| Small data, want a nested structure | Hierarchical clustering |
Common errors
- Skipping feature scaling. DBSCAN's
epsis a distance, so unscaled features distort it just as they distort k-means. - Using one
epsfor everything. Plot sorted nearest-neighbor distances to pick a reasonable value, and expect to tune it. - Treating a low
MiniBatchKMeansinertia gap as proof of equal quality. Check the clusters themselves, not only the score. - Forgetting that DBSCAN labels noise as
-1. Do not count it as a cluster.
Exercise
You have 5 million rows of customer features, scaled, with no obvious cluster shape, and KMeans takes too long. Which change do you try first, and what cost should you expect?
Show answer
Try MiniBatchKMeans. It runs faster and uses less memory, and the cost is a slightly higher inertia because its centroid updates come from small random batches. Compare the clusters to a full KMeans fit on a sample to check that the loss is acceptable.
Exercise
DBSCAN returns labels [0, 0, 1, -1, 1, -1]. How many clusters did it find, and what does -1 mean?
Show answer
It found two clusters, labeled 0 and 1. The label -1 marks noise, meaning points that were not in any dense region.