Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Scikit-Learn · Class

NearestNeighbors

NearestNeighbors is an unsupervised estimator for finding nearby samples in a fitted dataset. It supports fixed-count and radius-based queries with configurable search algorithms and distance metrics.

How it works

After fitting on feature vectors, the estimator searches the stored data for either a fixed number of closest points or all points within a radius. It can choose among brute force, BallTree, and KDTree strategies, while the metric and its parameters determine distance calculations.

Syntax

class sklearn.neighbors.NearestNeighbors(*, n_neighbors=5, radius=1.0, algorithm='auto', leaf_size=30, metric='minkowski', p=2, metric_params=None, n_jobs=None)

Parameters

NameTypeDescription
n_neighborsint, default=5Number of neighbors returned by default for fixed-count queries.
radiusfloat, default=1.0Radius used by default for range queries.
algorithm{'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'Search strategy: auto, ball_tree, kd_tree, or brute.
leaf_sizeint, default=30Leaf size passed to tree-based structures.
metricstr or callable, default='minkowski'Distance metric used for neighbor searches.
pfloat, default=2Power parameter for the Minkowski metric.
metric_paramsdict, default=NoneAdditional keyword arguments for the metric function.
n_jobsint, default=NoneNumber of parallel jobs; None means the library default.

Returns

A fitted NearestNeighbors estimator; query methods return neighbor distances and indices or range-neighbor results.

Key points

  • Use the class when you need neighbor lookup without fitting a predictive target model.
  • The algorithm option exposes BallTree and KDTree implementations in addition to brute-force search.
  • The default automatic mode selects a search approach based on the fitted data and parameter values.
  • kneighbors supports fixed-k queries and returns the neighboring sample information for each query point.
  • radius_neighbors supports range queries whose result count varies with local point density.

Common mistakes

  • Different algorithms can have different performance characteristics; select the strategy through algorithm or leave it at auto.
  • The automatic strategy makes its choice when fit is called, so the selected method depends on the fitted data and configuration.
  • Radius queries can return a variable number of neighbors rather than the fixed count used by kneighbors.

Example: Find nearest points

import numpy as np
from sklearn.neighbors import NearestNeighbors

X = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 2.0], [3.0, 3.0]])
queries = np.array([[0.2, 0.1]])

model = NearestNeighbors(n_neighbors=2).fit(X)
distances, indices = model.kneighbors(queries)
print(indices)
print(distances)

Fits a neighbor-search structure on training points, then returns the two closest training-point indices and their distances for a query point.

When to use it

Fixed-k similarity lookup

Retrieve the k closest reference samples for each query vector.

Radius or density neighborhood search

Find every reference sample within a distance threshold.

Neighbor graph preparation

Construct a reusable neighbor index for downstream unsupervised workflows.

Interview questions

QWhat does NearestNeighbors do?

NearestNeighbors is an unsupervised estimator for searching neighboring samples. Fit stores the reference dataset, and kneighbors returns distances and indices for the closest samples to query points.

Follow-up: How would you retrieve density-based neighborhoods? Use radius_neighbors, which returns samples lying within a specified radius around each query point.

QHow is the neighbor-search algorithm selected?

The algorithm parameter accepts auto, ball_tree, kd_tree, or brute. auto attempts to choose an appropriate method from the values supplied to fit.

Follow-up: When would a tree method be unsuitable? High-dimensional data can reduce the practical advantage of tree partitioning, making brute-force comparison a reasonable alternative.

QHow do kneighbors and radius_neighbors differ?

The estimator supports fixed-count and radius-based searches. kneighbors finds a requested number of closest samples, while radius_neighbors finds every sample within the supplied radius.

Follow-up: What determines the returned distances? The metric, p, and optional metric_params configure how distances are computed.

  • BallTree
  • KDTree
  • KNeighborsClassifier
  • RadiusNeighborsClassifier

Source: NearestNeighbors — scikit-learn 1.9.1 documentation. Checked 2026-10-15.