Clustering, Neighbors & NB
KNeighborsClassifier
Non-parametric k-nearest neighbors classifier with uniform or distance-weighted voting and hardware-accelerated neighbor search.
Overview & Backend Support
KNeighborsClassifier assigns each query sample the majority (or inverse-distance-weighted) class among its n_neighbors closest training samples. It supports multiple distance metrics, probability estimation (predict_proba), and direct neighbor inspection (kneighbors).
- Backend primitives:
N3(pairwise_l2_sq) andN4(topk_argmin) across CPU (Rayon), CUDA,wgpu, and Google TPU for Euclidean / Minkowski (p=2) queries;"manhattan"/"l1","chebyshev","cosine", and general Minkowskipare also supported. - Incremental learning (
partial_fit): Not supported. - Persistence: Supports binary
.ditserialization viasave(path),KNeighborsClassifier.load(path, device=...),ochreml.save(), andochreml.load().
Import & Signature
from ochreml.neighbors import KNeighborsClassifier
# or lazily from top-level:
from ochreml import KNeighborsClassifier
KNeighborsClassifier(
n_neighbors: int = 5,
*,
weights: str = "uniform",
metric: str = "minkowski",
p: float = 2.0,
device: str | None = None,
)Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
n_neighbors | int | 5 | Number of nearest neighbors used by default for classification and kneighbors queries. |
weights | {"uniform", "distance"} | "uniform" | Weight function for neighbor voting ("uniform" gives equal weight; "distance" weights by inverse distance). |
metric | {"minkowski", "euclidean", "l2", "manhattan", "l1", "chebyshev", "cosine"} | "minkowski" | Distance metric used for neighbor search. |
p | float | 2.0 | Power parameter for the Minkowski metric (p=1 is Manhattan, p=2 is Euclidean). |
device | str | None | None | Target compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device(). |
Attributes
| Attribute | Type | Description |
|---|---|---|
classes_ | ndarray of shape (n_classes,) | None | Sorted unique class labels (float64) known to the classifier. |
n_features_in_ | int | None | Number of features seen during fit. |
n_samples_fit_ | int | None | Number of indexed training samples. |
device_ | str | None | Resolved hardware device string used by the underlying Rust model. |
Methods
| Method | Signature | Description |
|---|---|---|
fit | fit(X, y) -> KNeighborsClassifier | Index training features X and 1D class targets y. |
predict | predict(X) -> ndarray | Predict class labels (float64, shape (n_queries,)) for X. |
predict_proba | predict_proba(X) -> ndarray | Return class probability estimates of shape (n_queries, n_classes). |
score | score(X, y) -> float | Return mean classification accuracy on (X, y). |
kneighbors | kneighbors(X=None, n_neighbors=None, return_distance=True) | Return (distances, indices) or indices of shape (n_queries, k). If X is None, queries the training set excluding each point itself. |
save | save(path: str) -> None | Save the fitted classifier to a binary .dit file. |
load | KNeighborsClassifier.load(path: str, device: str | None = None) -> KNeighborsClassifier | Load a fitted classifier from a binary .dit file. |
to | to(device: str) -> KNeighborsClassifier | Move estimator compute target to another hardware device. |
Example
import numpy as np
from ochreml.neighbors import KNeighborsClassifier
X = np.array([[0.0, 0.0], [0.2, 0.1], [3.0, 3.0], [3.1, 2.9]], dtype=np.float64)
y = np.array([0, 0, 1, 1], dtype=np.float64)
clf = KNeighborsClassifier(n_neighbors=2, weights="distance", metric="euclidean")
clf.fit(X, y)
X_query = np.array([[0.1, 0.05], [2.9, 3.1]], dtype=np.float64)
print("Predictions:", clf.predict(X_query))
print("Probabilities:\n", clf.predict_proba(X_query))
dists, idxs = clf.kneighbors(X_query, n_neighbors=2)
print("Neighbor indices:\n", idxs)