API Reference / base /

neighbors.py

Base class for nearest neighbor search algorithms.

Defines the common interface (build/query) shared by search strategies such as brute force, KD-tree, and Ball-tree.

Classes

NearestNeighborSearch

class base.neighbors.NearestNeighborSearch(ABC)

Abstract base class for nearest neighbor search algorithms.

Provides a common interface for different search strategies like brute force, KD-tree, Ball-tree, etc.
Constructor
__init__(
    self,
)

Attributes

X_
np.ndarray of shape (n_samples, n_features)
Training data (set by build()).
n_samples_
int
Number of training samples.
n_features_
int
Number of features.

Methods

__init__ (self)

Initialize the search algorithm.

build (self, X: np.ndarray) -> 'NearestNeighborSearch'

Build the search structure from training data.

Parameters
X
np.ndarray of shape (n_samples, n_features)
Training data.
Returns
self
NearestNeighborSearch
The built search structure, for method chaining.
query (self, x: np.ndarray, k: int=1) -> Tuple[np.ndarray, np.ndarray]

Find the k nearest neighbors of a single query point.

Parameters
x
np.ndarray of shape (n_features,)
Query point.
k
int = 1
Number of neighbors to find.
Returns
distances
np.ndarray of shape (k,)
Distance to each neighbor.
indices
np.ndarray of shape (k,)
Index of each neighbor in the training data.
query_batch (self, X: np.ndarray, k: int=1) -> Tuple[np.ndarray, np.ndarray]

Find the k nearest neighbors of multiple query points.

Parameters
X
np.ndarray of shape (n_queries, n_features)
Query points.
k
int = 1
Number of neighbors to find.
Returns
distances
np.ndarray of shape (n_queries, k)
Distance to each neighbor for each query.
indices
np.ndarray of shape (n_queries, k)
Index of each neighbor in the training data.
query_radius (self, x: np.ndarray, radius: float) -> Tuple[np.ndarray, np.ndarray]

Find all neighbors within a given radius.

Parameters
x
np.ndarray of shape (n_features,)
Query point.
radius
float
Maximum distance.
Returns
distances
np.ndarray
Distances to the neighbors within radius.
indices
np.ndarray
Indices of the neighbors within radius.
euclidean_distance (x1: np.ndarray, x2: np.ndarray) -> float

Compute the Euclidean distance between two points.

Parameters
x1
np.ndarray of shape (n_features,)
First point.
x2
np.ndarray of shape (n_features,)
Second point.
Returns
distance
float
Euclidean distance :math:`\sqrt{\sum_i (x_{1i} - x_{2i})^2}`.
euclidean_distance_squared (x1: np.ndarray, x2: np.ndarray) -> float

Compute the squared Euclidean distance (faster, avoids the square root).

Parameters
x1
np.ndarray of shape (n_features,)
First point.
x2
np.ndarray of shape (n_features,)
Second point.
Returns
distance
float
Squared Euclidean distance between the points.
__repr__ (self) -> str

Return string representation of the search structure.