我之前使用过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)
这将返回 两个 最近的邻居,您可以将进一步的逻辑应用于返回距离为零的情况(即查询的点是用于构建树的数据项之一)取第二个最近的邻居而不是第一个。