Implementation:Scikit learn Scikit learn NearestNeighbors
| Knowledge Sources | |
|---|---|
| Domains | Machine Learning, Nearest Neighbors |
| Last Updated | 2026-02-08 15:00 GMT |
Overview
Concrete tool for performing unsupervised nearest neighbor searches, provided by scikit-learn.
Description
The NearestNeighbors class is an unsupervised learner that implements neighbor searches. It provides both k-nearest neighbor queries (kneighbors) and radius-based neighbor queries (radius_neighbors). It supports multiple algorithms (ball_tree, kd_tree, brute force), various distance metrics, and can handle both dense and sparse input data.
Usage
Use this class when you need to find nearest neighbors in an unsupervised setting, such as for building neighborhood graphs, performing local density estimation, or as a building block for other neighbor-based algorithms.
Code Reference
Source Location
- Repository: scikit-learn
- File: sklearn/neighbors/_unsupervised.py
Signature
class NearestNeighbors(KNeighborsMixin, RadiusNeighborsMixin, NeighborsBase):
def __init__(
self,
*,
n_neighbors=5,
radius=1.0,
algorithm="auto",
leaf_size=30,
metric="minkowski",
p=2,
metric_params=None,
n_jobs=None,
):
Import
from sklearn.neighbors import NearestNeighbors
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| n_neighbors | int | No | Number of neighbors for kneighbors queries (default 5) |
| radius | float | No | Range for radius_neighbors queries (default 1.0) |
| algorithm | str | No | Algorithm: 'auto', 'ball_tree', 'kd_tree', or 'brute' (default 'auto') |
| leaf_size | int | No | Leaf size for BallTree or KDTree (default 30) |
| metric | str or callable | No | Distance metric (default 'minkowski') |
| p | float | No | Power parameter for Minkowski metric (default 2, i.e. Euclidean) |
| n_jobs | int or None | No | Number of parallel jobs for neighbor search (default None) |
Outputs
| Name | Type | Description |
|---|---|---|
| distances | ndarray of shape (n_queries, n_neighbors) | Distances to the nearest neighbors |
| indices | ndarray of shape (n_queries, n_neighbors) | Indices of the nearest neighbors in the training data |
Usage Examples
Basic Usage
from sklearn.neighbors import NearestNeighbors
import numpy as np
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
nn = NearestNeighbors(n_neighbors=2)
nn.fit(X)
distances, indices = nn.kneighbors([[2, 3]])
print(indices) # [[0 1]]
print(distances) # nearest neighbor distances