Implementation:Scikit learn Scikit learn KNeighborsGraph
| Knowledge Sources | |
|---|---|
| Domains | Machine Learning, Graph Construction |
| Last Updated | 2026-02-08 15:00 GMT |
Overview
Concrete tool for computing k-nearest neighbors graphs and transformer classes provided by scikit-learn.
Description
This module provides the kneighbors_graph function and the KNeighborsTransformer and RadiusNeighborsTransformer classes for computing weighted graphs of nearest neighbors. The kneighbors_graph function computes a sparse graph representing the k-nearest neighbors connectivity or distance for each point. The transformer classes wrap this functionality into scikit-learn's transformer API, producing sparse matrices suitable for pipeline integration.
Usage
Use kneighbors_graph or KNeighborsTransformer when you need to construct a nearest neighbor graph for downstream tasks such as spectral clustering, manifold learning, or graph-based semi-supervised learning.
Code Reference
Source Location
- Repository: scikit-learn
- File: sklearn/neighbors/_graph.py
Signature
def kneighbors_graph(
X,
n_neighbors,
*,
mode="connectivity",
metric="minkowski",
p=2,
metric_params=None,
include_self=False,
n_jobs=None,
):
class KNeighborsTransformer(
ClassNamePrefixFeaturesOutMixin, KNeighborsMixin, TransformerMixin, NeighborsBase
):
def __init__(
self,
*,
mode="distance",
n_neighbors=5,
algorithm="auto",
leaf_size=30,
metric="minkowski",
p=2,
metric_params=None,
n_jobs=None,
):
Import
from sklearn.neighbors import kneighbors_graph, KNeighborsTransformer
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| X | array-like or sparse matrix | Yes | Input data of shape (n_samples, n_features) or a fitted NearestNeighbors object |
| n_neighbors | int | Yes | Number of neighbors for each sample |
| mode | str | No | Type of returned matrix: 'connectivity' or 'distance' (default='connectivity') |
| metric | str or callable | No | Distance metric to use (default='minkowski') |
| p | float | No | Power parameter for Minkowski metric (default=2) |
| metric_params | dict or None | No | Additional keyword arguments for the metric function |
| include_self | bool or str | No | Whether to mark each sample as its own neighbor (default=False) |
| n_jobs | int or None | No | Number of parallel jobs |
Outputs
| Name | Type | Description |
|---|---|---|
| A | sparse matrix of shape (n_samples, n_samples) | Graph where A[i, j] gives the weight of the edge connecting i to j (connectivity=1 or distance value) |
Usage Examples
Basic Usage
from sklearn.neighbors import kneighbors_graph
import numpy as np
X = np.array([[0, 0], [1, 1], [2, 2], [3, 3]])
A = kneighbors_graph(X, n_neighbors=2, mode="connectivity", include_self=False)
print(A.toarray())