Sub topic 11
Mini-batch k-means and other clustering methods
This chapter closes the tutorial. You have a working model of k-means: Lloyd's algorithm, inertia, k-means++ seeding, scaling, and choosing k. Here you will learn how to run k-means on data too large for repeated full passes, and how to decide when to use a different algorithm.
It assumes you can read scikit-learn code, know that each Lloyd iteration costs a distance computation between every point and every centroid, and remember the limitations from the previous chapter: spherical clusters, similar cluster sizes, sensitivity to outliers, and dependence on scale.
Why full k-means gets expensive
One iteration of Lloyd's algorithm computes the distance from all n points to all k centroids in d dimensions. That costs roughly O(n·k·d). Training repeats this for many iterations, and n_init restarts multiply the cost again.
For tens of thousands of rows this is trivial. For tens of millions of rows, or for data that arrives as a stream and does not fit in memory, repeated full passes become the bottleneck. Two ideas address this:
- Use a small random sample of the data on each update.
- Update centroids incrementally so you never need all the data at once.
Mini-batch k-means does both.
Mini-batch k-means
Mini-batch k-means (Sculley, 2010) replaces the full pass with a loop over small random batches. Each step does the following:
- Draw a random batch of
bpoints (for example 1,024). - Assign each point in the batch to its nearest current centroid.
- Move each affected centroid a little toward the batch points assigned to it.
The move in step 3 is a running average. Each centroid keeps a count of how many points it has absorbed so far. When a new point x arrives, the centroid c becomes:
c ← c + (x − c) / count
Early points move a centroid a lot. Later points move it less. With enough points, c approximates the mean of everything assigned to it, which is the same quantity Lloyd's algorithm computes exactly.
Each step costs O(b·k·d) instead of O(n·k·d). The cost per step does not depend on n.
What you give up
Mini-batch k-means is an approximation. Each update uses a noisy sample of the data, so:
- Final inertia is usually a little higher than full k-means. Differences of a few percent are typical, but the gap depends on the data.
- The result varies more between runs, so a fixed
random_statematters for reproducibility. - Stopping is heuristic. scikit-learn stops when a smoothed estimate of batch inertia has not improved for
max_no_improvementconsecutive batches, or whenmax_iterpasses over the data are done.
Comparing the two on one dataset
The script below fits both estimators on 200,000 points and reports time and inertia. Timings depend on your machine, so the point is the relative difference and the inertia gap.
import time
from sklearn.cluster import KMeans, MiniBatchKMeans
from sklearn.datasets import make_blobs
X, _ = make_blobs(
n_samples=200_000, n_features=10, centers=8, cluster_std=2.0, random_state=0
)
models = {
"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
),
}
for name, model in models.items():
start = time.perf_counter()
model.fit(X)
elapsed = time.perf_counter() - start
print(f"{name:16s} time={elapsed:6.2f}s inertia={model.inertia_:,.0f}")On well-separated blobs like these, the two inertias are usually very close and the mini-batch version is faster. On messier data the gap in inertia can be larger. Always compare on your own data before switching.
Key parameters
| Parameter | Default | Effect |
|---|---|---|
| `batch_size` | 1024 | Larger batches give less noise but cost more per step. |
| `max_no_improvement` | 10 | Number of consecutive batches without improvement before early stopping. |
| `n_init` | `"auto"` | Number of seedings tried. The best seeding is chosen using inertia on a subset of data. |
| `reassignment_ratio` | 0.01 | Controls how readily low-count centroids are moved to random points. Higher values reassign more. |
| `max_iter` | 100 | Maximum number of passes over the full dataset. |
The reassignment_ratio setting exists because a centroid that attracts few points can get stuck near nothing useful. Mini-batch k-means periodically relocates such centroids, which reduces the empty-cluster problem you saw in the NumPy implementation.
Streaming with `partial_fit`
MiniBatchKMeans supports partial_fit, which performs one update from the data you give it. This lets you cluster data from a file reader, a database cursor, or a message queue without loading everything.
import numpy as np
from sklearn.cluster import MiniBatchKMeans
rng = np.random.default_rng(0)
true_centers = np.array([[0.0, 0.0], [8.0, 8.0], [-8.0, 8.0]])
def stream_chunks(n_chunks, chunk_size):
"""Yield chunks of 2-D points drawn around three centers."""
for _ in range(n_chunks):
idx = rng.integers(0, len(true_centers), size=chunk_size)
yield true_centers[idx] + rng.normal(scale=1.0, size=(chunk_size, 2))
mbk = MiniBatchKMeans(n_clusters=3, n_init=3, random_state=0)
for chunk in stream_chunks(n_chunks=200, chunk_size=500):
mbk.partial_fit(chunk)
print(np.round(mbk.cluster_centers_, 1))Three points matter when streaming:
- The first chunk must contain at least
n_clusterssamples, because the initial centroids are chosen from it. If early data is unrepresentative, the seeding will be too. - The estimator cannot rescan earlier chunks. If the data distribution drifts, old points keep influencing centroids through the counts.
- Scaling must be decided up front. A
StandardScalerfitted on one chunk may not suit later chunks. UseStandardScaler.partial_fitor fixed, known scaling constants.
Other variants of k-means
Several modifications keep the centroid idea but change one part of the algorithm.
- Bisecting k-means starts with all points in one cluster, then repeatedly splits one cluster in two using 2-means. It produces a hierarchy of clusters, can be faster for large
k, and tends to give more evenly sized clusters. scikit-learn providesBisectingKMeans(version 1.1 and later). - k-medoids requires each center to be an actual data point, and it can use any distance. Because it minimizes a sum of distances instead of squared distances, one outlier pulls the center much less. It is not part of core scikit-learn. The
scikit-learn-extrapackage providesKMedoids. - Spherical k-means is the usual name for k-means on length-normalized vectors. Euclidean distance between unit vectors is a monotone function of cosine similarity, so this approximates clustering by direction. It is common for text embeddings. In scikit-learn you can do this by normalizing rows with
sklearn.preprocessing.normalizebefore fittingKMeans. - Kernel k-means runs k-means in an implicit feature space, which allows non-linear cluster boundaries. It needs an
n × nkernel matrix, so it does not scale to large data. It is closely related to spectral clustering, covered below.
Alternatives built on different assumptions
K-means assumes each cluster is a compact blob around a mean. When that is false, a different model of what a "cluster" is usually works better.
Gaussian mixture models
A Gaussian mixture model (GMM) describes the data as a combination of k Gaussian distributions, each with its own mean and covariance. It is fitted with the expectation-maximization (EM) algorithm. EM has the same two-step shape as Lloyd's algorithm, but the assignment step is soft: each point gets a probability of belonging to each component instead of a single label.
K-means is the special case of a GMM where every component is spherical with the same variance and assignments are hard. With covariance_type="full", a GMM can model elongated, tilted ellipses, which k-means cannot. You also get probabilities from predict_proba, and information criteria (bic, aic) to help choose the number of components.
The cost is more parameters to estimate. Full covariances need O(d²) values per component, so GMMs need more data and are more sensitive to initialization in high dimensions. They also remain unsuited to non-convex shapes.
DBSCAN and HDBSCAN
DBSCAN defines clusters as dense regions separated by sparse ones. A point is a core point if at least min_samples points lie within distance eps. Clusters grow by connecting core points that are near each other. Points that are not reachable from any core point are labeled noise (-1).
Differences from k-means:
- You do not choose the number of clusters. You choose
epsandmin_samples. - Clusters can have any shape, including crescents and rings.
- Outliers are labeled as noise instead of being forced into a cluster.
- A single
epsassumes similar density everywhere. If clusters differ in density, DBSCAN struggles. - Distances lose meaning in very high dimensions, which affects
epsin any method based on distance.
HDBSCAN (sklearn.cluster.HDBSCAN, version 1.3 and later) removes the need for a global eps by building a hierarchy over many density levels and selecting stable clusters. It copes with clusters of different densities and is often the better first choice among density-based methods.
Agglomerative (hierarchical) clustering
Agglomerative clustering starts with every point as its own cluster and repeatedly merges the closest pair. The linkage setting defines "closest". With linkage="ward", each merge is the one that increases within-cluster variance the least, so the results resemble k-means. With "single" linkage, clusters can chain along elongated shapes. The output is a tree (dendrogram) that you can cut at any level. The standard algorithm needs memory quadratic in n, which limits it to moderate dataset sizes.
Spectral clustering
Spectral clustering builds a similarity graph over the points, computes leading eigenvectors of the graph Laplacian, and runs k-means on those eigenvectors. This handles non-convex shapes well when clusters are connected groups. It needs an n × n affinity structure and an eigendecomposition, so it is practical only for small to medium datasets.
Seeing the difference on non-convex data
The two-moons dataset has two crescent-shaped clusters. A mean-based method cannot separate them well. The script scores each method against the true labels with the adjusted Rand index (ARI), where 1.0 is a perfect match and values near 0 are no better than random.
from sklearn.cluster import DBSCAN, AgglomerativeClustering, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
X, y_true = 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),
"GaussianMixture": GaussianMixture(n_components=2, random_state=0).fit_predict(X),
"Agglomerative (ward)": AgglomerativeClustering(n_clusters=2).fit_predict(X),
"Agglomerative (single)": AgglomerativeClustering(
n_clusters=2, linkage="single"
).fit_predict(X),
"DBSCAN": DBSCAN(eps=0.2, min_samples=5).fit_predict(X),
}
for name, labels in results.items():
ari = adjusted_rand_score(y_true, labels)
print(f"{name:24s} ARI={ari:.2f}")K-means, the Gaussian mixture, and Ward linkage all assume compact groups and split the crescents across their bounding region, so their ARI is well below 1. DBSCAN and single-linkage agglomerative clustering follow the connected dense shape and recover the crescents almost perfectly. Neither of these needed the shape to be convex.
Choosing a method
Start from what you know about the data and the task.
The table summarizes the trade-offs.
| Method | You choose | Cluster shape | Handles noise | Scales to large `n` |
|---|---|---|---|---|
| KMeans | `k` | Convex, similar size | No | Good |
| MiniBatchKMeans | `k`, `batch_size` | Convex, similar size | No | Very good, supports streaming |
| GaussianMixture | components, covariance type | Ellipses | No (soft assignments) | Moderate |
| DBSCAN | `eps`, `min_samples` | Arbitrary | Yes | Moderate |
| HDBSCAN | `min_cluster_size` | Arbitrary, varying density | Yes | Moderate |
| Agglomerative | `k` or cut height, linkage | Depends on linkage | Limited | Poor |
| Spectral | `k`, affinity | Non-convex | No | Poor |
Common errors when switching methods
- Reusing the elbow method everywhere. Inertia is defined by k-means. For a GMM use BIC. For DBSCAN there is no
kto choose, so tuneepsusing a k-distance plot instead. - Skipping scaling. Every method here that depends on distance needs scaled features, not just k-means. A DBSCAN
epsis meaningless when one feature spans 0 to 100,000. - Treating the label
-1as a cluster. DBSCAN and HDBSCAN use it for noise. Filter it before computing per-cluster statistics, and decide explicitly whether noise points should be excluded from silhouette calculations. - Comparing inertia across methods. Only k-means variants minimize it, so a lower inertia from one method does not mean better clusters.
- Assuming a result means the structure is real. Every algorithm returns clusters, even for uniform random data. Check stability by refitting on resamples with different seeds.
Summary of the tutorial
K-means groups data by minimizing within-cluster squared distance, using Lloyd's alternating assignment and update steps. It finds a local minimum, so it needs good seeding (k-means++) and several restarts. It depends on scaling and on the choice of k. Mini-batch k-means trades a small amount of inertia for much lower cost and streaming support. When clusters are not compact blobs, a Gaussian mixture, density-based, or hierarchical method fits better.
Exercise
You have 50 million rows of 20 numeric features, stored on disk in chunks. You want 100 clusters and the data does not fit in memory. Which estimator and method would you use to fit it, which parameter must the first chunk satisfy, and what extra step do you need to take about scaling?
Show answer
Use MiniBatchKMeans and call partial_fit on each chunk as it is read. The first chunk must contain at least n_clusters (100) samples, and should be representative, because the initial centroids are chosen from it. For scaling, you cannot fit a normal StandardScaler on the full data at once, so either fit it incrementally with StandardScaler.partial_fit over a first pass or use fixed scaling constants known in advance, and apply the same transform to every chunk.
Exercise
You run DBSCAN on a scaled dataset and get 3 clusters plus a large group of points labeled -1. Name two things you could change to reduce the number of noise points, and say which direction each parameter moves.
Show answer
Increase eps, so points count as neighbors at a larger distance and more points join clusters. Decrease min_samples, so fewer neighbors are needed for a point to be a core point. Both changes can also merge distinct clusters, so check the result after each change.
Exercise
Why can a k-means silhouette score rate a k-means split of the two-moons data as good, even though the split does not match the true crescents?
Show answer
The silhouette score compares each point's distance to its own cluster with its distance to the nearest other cluster, so it rewards compact, well-separated groups. K-means produces compact groups by construction, and the silhouette score measures that same property. It does not measure whether the clusters follow connected, non-convex shapes, so it cannot detect that the crescents were cut apart.