2010-10-06 103 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