Python 在二维数组中查找到最近邻的距离

Python 在二维数组中查找到最近邻的距离,python,numpy,scipy,nearest-neighbor,euclidean-distance,Python,Numpy,Scipy,Nearest Neighbor,Euclidean Distance,我有一个2D数组,我想为每个(x,y)点尽可能快地找到到其最近邻居的距离 我可以使用以下方法进行此操作: 这是可行的,但我觉得它太多的工作,应该能够处理这一点,但我不知道如何。我对最近邻居的坐标不感兴趣,我只想知道距离(并尽可能快)。KDTree可以做到这一点。该过程与使用cdist时几乎相同。但是cdist要快得多。正如评论中指出的,cKDTree的速度更快: import numpy as np from scipy.spatial.distance import cdist from sc

我有一个2D数组,我想为每个
(x,y)
点尽可能快地找到到其最近邻居的距离

我可以使用以下方法进行此操作:


这是可行的,但我觉得它太多的工作,应该能够处理这一点,但我不知道如何。我对最近邻居的坐标不感兴趣,我只想知道距离(并尽可能快)。

KDTree可以做到这一点。该过程与使用cdist时几乎相同。但是cdist要快得多。正如评论中指出的,cKDTree的速度更快:

import numpy as np
from scipy.spatial.distance import cdist
from scipy.spatial import KDTree
from scipy.spatial import cKDTree
import timeit

# Random data
data = np.random.uniform(0., 1., (1000, 2))

def scipy_method():
    # Distance between the array and itself
    dists = cdist(data, data)
    # Sort by distances
    dists.sort()
    # Select the 1st distance, since the zero distance is always 0.
    # (distance of a point with itself)
    nn_dist = dists[:, 1]
    return nn_dist

def KDTree_method():
    # You have to create the tree to use this method.
    tree = KDTree(data)
    # Then you find the closest two as the first is the point itself
    dists = tree.query(data, 2)
    nn_dist = dists[0][:, 1]
    return nn_dist

def cKDTree_method():
    tree = cKDTree(data)
    dists = tree.query(data, 2)
    nn_dist = dists[0][:, 1]
    return nn_dist

print(timeit.timeit('cKDTree_method()', number=100, globals=globals()))
print(timeit.timeit('scipy_method()', number=100, globals=globals()))
print(timeit.timeit('KDTree_method()', number=100, globals=globals()))
输出:

0.34952507635557595
7.904083715193579
20.765962179145546

再一次,证明C是很棒的,这是非常不必要的

那么,你为什么不继续尝试一下cKDTree呢?这只是几行代码。我没有想到尝试
cKDTree
。我要试一试。哇,这在运行时有很大的不同。我只是假设
KDTree
会快得多,不知道为什么。谢谢@Akaisteph7!我听从了Paul的建议,尝试了
cKDTree
而不是
KDTree
(只需更改上面代码中的两个字母),它比
cdist
快几个数量级。
0.34952507635557595
7.904083715193579
20.765962179145546