Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding nearest neighbor for python numpy.ndarray in 3d-space

I have a numpy.ndarray of 3d-points, i.e. the np.shape of it is (4350,3) and such a second numpy.ndarray of 3d-points of np.shape (10510,3). Now I am trying to find the right python-package to calculate the nearest neighbors in the second array of the points in the first array as quickly as possible.

I've found a quite similar question here: find the k nearest neighbours of a point in 3d space with python numpy but I don't understand how to use the solution there for my problem.

I'd very, very much appreciate your help on this!

like image 540
Studentu Avatar asked Jan 09 '19 16:01

Studentu


People also ask

Is there a way to find the nearest neighbor?

@Victor'Chris'Cabral No, what I've implemented so far is finding the nearest neighbor through calculating the euclidean distance for each point of the first set for each point of the second one (4350*10510 = 45718500 times) and returning the points for the closest distances.

How to find the nearest value of an array in NumPy?

Take an array, say, arr [] and an element, say x to which we have to find the nearest value. Call the numpy.abs (d) function, with d as the difference between element of array and x, and store the values in a difference array, say difference_array []. The element, providing minimum difference will be the nearest to the specified value.

What is the k-nearest neighbors algorithm in Python?

In this tutorial, you’ll get a thorough introduction to the k-Nearest Neighbors (kNN) algorithm in Python. The kNN algorithm is one of the most famous machine learning algorithms and an absolute must-have in your machine learning toolbox.

How do you make a k-nearest neighbor model in Python?

The k-nearest neighbor algorithm is imported from the scikit-learn package. Create feature and target variables. Split data into training and test data. Generate a k-NN model using neighbors value. Train or fit the data into the model. Predict the future.


1 Answers

Here is the KDTree way :

from scipy.spatial import KDTree

data= np.random.rand(10510,3)
sample= np.random.rand(4350,3)
kdtree=KDTree(data)

Then dist,points=kdtree.query(sample,2) will give you the 2 best neighbors for the 4350 candidates in about one second.

like image 187
B. M. Avatar answered Sep 22 '22 05:09

B. M.