【问题标题】:Data type problem using scipy.spatial使用 scipy.spatial 的数据类型问题
【发布时间】:2010-10-07 01:38:57
【问题描述】:

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

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

最近打印出 (0.0, 0)。目前,我使用的数组基本上是 y = x 的范围(1,50)所以我希望我应该得到(1,1)的(2,2)的最近邻居

我做错了什么,scipy 大师?

编辑:或者,如果有人可以将我指向 python 的 KDTree 包,他们已将其用于给定点的最近邻搜索,我很想听听。

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    我之前使用过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)
    

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

    【讨论】:

    • 非常感谢。现在更有意义了!
    猜你喜欢
    • 2011-08-31
    • 2021-04-24
    • 2012-03-03
    • 2020-05-25
    • 2010-12-24
    • 2018-10-27
    • 2011-06-01
    • 1970-01-01
    相关资源
    最近更新 更多