Clustering, Neighbors & NB
MiniBatchKMeans
Streaming and mini-batch K-Means clustering with online SGD center updates and partial_fit support.
Overview & Backend Support
MiniBatchKMeans reduces the computational cost of K-Means on large or streaming datasets by updating centroids on fixed-size mini-batches using online stochastic gradient steps and center reassignment for under-populated clusters.
- Backend primitives:
N3(pairwise_l2_sq) andN4(row_argmin) across CPU (Rayon), CUDA,wgpu, and Google TPU. - Incremental learning (
partial_fit): Supported. Callpartial_fit(X_batch, sample_weight=...)repeatedly to update centroids incrementally on streaming batches without holding the full dataset in memory. - Persistence: Supports binary
.ditserialization viasave(path),MiniBatchKMeans.load(path, device=...),ochreml.save(), andochreml.load().
Import & Signature
from ochreml.cluster import MiniBatchKMeans
# or lazily from top-level:
from ochreml import MiniBatchKMeans
MiniBatchKMeans(
n_clusters: int = 8,
init: str = "k-means++",
max_iter: int = 100,
batch_size: int = 1024,
tol: float = 0.0,
max_no_improvement: int = 10,
n_init: int | str = 3,
reassignment_ratio: float = 0.01,
random_state: int | None = None,
device: str | None = None,
)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n_clusters | int | 8 | Number of clusters to form and centroids to generate. |
init | {"k-means++", "random"} | "k-means++" | Method for centroid initialization. |
max_iter | int | 100 | Maximum number of iterations over the complete dataset before stopping. |
batch_size | int | 1024 | Number of samples per mini-batch. |
tol | float | 0.0 | Early stopping tolerance based on relative center changes / EWMA inertia. |
max_no_improvement | int | 10 | Consecutive mini-batches without smoothed inertia improvement before early stopping. |
n_init | int | "auto" | 3 | Number of random initializations tried; "auto" resolves to 3. |
reassignment_ratio | float | 0.01 | Fraction of maximum cluster count below which a center is reassigned to avoid empty clusters. |
random_state | int | None | None | Random seed controlling initialization and mini-batch sampling. |
device | str | None | None | Target compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device(). |
Attributes
| Attribute | Type | Description |
|---|---|---|
cluster_centers_ | ndarray of shape (n_clusters, n_features) | None | Coordinates of fitted cluster centers. |
labels_ | ndarray of shape (n_samples,) | None | Cluster index (int64) assigned to each sample from fit. |
inertia_ | float | None | Sum of squared distances of samples to their closest cluster center. |
n_iter_ | int | Number of full-dataset iterations completed. |
n_steps_ | int | Total number of mini-batch updates performed across fit or partial_fit. |
n_features_in_ | int | None | Number of features seen during fit or partial_fit. |
device_ | str | None | Resolved hardware device string used by the underlying Rust model. |
Methods
| Method | Signature | Description |
|---|---|---|
fit | fit(X, y=None, sample_weight=None) -> MiniBatchKMeans | Compute centroids on X using mini-batch updates. |
partial_fit | partial_fit(X, y=None, sample_weight=None) -> MiniBatchKMeans | Incrementally update centroid estimates on a single mini-batch X. |
fit_predict | fit_predict(X, y=None, sample_weight=None) -> ndarray | Fit the model and return int64 cluster labels for X. |
fit_transform | fit_transform(X, y=None, sample_weight=None) -> ndarray | Fit the model and return Euclidean distances to each cluster center (shape (n_samples, n_clusters)). |
predict | predict(X) -> ndarray | Predict the closest cluster index (int64) for each sample in X. |
transform | transform(X) -> ndarray | Transform X to cluster-distance space (shape (n_samples, n_clusters)). |
score | score(X, y=None, sample_weight=None) -> float | Return the negative inertia of X under the fitted centers. |
save | save(path: str) -> None | Save the fitted model to a binary .dit file. |
load | MiniBatchKMeans.load(path: str, device: str | None = None) -> MiniBatchKMeans | Load a fitted model from a binary .dit file. |
to | to(device: str) -> MiniBatchKMeans | Move estimator compute target to another hardware device. |
Example
import numpy as np
from ochreml.cluster import MiniBatchKMeans
rng = np.random.default_rng(42)
batch_1 = np.vstack([rng.normal(0.0, 0.3, (64, 2)), rng.normal(5.0, 0.3, (64, 2))])
batch_2 = np.vstack([rng.normal(0.0, 0.3, (64, 2)), rng.normal(5.0, 0.3, (64, 2))])
mbk = MiniBatchKMeans(n_clusters=2, batch_size=32, random_state=42)
mbk.partial_fit(batch_1)
mbk.partial_fit(batch_2)
print("Steps:", mbk.n_steps_)
print("Centers:\n", mbk.cluster_centers_)
print("Predictions:", mbk.predict(np.array([[0.1, -0.1], [5.1, 4.9]])))