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!
@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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With