我有两个 2d numpy 数组: x_array 包含 x 方向的位置信息, y_array 包含 y 方向的位置。
然后,我有一长串 x,y 点。
对于列表中的每个点,我需要找到最接近该点的位置(在数组中指定)的数组索引。
基于这个问题,我天真地制作了一些有效的代码: Find nearest value in numpy array
IE
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 版本......