Skip to content

Neighbours

knn_graph

knn_graph(
    X: Any,
    k: int = 15,
    *,
    metric: str = "euclidean",
    ann: str = "kmknn",
    nn_params: NeighbourParams | None = None,
    seed: int = 42,
    verbose: int = 0,
) -> tuple[ndarray, ndarray]

Build a k-nearest-neighbour graph over X.

Parameters:

Name Type Description Default
X Any

Array-like of shape (n_samples, n_features). float32 and float64 are used as-is; anything else is promoted to float64.

required
k int

Neighbours per point, excluding self.

15
metric str

"euclidean"/"l2", "cosine" or "manhattan"/"l1".

'euclidean'
ann str

"exhaustive", "kmknn", "balltree", "annoy", "hnsw", "ivf" or "nndescent". "kmknn" is exact and holds up well into the hundreds of thousands; past that "nndescent" or "hnsw".

'kmknn'
nn_params NeighbourParams | None

Backend-specific knobs. See NeighbourParams.

None
seed int

Fixes anything randomised in the build.

42
verbose int

0 silent, 1 normal, 2 detailed.

0

Returns:

Type Description
ndarray

(indices, distances), both (n_samples, k). Indices are int64,

ndarray

distances match the dtype of X. Indices first, unlike scikit-learn:

tuple[ndarray, ndarray]

it is the order the estimators take them in.

Raises:

Type Description
ValueError

If ann or metric is not recognised, or X is empty or not finite.

set_num_threads builtin

set_num_threads(n: int) -> None

Cap the threads the core may use.

Params
  • n - Thread count. 0 restores rayon's global pool, which sizes itself from RAYON_NUM_THREADS or the core count.
Returns

Nothing, or a ValueError if the pool could not be built.

num_threads builtin

num_threads() -> int

Threads the core will use for the next call.

Returns

The configured cap, or rayon's global pool size when none was set.

gpu_available builtin

gpu_available() -> bool

Whether the GPU entry points can be used here.

Returns

True only when this build has the gpu feature and wgpu resolves an adapter. Safe to call on any machine.

Note

Acquiring a client panics rather than erroring when no adapter is found, so the probe catches it. That is sound here because the release profile is pinned to panic = "unwind", which pyo3 requires anyway. The panic hook is silenced for the duration, otherwise merely asking the question prints a backtrace to stderr.