Online Mini-Batch K-Means With partial_fit

Quick Overview

Implement a streaming k-means class whose partial_fit labels each mini-batch against fixed centroids and then updates them with a per-cluster running-mean step. It tests the incremental mean, batch ordering, input validation, and how to handle drift and dead clusters.

Online Mini-Batch K-Means With partial_fit

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `OnlineKMeans(init_centroids, init_counts=None)`, a streaming k-means whose `partial_fit(batch)` assigns each batch point to its nearest centroid, then updates centroids one point at a time: increment `counts_[c]` and set `c <- c + (1 / counts_[c]) * (x - c)`. Also implement `predict(X)` and `inertia(X)`. Requirements: - Store float copies in `centroids_` (k × d) and int `counts_` (zeros if `init_counts` is `None`). Never mutate the inputs. - All labels in a batch use the centroids from the start of that batch. Ties go to the lowest index. Store them in `labels_` and return `self`. - Clusters with no assigned points keep their centroid and count. - `predict` returns int labels. `inertia` returns the float sum of squared distances to the nearest centroid (`0.0` for empty `X`). - Non-2-D input or a feature-count mismatch raises `ValueError`. An empty batch (shape `(0, d)`) sets `labels_` to an empty array. Example: ```python m = OnlineKMeans([[0.0], [10.0]]) m.partial_fit([[6.0], [4.8]]) m.labels_ # [1, 0] (both assigned against [0], [10]) m.centroids_ # [[4.8], [6.0]] m.counts_ # [1, 1] ``` Both points are labelled against the starting centroids: 6.0 is closer to 10, and 4.8 is closer to 0. Each cluster starts with count 0, so its first point gets weight 1 and replaces the centroid. ```hint Order of operations Decide exactly when the batch labels are computed relative to the first centroid update, and check the example against that order. ``` ```hint What the step size gives you Work out what a centroid equals after a few updates with step `1 / counts_[c]`, starting from a known count. ``` ### Constraints & Assumptions - `init_centroids` is a non-empty `k × d` array-like. `init_counts`, when given, holds `k` non-negative integers. - Distances are squared Euclidean. ### Clarifying Questions to Ask - Do `init_counts` stand for points already absorbed into each centroid, so that a centroid with count 0 is replaced outright by its first point? - Should an empty batch written as `[]` be accepted, or only an array of shape `(0, d)`? - Is a per-point Python loop fast enough, or does batch throughput matter enough to vectorize the update? ### What a Strong Answer Covers - Labels for the whole batch computed before any update, with ties going to the lowest index. - The `1 / counts_[c]` step read as an incremental mean, including what `init_counts` does to it. - Defensive float copies, the right dtypes, and untouched clusters keeping their centroid and count. - Shape and feature-count validation, plus the empty-batch and empty-`X` cases. - Time and memory cost per batch. ### Follow-up Questions - How would you handle concept drift where old points should matter less? - How would you deal with clusters that never receive points? - Can the per-point update loop be vectorized?

Overview: Implement a streaming k-means class whose partial_fit labels each mini-batch against fixed centroids and then updates them with a per-cluster running-mean step. It tests the incremental mean, batch ordering, input validation, and how to handle drift and dead clusters.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement OnlineKMeans(init_centroids, init_counts=None), a streaming k-means whose partial_fit(batch) assigns each batch point to its nearest centroid, then updates centroids one point at a time: increment counts_[c] and set c <- c + (1 / counts_[c]) * (x - c). Also implement predict(X) and inertia(X).

Requirements:

  • Store float copies in centroids_ (k × d) and int counts_ (zeros if init_counts is None ). Never mutate the inputs.
  • All labels in a batch use the centroids from the start of that batch. Ties go to the lowest index. Store them in labels_ and return self .
  • Clusters with no assigned points keep their centroid and count.
  • predict returns int labels. inertia returns the float sum of squared distances to the nearest centroid ( 0.0 for empty X ).
  • Non-2-D input or a feature-count mismatch raises ValueError . An empty batch (shape (0, d) ) sets labels_ to an empty array.

Example:

m = OnlineKMeans([[0.0], [10.0]])
m.partial_fit([[6.0], [4.8]])
m.labels_     # [1, 0]  (both assigned against [0], [10])
m.centroids_  # [[4.8], [6.0]]
m.counts_     # [1, 1]

Both points are labelled against the starting centroids: 6.0 is closer to 10, and 4.8 is closer to 0. Each cluster starts with count 0, so its first point gets weight 1 and replaces the centroid.

Constraints & Assumptions

  • init_centroids is a non-empty k × d array-like. init_counts , when given, holds k non-negative integers.
  • Distances are squared Euclidean.

Clarifying Questions to Ask Guidance

  • Do init_counts stand for points already absorbed into each centroid, so that a centroid with count 0 is replaced outright by its first point?
  • Should an empty batch written as [] be accepted, or only an array of shape (0, d) ?
  • Is a per-point Python loop fast enough, or does batch throughput matter enough to vectorize the update?

What a Strong Answer Covers Guidance

  • Labels for the whole batch computed before any update, with ties going to the lowest index.
  • The 1 / counts_[c] step read as an incremental mean, including what init_counts does to it.
  • Defensive float copies, the right dtypes, and untouched clusters keeping their centroid and count.
  • Shape and feature-count validation, plus the empty-batch and empty- X cases.
  • Time and memory cost per batch.

Follow-up Questions Guidance

  • How would you handle concept drift where old points should matter less?
  • How would you deal with clusters that never receive points?
  • Can the per-point update loop be vectorized?