2015-09-06 154 views
6

我有一個很大的x和y座標列表,存儲在numpy數組中。在特定距離內查找所有最近的鄰居

Coordinates = [[ 60037633 289492298] 
[ 60782468 289401668] 
[ 60057234 289419794]] 
... 
... 

我要的是找出一個特定距離內的所有的近鄰(可以說3米)和存儲結果,這樣我以後可以做的結果進一步的分析。

對於大多數軟件包,我發現有必要確定應該找到多少個神經網絡,但我只希望在設定的距離內。

我該如何實現這樣的目標,以及如何爲大數據集(幾百萬個點)實現類似的最快和最好的方法?

+2

你有沒有試圖自己做到這一點呢?你的代碼現在是什麼樣的?你能舉一個你想要計算什麼的例子(即3米是什麼意思)?這些GPS座標? – reynoldsnlp

+0

'從SciPy的進口空間 myTreeName = spatial.cKDTree(座標,leafsize = 100)在座標 爲項: TheResult = myTreeName.query(項目中,k = 20,distance_upper_bound = 3)' 是我之前,但嘗試過在這裏我必須指定我想找到多少個最近的鄰居。是的,這些都是GPS座標(X,Y),我想爲數據集中的每個點找到半徑爲3米範圍內的所有NN。 – Kitumijasi

回答

9

你可以使用一個scipy.spatial.cKDTree

import numpy as np 
import scipy.spatial as spatial 
points = np.array([(1, 2), (3, 4), (4, 5)]) 
point_tree = spatial.cKDTree(points) 
# This finds the index of all points within distance 1 of [1.5,2.5]. 
print(point_tree.query_ball_point([1.5, 2.5], 1)) 
# [0] 

# This gives the point in the KDTree which is within 1 unit of [1.5, 2.5] 
print(point_tree.data[point_tree.query_ball_point([1.5, 2.5], 1)]) 
# [[1 2]] 

# More than one point is within 3 units of [1.5, 1.6]. 
print(point_tree.data[point_tree.query_ball_point([1.5, 1.6], 3)]) 
# [[1 2] 
# [3 4]] 

這裏是你展示如何 找到所有最近的鄰居點的數組,一個電話 到point_tree.query_ball_point一個例子:

import numpy as np 
import scipy.spatial as spatial 
import matplotlib.pyplot as plt 
np.random.seed(2015) 

centers = [(1, 2), (3, 4), (4, 5)] 
points = np.concatenate([pt+np.random.random((10, 2))*0.5 
         for pt in centers]) 
point_tree = spatial.cKDTree(points) 

cmap = plt.get_cmap('copper') 
colors = cmap(np.linspace(0, 1, len(centers))) 
for center, group, color in zip(centers, point_tree.query_ball_point(centers, 0.5), colors): 
    cluster = point_tree.data[group] 
    x, y = cluster[:, 0], cluster[:, 1] 
    plt.scatter(x, y, c=color, s=200) 

plt.show() 

enter image description here

+1

我相信建議使用['spatial.cKDTree'](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html)。 (我相信唯一的區別是實現...行爲和界面是相同的。) – askewchan

+0

感謝您的更正,@askewchan。 'cKDTree'應該更快。 – unutbu

+0

也許現在如果我想讓你的查詢很多或點我怎麼能存儲找到最近點與查詢點?因此,在你的例子是這樣的: '(1.5:1 2) (1.6:3 4)' 一樣具有一定的折射率,字典或元組或類似的東西? – Kitumijasi