x、y坐标系numpy数组中最近点索引的求法

2024-06-28 20:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个2d numpy数组:x_数组包含x方向的位置信息,y_数组包含y方向的位置。

然后我有一长串的x,y点。

对于列表中的每个点,我需要找到最接近该点的位置(在数组中指定)的数组索引。

基于这个问题,我天真地生成了一些有效的代码: Find nearest value in numpy array

import time
import numpy

def find_index_of_nearest_xy(y_array, x_array, y_point, x_point):
    distance = (y_array-y_point)**2 + (x_array-x_point)**2
    idy,idx = numpy.where(distance==distance.min())
    return idy[0],idx[0]

def do_all(y_array, x_array, points):
    store = []
    for i in xrange(points.shape[1]):
        store.append(find_index_of_nearest_xy(y_array,x_array,points[0,i],points[1,i]))
    return store


# Create some dummy data
y_array = numpy.random.random(10000).reshape(100,100)
x_array = numpy.random.random(10000).reshape(100,100)

points = numpy.random.random(10000).reshape(2,5000)

# Time how long it takes to run
start = time.time()
results = do_all(y_array, x_array, points)
end = time.time()
print 'Completed in: ',end-start

我是在一个大数据集上做这个的,我真的想加快一点。 有人能优化这个吗?

谢谢。


更新:解决方案遵循@silvado和@justin的建议(如下)

# Shoe-horn existing data for entry into KDTree routines
combined_x_y_arrays = numpy.dstack([y_array.ravel(),x_array.ravel()])[0]
points_list = list(points.transpose())


def do_kdtree(combined_x_y_arrays,points):
    mytree = scipy.spatial.cKDTree(combined_x_y_arrays)
    dist, indexes = mytree.query(points)
    return indexes

start = time.time()
results2 = do_kdtree(combined_x_y_arrays,points_list)
end = time.time()
print 'Completed in: ',end-start

上面的代码将我的代码(在100x100矩阵中搜索5000个点)提高了100倍。有趣的是,使用scipy.spatial.KDTree(而不是scipy.spatial.cKDTree)提供了与我的原始解决方案相当的时间,因此使用cKDTree版本绝对值得。。。


Tags: 代码innumpytimerandom数组arraydo
3条回答

下面是一个scipy.spatial.KDTree示例

In [1]: from scipy import spatial

In [2]: import numpy as np

In [3]: A = np.random.random((10,2))*100

In [4]: A
Out[4]:
array([[ 68.83402637,  38.07632221],
       [ 76.84704074,  24.9395109 ],
       [ 16.26715795,  98.52763827],
       [ 70.99411985,  67.31740151],
       [ 71.72452181,  24.13516764],
       [ 17.22707611,  20.65425362],
       [ 43.85122458,  21.50624882],
       [ 76.71987125,  44.95031274],
       [ 63.77341073,  78.87417774],
       [  8.45828909,  30.18426696]])

In [5]: pt = [6, 30]  # <-- the point to find

In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point 
Out[6]: array([  8.45828909,  30.18426696])

#how it works!
In [7]: distance,index = spatial.KDTree(A).query(pt)

In [8]: distance # <-- The distances to the nearest neighbors
Out[8]: 2.4651855048258393

In [9]: index # <-- The locations of the neighbors
Out[9]: 9

#then 
In [10]: A[index]
Out[10]: array([  8.45828909,  30.18426696])

如果您可以将数据转换为正确的格式,一个快速的方法是使用scipy.spatial.distance中的方法:

http://docs.scipy.org/doc/scipy/reference/spatial.distance.html

尤其是pdistcdist提供了快速计算成对距离的方法。

scipy.spatial还有一个k-d树实现:^{}

该方法一般是先利用点数据建立k-d树。它的计算复杂度为N logn,其中N是数据点的数目。范围查询和近邻搜索可以用log N复杂度完成。这比简单地遍历所有点(复杂度N)要高效得多。

因此,如果有重复的范围或最近邻查询,强烈建议使用k-d树。

相关问题 更多 >