Python skicit-learn k-nearest neighbors – 3d distance matrix ( Python, Scikit Learn )

Problem :
( Scroll to solution )

I’m working on the distances of thousands sphere shaped objects in a 3D environment. I used numpy to create a distance matrix between the spheres and would initially like to pick out certain distances, e.g. the nearest 5, of all objects within the 3D environment before using k-nearest algorithms. Is there any package which works like the kneighbors output using index and value without using k-nearest algorithms? The input is a precomputed distance matrix containing all distances per sphere to all other objects.

You can use a pre-computed distance matrix as your input to sklearn’s neighbours.NearestNeighbors by setting the metrics parameter as “precomputed”

Lets create a dummy distance matrix between 6 points in some 3D space (or any dimensional space).

from sklearn.neighbors import NearestNeighbors

#Distance matrix from numpy (dummy)
precomputed_distances = np.random.random((6,6)) 

#Get top 5 neighbours from precomputed distance matrix
nn = NearestNeighbors(n_neighbors=5, metric="precomputed")
nn.fit(precomputed_distances)

#Fetch kneighbors
distances, indexes = nn.kneighbors()

print(indexes)
print('')
print(distances)
#neighbours indexes
[[2 5 3 1 4]
 [0 4 3 2 5]
 [5 3 0 1 4]
 [1 2 4 0 5]
 [3 1 2 5 0]
 [3 2 0 1 4]]

#distances
[[0.07355072 0.30327092 0.32645641 0.54227088 0.76145093]
 [0.06451358 0.13867276 0.7570105  0.84383876 0.92184049]
 [0.52953184 0.59474913 0.63211483 0.80958676 0.99361867]
 [0.10885239 0.31822021 0.39327313 0.47670755 0.6764581 ]
 [0.18309627 0.69483384 0.74029263 0.82705113 0.92923248]
 [0.28584336 0.42956108 0.43323451 0.64124948 0.90154176]]

Read more about this here.

Read more here: Source link