Bounded-Memory Online Clustering of a Numeric Stream
Machine LearningModel answerLast updated
Design and code a clustering routine for an endless stream of numbers that keeps only small per-cluster summaries, and discuss seeding, convergence, outliers, drift, and testing.
Problem
Numbers arrive one at a time from a feed that never ends. You must group them into clusters on the fly. Keeping the full history is not an option, so memory use has to stay fixed no matter how long the feed runs.
Pick a clustering method and implement it as a small class with these operations:
add(value)consumes one new number and updates the model. It should also say which cluster the number went to (or that it was treated as an outlier).get_clusters()returns the current cluster centers, or richer summaries such as size and spread.
Assumptions
- You may take the number of clusters
kas an input. If you prefer not to, explain how you would pick it. - Per-cluster state must be constant-size, and total state must not grow with the length of the stream.
- Values are one-dimensional floats.
What to cover
- The algorithm you chose and why it suits a stream.
- What each cluster stores, and the exact update rule applied when a value arrives.
- How you seed the clusters at the start.
- Whether and why the centers converge.
- How you deal with extreme values.
- How you cope with a distribution that shifts over time.
- How you would test that the implementation is correct.
- Time and space cost of each operation, plus awkward edge cases.
Write working code (Python is fine) and justify the design choices.
Hints
Hint 1
Think of sequential k-means: each cluster holds a count and a center, and a new value only touches its nearest cluster. What step size makes the center equal the exact running mean?
Hint 2
In one dimension, centers stay in sorted order after such updates, so nearest-center lookup can use binary search. For seeding, avoid 'first k values become centers'; consider buffering a small sample and using its quantiles.
Hint 3
For drift, make old observations count less (a decay on the weight so the step size never reaches zero). For outliers, compare the new value with the cluster's running standard deviation before letting it move the center.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach: sequential (online) k-means with constant-size summaries
Each cluster keeps three numbers: a center, a weight (how many points it has absorbed, possibly decayed), and a variance. Memory is O(k).
When a value x arrives:
- Find the nearest center
c_i. - Increase the weight:
w_i ← w_i + 1. - Set the step size
η = 1 / w_iand move the center:c_i ← c_i + η (x − c_i). - Update the variance with Welford's recurrence:
v_i ← (1 − η)(v_i + η δ²), whereδ = x − c_iis measured before the move.
With η = 1/n the center is exactly the mean of every point assigned to that cluster, and the variance is the exact population variance. No raw points are kept.
One-dimensional bonus
The centers never swap order. If x is nearest to c_i, the updated c_i lands between its old position and x. Any other center inside that interval would have been closer to x, a contradiction. So the centers stay sorted, and the nearest-center search is a binary search in O(log k).
Design questions
Initialization. Starting with the first k values is fragile: a run of similar values gives k nearly identical centers that may never separate. Instead, buffer a warm-up of m values (for example 20k), seed centers at evenly spaced quantiles of the sorted buffer, and run a few batch Lloyd iterations on it. After that, discard the buffer and switch to the online update. Memory is O(k + m), still independent of stream length.
Convergence. Online k-means is stochastic gradient descent on the k-means SSE objective with per-cluster step sizes 1/n. These satisfy the Robbins-Monro conditions (Σ η = ∞, Σ η² < ∞), so on a stationary stream the centers converge to a local optimum, a fixed point of Lloyd's algorithm. It is not guaranteed to be the global optimum, and the result depends on seeding and arrival order, which is why quantile seeding plus Lloyd matters.
Outliers. Without protection, one huge value can drag a young center far away. Once a cluster has at least min_count points, if |x − c_i| > z·σ_i (with a small floor on σ_i to handle zero variance), do not absorb the value. Count it as an outlier and return -1. Trade-off: too small a z rejects legitimate new modes. A common refinement is to keep a small bounded buffer of rejected points and open or re-seed a cluster if they accumulate.
Concept drift. Use a decayed weight: w ← γ·w + 1 with γ ∈ (0, 1]. Then η = 1/w has a floor near 1 − γ, and the center becomes an exponentially weighted mean with effective memory about 1/(1 − γ) points. γ = 1 gives exact running means (stable, but slow to adapt). γ < 1 adapts to shifts but the centers jitter in a noise band forever. This is the stability-versus-plasticity trade-off. In production, monitor the outlier rate or the distance of new points to centers to detect drift and trigger re-seeding.
Choosing k when not given. Use the warm-up buffer: elbow on within-cluster SSE, silhouette score, or BIC for a 1D Gaussian mixture. A fully online alternative is DP-means: open a new cluster when a point is farther than a threshold λ from every center (and optionally merge clusters that drift close together to bound k).
Code
import bisect
import math
class StreamingKMeans1D:
def __init__(self, k, warmup=None, decay=1.0, outlier_z=None,
min_count=10, lloyd_iters=20):
if k < 1:
raise ValueError("k must be >= 1")
if not 0.0 < decay <= 1.0:
raise ValueError("decay must be in (0, 1]")
self.k = k
self.warmup = max(k, warmup if warmup is not None else 20 * k)
self.decay, self.outlier_z = decay, outlier_z
self.min_count, self.lloyd_iters = min_count, lloyd_iters
self._buf = []
self.c, self.w, self.v = [], [], [] # sorted centers
self.n_outliers = 0
def add(self, value):
x = float(value)
if not math.isfinite(x):
raise ValueError("value must be finite")
if not self.c: # warm-up phase
self._buf.append(x)
if len(self._buf) < self.warmup:
return None
self.c, self.w, self.v = self._fit(self._buf)
self._buf = []
return self._nearest(x)
i = self._nearest(x)
std = max(math.sqrt(self.v[i]), 1e-9)
if (self.outlier_z is not None and self.w[i] >= self.min_count
and abs(x - self.c[i]) > self.outlier_z * std):
self.n_outliers += 1
return -1
self.w[i] = self.decay * self.w[i] + 1.0
eta = 1.0 / self.w[i]
d = x - self.c[i]
self.c[i] += eta * d
self.v[i] = (1 - eta) * (self.v[i] + eta * d * d)
return i
def get_clusters(self):
if self.c:
c, w, v = self.c, self.w, self.v
elif self._buf:
c, w, v = self._fit(self._buf) # provisional only
else:
return []
return [{"center": a, "weight": b, "std": math.sqrt(s)}
for a, b, s in zip(c, w, v)]
def _nearest(self, x, centers=None):
c = self.c if centers is None else centers
j = bisect.bisect_left(c, x)
if j == 0:
return 0
if j == len(c):
return j - 1
return j - 1 if x - c[j - 1] <= c[j] - x else j
def _fit(self, data):
data = sorted(data)
n = len(data)
cs = sorted({data[min(n - 1, int((j + 0.5) * n / self.k))]
for j in range(self.k)})
for _ in range(self.lloyd_iters):
groups = [[] for _ in cs]
for x in data:
groups[self._nearest(x, cs)].append(x)
new = sorted({sum(g) / len(g) for g in groups if g})
if new == cs:
break
cs = new
groups = [[] for _ in cs]
for x in data:
groups[self._nearest(x, cs)].append(x)
w = [float(len(g)) for g in groups]
v = [sum((x - m) ** 2 for x in g) / len(g) if g else 0.0
for g, m in zip(groups, cs)]
return cs, w, v
Complexity
add:O(log k)lookup plusO(1)update after warm-up. The one-time fit costsO(m log m + iters · m log k).get_clusters:O(k).- Space:
O(k + m), independent of stream length.
Testing
- Exactness: with
decay = 1and no outlier rule, feed a fixed sequence, record the assignments, and compare each cluster's center, weight, and variance with a batch computation over the points assigned to it. - Recovery: sample from well-separated Gaussians (for example means 0, 10, 20), shuffle, stream them, and check the centers land near the true means.
- Order sensitivity: run several shuffles and confirm results are consistent, which exposes bad seeding.
- Sortedness invariant: assert
centers == sorted(centers)after every call. - Drift: shift a mean mid-stream and compare
decay = 1(lags) withdecay < 1(tracks). - Outliers: inject a value of 1e9 and verify the center barely moves and the outlier counter increments.
- Edge cases: fewer distinct values than
k(duplicate centers collapse; a later distinct value should open a new cluster), NaN or infinity (rejected), zero-variance clusters (std floor), callingget_clusters()mid-warm-up and on an empty model.
Common mistakes
- Using a fixed learning rate and calling it a running mean, or never reducing the step size on a stationary stream.
- Seeding with the first
kpoints. - Letting outliers update the center before checking them.
- Using decay without discussing the loss of exactness and the permanent jitter.
- Storing the whole history "just for the variance" instead of using Welford's recurrence.