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) andN4(row_argmin) across CPU (Rayon), CUDA (cuda:0,cuda:all),wgpu, and Google TPU (tpu:0). - Incremental learning (
partial_fit): Not supported; useMiniBatchKMeansfor online or out-of-core streaming updates. - Persistence: Supports binary
.ditserialization viasave(path),KMeans.load(path, device=...),ochreml.save(), andochreml.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
| 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. |
n_init | int | "auto" | 10 | Number of independent runs with different centroid seeds; "auto" resolves to 10. |
max_iter | int | 300 | Maximum number of Lloyd iterations for a single run. |
tol | float | 1e-4 | Relative convergence tolerance on the Frobenius norm of center shifts between consecutive iterations. |
random_state | int | None | None | Random seed controlling centroid initialization. |
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 training sample. |
inertia_ | float | None | Sum of squared distances of samples to their closest cluster center (weighted if sample_weight is provided). |
n_iter_ | int | Number of iterations run in the best initialization. |
n_features_in_ | int | None | Number of features seen during 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) -> KMeans | Compute K-Means clustering on 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 | KMeans.load(path: str, device: str | None = None) -> KMeans | Load a fitted model from a binary .dit file. |
to | to(device: str) -> KMeans | Move 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]])))