【问题标题】:Why sklearn.neighbors.KDTree.query_radius does not return indices as integers?为什么 sklearn.neighbors.KDTree.query_radius 不将索引作为整数返回?
【发布时间】:2022-01-13 22:40:51
【问题描述】:

我正在使用 KDTree 结构进行球形邻居研究。我使用sklearn.neigbors.KDTree中的query_radius方法

在文档here 上,它说索引作为“对象”类型返回。究竟是什么意思?我可以将它们转换为整数吗?为什么query 方法不是这样(索引以整数形式返回)?

这是我的代码的重要部分:

import numpy as np
from sklearn.neighbors import KDTree

def kdtree_spherical(queries, supports, radius, leaf_size=40):

    supports_tree = KDTree(supports, leaf_size=leaf_size)
    ind = supports_tree.query_radius(queries, r=radius, return_distance=False)
    
    return supports[ind]

# Define the search parameters
points = ... # array of size N*3, N is very big basically

neighbors_num = 100
radius = 0.2
num_queries = 1000

random_indices = np.random.choice(points.shape[0], num_queries, replace=False)
queries = points[random_indices, :]

# Search spherical
neighborhoods = kdtree_spherical(queries, points, radius)

出现以下错误

Traceback (most recent call last):
  File "neighborhoods.py", line 178, in <module>
    neighborhoods = kdtree_spherical(queries, points, radius, leaf_size)
  File "neighborhoods.py", line 79, in kdtree_spherical
    return supports[ind]
IndexError: arrays used as indices must be of integer (or boolean) type

【问题讨论】:

    标签: python scikit-learn kdtree


    【解决方案1】:

    使用此方法,您试图在queries 中的每个点周围找到最近的邻居; queries 包含一些点,因此,它将得到一个包含索引数组的数组(每个数组都是int64 类型),对应于queries 中的每个点。由于指定半径内的点周围的稀疏度不同,这些数组的大小不同(数组大小有不同的形状)。因此,包含这些索引数组的主数组必须是 object 类型(一个对象类型的数组可以包含不同大小或形状的数组;这种类型的数组需要进一步的向量化操作和...... )。
    现在,解决此问题的一个最简单的解决方案是循环主数组中的每个索引数组。所以函数必须修改为:

    def kdtree_spherical(queries, supports, radius, leaf_size=40):
        supports_tree = KDTree(supports, leaf_size=leaf_size)
        print(type(supports_tree))
        ind = supports_tree.query_radius(queries, r=radius, return_distance=False)
    
        # The changing section
        resulted_array = []
        for i in range(len(queries)):
            resulted_array.append(supports[ind[i]])
    
        return np.array(resulted_array, dtype=object)
    

    它也可以以矢量化方式处理,但我认为循环在这方面是最好的,就可能的内存泄漏或其他此类问题而言。

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 2014-12-02
      • 2014-06-05
      • 2013-04-14
      • 2018-06-12
      • 2012-05-28
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多