← retour aux snippets

sklearn: NearestNeighbors (brute/kd/ball)

Recherche des plus proches voisins avec différents algorithmes.

objectif

Recherche des plus proches voisins avec différents algorithmes.

code minimal

from sklearn.neighbors import NearestNeighbors
import numpy as np

X = np.array([[0,0],[1,1],[1,0]])
for algo in ["auto","brute","kd_tree","ball_tree"]:
    nn = NearestNeighbors(n_neighbors=2, algorithm=algo).fit(X)
print(True)

utilisation

from sklearn.neighbors import NearestNeighbors
d, i = NearestNeighbors(n_neighbors=2).fit(X).kneighbors(X[:1])
print(d.shape, i.shape)

variante(s) utile(s)

from sklearn.neighbors import NearestNeighbors
g = NearestNeighbors(radius=1.5).fit(X)
print(len(g.radius_neighbors([[0,0]], return_distance=False)[0]) >= 1)

notes

  • kd_tree/ball_tree utiles en dimension modérée.