2010-10-06 40 views
4

我想使用scipy.spatial的KDTree在二維數組(基本上是嵌套列表的維度爲2的列表的列表)中查找最近鄰居對。我生成我的列表清單,將其管入numpy的數組中,然後創建KDTree實例。但是,每當我嘗試運行「查詢」時,我都不可避免地會得到奇怪的答案。例如,當我鍵入:使用scipy.spatial的數據類型問題

tree = KDTree(array) 
nearest = tree.query(np.array[1,1]) 

最近打印出(0.0,0)。目前,我使用的數組基本上y = x的範圍(1,50),所以我期望我應該得到(2,2)的最近鄰居爲(1,1)

什麼我做錯了,scipy大師?

編輯:另外,如果有人可以指向我的Python的KDTree包,他們已經用於給定點的最近鄰居搜索,我很想聽聽它。

回答

7

我之前使用過scipy.spatial,與scikits.ann相比,它似乎是一個不錯的改進(特別是接口)。

在這種情況下,我認爲你已經混淆了你的tree.query(...)呼叫的回報。從scipy.spatial.KDTree.querydocs

Returns 
------- 

d : array of floats 
    The distances to the nearest neighbors. 
    If x has shape tuple+(self.m,), then d has shape tuple if 
    k is one, or tuple+(k,) if k is larger than one. Missing 
    neighbors are indicated with infinite distances. If k is None, 
    then d is an object array of shape tuple, containing lists 
    of distances. In either case the hits are sorted by distance 
    (nearest first). 
i : array of integers 
    The locations of the neighbors in self.data. i is the same 
    shape as d. 

因此,在這種情況下,當您查詢就近[1,1]給你:

distance to nearest: 0.0 
index of nearest in original array: 0 

這意味着[1,1]是你的原始數據的第一行array,預計給您的數據是y = x on the range [1,50]

scipy.spatial.KDTree.query功能有很多其他選擇,所以例如,如果你想確保獲得近鄰本身不是嘗試:

tree.query([1,1], k=2) 

這將返回最近的鄰居,您可以應用更多的邏輯,以便在返回距離爲零的情況下(即查詢的點是用於構建樹的數據項之一),將採用第二個最近的鄰居而不是第一個。

+0

非常感謝。現在更有意義! – jlv 2010-10-06 19:39:46