Skip to Content
OchreML
Clustering, Neighbors & NB

KMeans

Centroid-based K-Means clustering with k-means++ initialization and hardware-accelerated pairwise distance primitives.

Overview & Backend Support

KMeans partitions observations into n_clusters Voronoi cells by minimizing within-cluster sum of squared Euclidean distances (inertia). It supports k-means++ and random centroid initialization, multiple restarts (n_init), and per-sample weights (sample_weight).

  • Backend primitives: N3 (pairwise_l2_sq) and N4 (row_argmin) across CPU (Rayon), CUDA (cuda:0, cuda:all), wgpu, and Google TPU (tpu:0).
  • Incremental learning (partial_fit): Not supported; use MiniBatchKMeans for online or out-of-core streaming updates.
  • Persistence: Supports binary .dit serialization via save(path), KMeans.load(path, device=...), ochreml.save(), and ochreml.load().

Import & Signature

from ochreml.cluster import KMeans
# or lazily from top-level:
from ochreml import KMeans

KMeans(
    n_clusters: int = 8,
    init: str = "k-means++",
    n_init: int | str = 10,
    max_iter: int = 300,
    tol: float = 1e-4,
    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.
n_initint | "auto"10Number of independent runs with different centroid seeds; "auto" resolves to 10.
max_iterint300Maximum number of Lloyd iterations for a single run.
tolfloat1e-4Relative convergence tolerance on the Frobenius norm of center shifts between consecutive iterations.
random_stateint | NoneNoneRandom seed controlling centroid initialization.
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 training sample.
inertia_float | NoneSum of squared distances of samples to their closest cluster center (weighted if sample_weight is provided).
n_iter_intNumber of iterations run in the best initialization.
n_features_in_int | NoneNumber of features seen during fit.
device_str | NoneResolved hardware device string used by the underlying Rust model.

Methods

MethodSignatureDescription
fitfit(X, y=None, sample_weight=None) -> KMeansCompute K-Means clustering on 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.
loadKMeans.load(path: str, device: str | None = None) -> KMeansLoad a fitted model from a binary .dit file.
toto(device: str) -> KMeansMove estimator compute target to another hardware device.

Example

import numpy as np
from ochreml.cluster import KMeans

X = np.array([
    [1.0, 2.0], [1.2, 1.8], [0.8, 2.2],
    [8.0, 9.0], [8.5, 8.7], [7.9, 9.2],
], dtype=np.float64)

km = KMeans(n_clusters=2, n_init=10, random_state=42, device="auto")
labels = km.fit_predict(X)

print("Labels:", labels)
print("Centers:\n", km.cluster_centers_)
print("Inertia:", km.inertia_)
print("Distances to centers:\n", km.transform(np.array([[1.0, 1.9], [8.1, 9.0]])))

On this page