优化scipy最近邻搜索

ds_*_*ser 6 python nearest-neighbor scipy python-2.7 pysal

我试图找到距离1公里范围内的所有最近邻居.这是我构建树和搜索最近点的脚本,

from pysal.cg.kdtree import KDTree

def construct_tree(s):
    data_geopoints = [tuple(x) for x in s[['longitude','latitude']].to_records(index=False)]
    tree = KDTree(data_geopoints, distance_metric='Arc', radius=pysal.cg.RADIUS_EARTH_KM)
    return tree

def get_neighbors(s,tree):
    indices = tree.query_ball_point(s, 1)
    return indices

#Constructing the tree for search
tree = construct_tree(data)

#Finding the nearest neighbours within 1KM
data['neighborhood'] = data['lat_long'].apply(lambda row: get_neighbors(row,tree))
Run Code Online (Sandbox Code Playgroud)

从我在pysal页面上看到的内容,它说 -

kd-tree建立在scipy的kd-tree功能之上.如果使用scipy 0.12或更高版本使用scipy.spatial.cKDTree,否则使用scipy.spatial.KDTree.

在我的情况下,它应该使用cKDTree.这适用于样本数据集,但由于tree.query_ball_point返回索引列表作为结果.每个列表将包含100个元素.对于我的数据点(200万条记录),这种情况越来越大,并且由于某些点后的内存问题而停止.关于如何解决这个问题的任何想法?

ds_*_*ser 0

以防万一,如果有人寻找这个问题的答案,我已经通过找到一个组的最近邻居(tree.query_ball_point可以处理批次)并写入数据库然后处理下一个组来解决它,而不是将所有内容都保留在内存中。谢谢。