두 개의 2d numpy 배열이 있습니다. x_array는 x 방향의 위치 정보를 포함하고 y_array는 y 방향의 위치를 포함합니다.
그런 다음 x, y 포인트의 긴 목록이 있습니다.
목록의 각 지점에 대해 해당 지점에 가장 가까운 위치 (배열에 지정됨)의 배열 인덱스를 찾아야합니다.
이 질문을 기반으로 작동하는 일부 코드를 순진하게 생성
했습니다 .numpy 배열에서 가장 가까운 값 찾기
즉
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
위의 코드는 내 코드 (100×100 행렬에서 5000 개의 포인트 검색)를 100 배까지 가속화했습니다. 흥미롭게도, 사용 scipy.spatial.KDTree (대신 scipy.spatial.cKDTree는 ) 그래서이 cKDTree 버전을 사용하여 확실히 가치가있다, 내 순진 솔루션 비교 타이밍을 준 …
답변
scipy.spatial
또한 kd 트리 구현이 있습니다 : scipy.spatial.KDTree
.
접근 방식은 일반적으로 먼저 포인트 데이터를 사용하여 kd 트리를 구축하는 것입니다. 그것의 계산 복잡도는 N log N 정도이며, 여기서 N은 데이터 포인트의 수입니다. 그러면 범위 쿼리와 최근 접 이웃 검색이 log N 복잡도로 수행 될 수 있습니다. 이것은 단순히 모든 지점을 순환하는 것보다 훨씬 효율적입니다 (복잡성 N).
따라서 반복되는 범위 또는 최근 접 이웃 쿼리가있는 경우 kd 트리를 사용하는 것이 좋습니다.
답변
여기에 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
특히 pdist
와 cdist
계산 페어 거리 빠른 방법을 제공합니다.