Foundations to Frontier
Tests

Mini-batch k-Means

Mini-batch k-means (Sculley, 2010) updates the centres from small random batches instead of the whole dataset. Each batch is assigned to its nearest centres, and each centre moves toward its new points with a step size of one over the number of points it has won so far, so it becomes a running mean. It reaches a good clustering in a fraction of one pass over the data, needs little memory, and works on streams. The price is a slightly higher final inertia than full Lloyd and some sensitivity to batch size. This page covers the update rule, its link to stochastic gradient descent, batch-size trade-offs, stopping and reassigning empty centres. In the exercises you implement mini-batch k-means and compare it with Lloyd; then you map quality against compute for batch sizes from 32 to 2048.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Update from a handful of points at a time

Lloyd’s algorithm looks at every point before moving any centre. With millions of points, that is slow. Mini-batch k-means grabs a small random batch (say 256 points), nudges the centres toward the batch points they win, and repeats with a new batch. Each centre moves less as it collects more points, settling down like a running average.

Mini-batch k-means: many cheap updates
optpoints processed (passes over the data) →Lloyd (dots: after each full pass)mini-batch
at 1.00 passes: mini-batch inertia ÷ optimum 1.005 · Lloyd after 1 full pass 1.268
Mini-batch gets most of the way in a fraction of one pass, before Lloyd has updated anything. Very large batches waste that advantage: they update rarely. On this easy 2-D problem even tiny batches work well. On harder ones (exercise 2), tiny batches are noisy, and because each centre's step size shrinks as 1/count, early mistakes get frozen in. Given several full passes, Lloyd ends slightly lower than mini-batch.
Why engineers care

Telemetry archives, image patches and log embeddings often have millions to billions of rows. Mini-batch k-means clusters them in minutes on one machine with constant memory, and it can keep updating as new data streams in, for example to track drifting operating regimes on a fleet.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Mini-batch k-means updates centres using…
  2. 2. As a centre collects more points, its moves get…
  3. 3. Compared with Lloyd after many passes, mini-batch ends with…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The update by hand

Running mean. Each centre keeps a count v of points it has won. A batch gives it m new points with sum S, and it moves to

c ← (v·c + S) / (v + m), v ← v + m.

Example 1. A centre at 0 with count 2 wins the point 3: c = (2·0 + 3)/3 = 1, count 3.

Example 2. A centre at 4 with count 4 wins 6 and 9: c = (16 + 15)/6 = 5.167, count 6.

Step size. Processing points one at a time, this is c ← c + η(x − c) with η = 1/v. After 5 points, η = 0.2.

Compute. One step processes b points against k centres: b·k distances. For n = 10⁶, k = 100, batch 1000 and 500 steps that is 5 × 10⁷ distances, half a pass. Twenty Lloyd passes need 2 × 10⁹, 40 times more.

The steps in plain English:

  1. Seed k centres (k-means++ on a sample) and set every count to 0.
  2. Draw a random batch of b points and assign each to its nearest centre.
  3. For each centre, fold its new points into its running mean and add them to its count.
  4. Repeat until the centres stop moving much, or inertia on a held-out sample stops improving. Optionally re-seed centres whose counts stay tiny.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Centre at 2, count 3, wins point 6. New centre?
  2. 2. Step size after a centre has won 10 points?
  3. 3. Distances per step with batch 512 and k = 20?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

What mini-batch trades away

Stochastic gradient view. The k-means objective’s gradient with respect to centre c is −2Σ(x − c) over the points it owns. A batch gives a noisy estimate. The update c ← c + η(x̄_batch − c) is an SGD step, and η = 1/v is a decreasing step size, the Robbins–Monro schedule. So mini-batch k-means converges to a local minimum of the expected objective, at SGD’s slower final rate.

Where the speed comes from. The early steps of Lloyd mostly fix gross errors, and a few hundred random points are enough to see those. Exercise 1 (n = 20 000, k = 10): Lloyd took 33 passes to converge. Mini-batch with batch 256 was within 7.9% of Lloyd’s inertia after 0.13 passes, 2.6% after 0.64, and 0.47% after 2.56.

Batch size.

  • Small batches give many updates per pass, but noisy ones. With η = 1/v, early noise is averaged in with full weight and never undone.
  • Large batches give accurate updates, but few of them.
  • Exercise 2 found a sweet spot in the hundreds. scikit-learn’s default is 1024.

Practical details.

  • Seed with k-means++ on a sample.
  • Re-assign centres that win almost nothing (scikit-learn’s reassignment_ratio).
  • Stop on stalled improvement of smoothed batch inertia.
  • For streaming data that drifts, cap the count (a constant step size) so centres can keep moving.
from sklearn.cluster import MiniBatchKMeans
mbk = MiniBatchKMeans(n_clusters=20, batch_size=1024, n_init=3, random_state=0).fit(X)
for chunk in stream: mbk.partial_fit(chunk)          # online updates
🐍 Exercise 1: mini-batch k-means versus Lloyd
Implement k-means++ seeding, vectorised nearest-centre search, full Lloyd and mini-batch k-means with per-centre 1/count steps; compare inertia against passes over the data.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The 1/count step size is an example of…
  2. 2. For drifting streams, a better choice is…
  3. 3. In exercise 1, after 0.64 passes mini-batch was within…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Convergence. With step sizes η_t satisfying Ση_t = ∞ and Ση_t² < ∞, the online k-means iteration (MacQueen’s algorithm with batch size 1) converges almost surely to a stationary point of the expected objective (Bottou and Bengio, 1995). The 1/count rule satisfies both conditions for each centre that keeps winning points.

Error versus compute. Lloyd’s per-pass cost is n·k·d. Mini-batch reaches error ε above a local optimum after about O(1/ε) batches, independent of n. So for very large n it wins at moderate accuracy, while Lloyd wins when you need the last fraction of a percent.

Noise floor. With a fixed batch size, the gap to Lloyd shrinks only as the counts grow. Badly placed early updates are averaged in permanently. That is why small batches plateaued in exercise 2.

Interview questions.

  • When would you choose mini-batch k-means? With very large n, limited memory, streaming data, or when an approximately optimal clustering is enough.
  • How do you choose the batch size? Large enough that each centre sees several points per batch (at least a few × k), small enough for many updates per pass. Validate inertia on a held-out sample.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Robbins–Monro conditions require Ση_t…
  2. 2. Mini-batch's cost to reach accuracy ε depends on n…
  3. 3. Batch size 1 mini-batch k-means is…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Which batch size gives the most for the compute?

History.

  • J. MacQueen (1967) introduced the online, one-point-at-a-time k-means.
  • L. Bottou and Y. Bengio (1995) analysed it as stochastic gradient descent.
  • D. Sculley (2010) proposed mini-batch k-means for web-scale clustering at Google.
  • scikit-learn’s MiniBatchKMeans added reassignment of starved centres and early stopping.

Exercise 2. n = 20 000, k = 20, d = 8, k-means++ seeds, 3 repetitions. Each cell is inertia ÷ converged Lloyd after the given compute, in passes over the data.

method 0.25 passes 1 pass 4 passes
batch 32 1.107 1.099 1.089
batch 128 1.074 1.056 1.052
batch 512 1.056 1.041 1.040
batch 2048 1.121 1.049 1.040
Lloyd (seeds only at 0.25) 2.181 1.278 1.039
  • Within one pass, mini-batch is far ahead. After a single pass Lloyd was still 28% above the optimum; mini-batch with batch 512 was 4%.
  • Batch size matters. Batch 32 plateaued about 9% above the optimum, freezing in early noise. 2048 started slowly. 512 was best throughout.
  • With 4 passes, the best mini-batch matched Lloyd (1.040 against 1.039). Both were still about 4% above the converged solution, which Lloyd from the same seeds reaches only after many more passes.
🐍 Exercise 2 (research): quality versus compute and batch size
On 20 Gaussian blobs in 8-D (n = 20 000), record inertia ÷ converged Lloyd for mini-batch k-means with batch sizes 32–2048 and for Lloyd, after 0.25, 1 and 4 passes of compute.

Mini-batch k-means in AI, robotics and aerospace

  • Web-scale and fleet-scale clustering of logs, embeddings and telemetry where full passes are expensive.
  • Online regime tracking: partial_fit on streaming sensor data, with a capped count so centres follow drift.
  • Codebooks for learned compression (vector quantisation layers), which are trained with mini-batch or exponential-moving-average centre updates.

References

  1. D. Sculley (2010). “Web-scale k-means clustering.” Proc. WWW.
  2. L. Bottou, Y. Bengio (1995). “Convergence properties of the k-means algorithms.” NeurIPS 7.
  3. J. MacQueen (1967). “Some methods for classification and analysis of multivariate observations.” Proc. 5th Berkeley Symposium.
  4. H. Robbins, S. Monro (1951). “A stochastic approximation method.” Annals of Mathematical Statistics 22.
  5. scikit-learn developers. “MiniBatchKMeans.” Documentation.