Skip to Content
OchreML
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) and N4 (row_argmin) across CPU (Rayon), CUDA, wgpu, and Google TPU.
  • Incremental learning (partial_fit): Supported. Call partial_fit(X_batch, sample_weight=...) repeatedly to update centroids incrementally on streaming batches without holding the full dataset in memory.
  • Persistence: Supports binary .dit serialization via save(path), MiniBatchKMeans.load(path, device=...), ochreml.save(), and ochreml.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

ParameterTypeDefaultDescription
n_clustersint8Number of clusters to form and centroids to generate.
init{"k-means++", "random"}"k-means++"Method for centroid initialization.
max_iterint100Maximum number of iterations over the complete dataset before stopping.
batch_sizeint1024Number of samples per mini-batch.
tolfloat0.0Early stopping tolerance based on relative center changes / EWMA inertia.
max_no_improvementint10Consecutive mini-batches without smoothed inertia improvement before early stopping.
n_initint | "auto"3Number of random initializations tried; "auto" resolves to 3.
reassignment_ratiofloat0.01Fraction of maximum cluster count below which a center is reassigned to avoid empty clusters.
random_stateint | NoneNoneRandom seed controlling initialization and mini-batch sampling.
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
cluster_centers_ndarray of shape (n_clusters, n_features) | NoneCoordinates of fitted cluster centers.
labels_ndarray of shape (n_samples,) | NoneCluster index (int64) assigned to each sample from fit.
inertia_float | NoneSum of squared distances of samples to their closest cluster center.
n_iter_intNumber of full-dataset iterations completed.
n_steps_intTotal number of mini-batch updates performed across fit or partial_fit.
n_features_in_int | NoneNumber of features seen during fit or partial_fit.
device_str | NoneResolved hardware device string used by the underlying Rust model.

Methods

MethodSignatureDescription
fitfit(X, y=None, sample_weight=None) -> MiniBatchKMeansCompute centroids on X using mini-batch updates.
partial_fitpartial_fit(X, y=None, sample_weight=None) -> MiniBatchKMeansIncrementally update centroid estimates on a single mini-batch X.
fit_predictfit_predict(X, y=None, sample_weight=None) -> ndarrayFit the model and return int64 cluster labels for X.
fit_transformfit_transform(X, y=None, sample_weight=None) -> ndarrayFit the model and return Euclidean distances to each cluster center (shape (n_samples, n_clusters)).
predictpredict(X) -> ndarrayPredict the closest cluster index (int64) for each sample in X.
transformtransform(X) -> ndarrayTransform X to cluster-distance space (shape (n_samples, n_clusters)).
scorescore(X, y=None, sample_weight=None) -> floatReturn the negative inertia of X under the fitted centers.
savesave(path: str) -> NoneSave the fitted model to a binary .dit file.
loadMiniBatchKMeans.load(path: str, device: str | None = None) -> MiniBatchKMeansLoad a fitted model from a binary .dit file.
toto(device: str) -> MiniBatchKMeansMove 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]])))

On this page