Skip to content

Estimator base

Shared fit / kneighbors / save plumbing. You never instantiate these directly, but every estimator inherits the methods documented here.

_base

Shared estimator behaviour.

Every index here is immutable once built, so the scikit-learn shape (parameters in __init__, data in fit, results from kneighbors) is the honest one: the FAISS-style add() would be a method callable exactly once.

get_params and set_params introspect the subclass __init__, which is all sklearn.base.BaseEstimator does. Doing it here keeps scikit-learn out of the install requirements while clone, GridSearchCV and Pipeline still work by duck-typing.

BaseAnnIndex

Common fit / kneighbors plumbing for every index.

Subclasses supply an __init__ that stores its parameters verbatim, a _build hook, a _search_kwargs hook naming the algorithm's search-time knobs, and the handle class from the compiled core.

get_params

get_params(deep: bool = True) -> dict[str, Any]

Parameters this estimator was constructed with.

Parameters:

Name Type Description Default
deep bool

Accepted for scikit-learn compatibility; these estimators hold no nested estimators, so it makes no difference.

True

Returns:

Type Description
dict[str, Any]

Constructor parameters, keyed by name.

set_params

set_params(**params: Any) -> BaseAnnIndex

Set constructor parameters, invalidating any fitted index.

Returns:

Type Description
BaseAnnIndex

self.

Raises:

Type Description
ValueError

If a name is not a parameter of this estimator.

fit

fit(X: Any, y: Any = None) -> BaseAnnIndex

Build the index over X.

Parameters:

Name Type Description Default
X Any

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

required
y Any

Ignored, present for scikit-learn pipeline compatibility.

None

Returns:

Type Description
BaseAnnIndex

self.

kneighbors

kneighbors(
    X: Any = None,
    n_neighbors: int | None = None,
    *,
    return_distance: bool = True,
    **overrides: Any,
) -> tuple[ndarray, ndarray] | ndarray

Find the nearest neighbours of X among the fitted points.

Parameters:

Name Type Description Default
X Any

Query points of shape (n_queries, n_features). None means query the fitted data against itself, which takes each index's own fast path rather than re-entering from outside.

None
n_neighbors int | None

Neighbours per query. Defaults to self.n_neighbors.

None
return_distance bool

Whether to return distances alongside indices. This saves the copy into numpy but not the distance computation, which the core does either way.

True
**overrides Any

Per-call values for this algorithm's search-time knobs, for example ef_search or nprobe.

{}

Returns:

Type Description
tuple[ndarray, ndarray] | ndarray

(distances, indices), or just indices when

tuple[ndarray, ndarray] | ndarray

return_distance is False. Both have shape (n_queries, k).

tuple[ndarray, ndarray] | ndarray

A query that found fewer than k neighbours is padded with -1

tuple[ndarray, ndarray] | ndarray

indices and infinite distances.

kneighbors_graph

kneighbors_graph(
    X: Any = None,
    n_neighbors: int | None = None,
    mode: str = "distance",
    **overrides: Any,
) -> Any

Build the sparse neighbourhood graph.

Parameters:

Name Type Description Default
X Any

Query points, or None for the self-kNN graph.

None
n_neighbors int | None

Neighbours per query. Defaults to self.n_neighbors.

None
mode str

"distance" weights edges by distance, "connectivity" by 1.

'distance'
**overrides Any

Per-call search-time knobs, as for kneighbors.

{}

Returns:

Type Description
Any

A scipy.sparse.csr_matrix of shape

Any

(n_queries, n_samples_fit_). Padding slots are dropped, so rows

Any

can hold fewer than k entries.

Raises:

Type Description
ImportError

If scipy is not installed.

ValueError

If mode is not recognised.

transform

transform(X: Any = None) -> Any

Neighbourhood graph of X, for use as a KNeighborsTransformer.

fit_transform

fit_transform(X: Any, y: Any = None) -> Any

Fit on X and return its self-kNN graph.

save

save(path: str | Path) -> None

Write the fitted index to a directory.

The directory holds the core's own bundle plus a small JSON sidecar with the estimator parameters, so load reproduces the whole object rather than a bare handle.

Parameters:

Name Type Description Default
path str | Path

Target directory. Created if it does not exist.

required

Raises:

Type Description
NotImplementedError

If this index cannot be serialised. The GPU indices hold device buffers and sit outside the crate's serialise feature, so rebuilding is the only route.

load classmethod

load(path: str | Path) -> BaseAnnIndex

Read an index written by save.

Parameters:

Name Type Description Default
path str | Path

Directory holding the bundle.

required

Returns:

Type Description
BaseAnnIndex

The reconstructed estimator.

Raises:

Type Description
ValueError

If the directory was written by a different index type.

NotImplementedError

If this index cannot be serialised.

ExtractKnnMixin

Read-back of a graph the index already built, for the descent indices.

NN-Descent and its GPU counterpart converge on a kNN graph and keep it, so kneighbors(None) searches for something already sitting in the handle. No other index here has such a graph, hence a mixin rather than a method on BaseAnnIndex.

extract_knn

extract_knn(
    n_neighbors: int | None = None,
    *,
    include_self: bool = True,
    return_distance: bool = True,
) -> tuple[ndarray, ndarray] | ndarray

Return the graph the descent built, without searching it.

Parameters:

Name Type Description Default
n_neighbors int | None

Total row length, the self-edge included when include_self is set. None keeps the build-time degree, which is the ceiling. Note this differs from kneighbors, where None means self.n_neighbors.

None
include_self bool

Whether row i starts with i at distance zero. A kNN graph stores no such edge, but kneighbors and any exhaustive ground truth do, so the default keeps the two comparable.

True
return_distance bool

Whether to return distances alongside indices.

True

Returns:

Type Description
tuple[ndarray, ndarray] | ndarray

(distances, indices), or just indices when

tuple[ndarray, ndarray] | ndarray

return_distance is False. Rows the descent never filled are

tuple[ndarray, ndarray] | ndarray

padded with -1 indices and infinite distances, which the search

tuple[ndarray, ndarray] | ndarray

paths never produce.

NotFittedError

Bases: ValueError, AttributeError

Raised when a query is attempted before fit.

Inherits from both ValueError and AttributeError to match sklearn.exceptions.NotFittedError, so code catching either still works.