使用scipy.spatial的数据类型问题

jlv*_*jlv 6 python numpy scipy

我想使用scipy.spatial的KDTree来查找二维数组中的最近邻居对(本质上是嵌套列表的维度为2的列表列表).我生成我的列表列表,将其输入numpy的数组,然后创建KDTree实例.但是,每当我尝试对其运行"查询"时,我都不可避免地会得到奇怪的答案.例如,当我输入:

tree = KDTree(array)
nearest = tree.query(np.array[1,1])
Run Code Online (Sandbox Code Playgroud)

最近打印出来(0.0,0).目前,我正在使用一个基本上y = x的数组作为范围(1,50)所以我希望我得到(2,1)的最近邻居(1,1)

我做错了什么,狡猾的大师?

编辑:或者,如果有人可以指向我的python的KDTree包,他们已经用于最近邻搜索给定点,我很乐意听到它.

dtl*_*ier 9

我之前使用scipy.spatial过,与之相比,它似乎是一个很好的改进(尤其是接口)scikits.ann.

在这种情况下,我认为你已经混淆了tree.query(...)通话的回报.来自scipy.spatial.KDTree.query 文档:

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.
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下,当你查询离[1,1]你最近的时候:

distance to nearest: 0.0
index of nearest in original array: 0
Run Code Online (Sandbox Code Playgroud)

这意味着这[1,1]是您原始数据的第一行array,这是您的数据所期望的y = x on the range [1,50].

scipy.spatial.KDTree.query函数有很多其他选项,因此,例如,如果您想确保获取本身不是最近的邻居,请尝试:

tree.query([1,1], k=2)
Run Code Online (Sandbox Code Playgroud)

这将返回两个最近的邻居,您可以应用进一步的逻辑,以便返回的距离为零(即查询的点是用于构建树的数据项之一)第二个最近邻居被采用而不是第一个.