KatInterview

Bounded-Memory Online Clustering of a Numeric Stream

Machine LearningModel answer
MediumModel answerMachine Learningstreamingonline-clusteringk-means

Last 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 k as 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

  1. The algorithm you chose and why it suits a stream.
  2. What each cluster stores, and the exact update rule applied when a value arrives.
  3. How you seed the clusters at the start.
  4. Whether and why the centers converge.
  5. How you deal with extreme values.
  6. How you cope with a distribution that shifts over time.
  7. How you would test that the implementation is correct.
  8. 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.