kd tree python 搜索

来源:互联网 发布:翻译机 知乎 编辑:程序博客网 时间:2024/05/21 05:24

海量数据最近邻查找可以用kd tree

目前理解,kd tree需要的数据维度相同,否则会出问题

kd tree实现:https://github.com/stefankoegl/kdtree

下面是测试代码:

import kdtree# Create an empty tree by specifying the number of# dimensions its points will haveemptyTree = kdtree.create(dimensions=3)# A kd-tree can contain different kinds of points, for example tuplespoint1 = (2, 3, 4)point2 = [4, 5, 6]import collectionsPoint = collections.namedtuple('Point', 'x y z')point3 = Point(5, 3, 2)tree = kdtree.create([point1, point2, point3])# Each (sub)tree is represented by its root nodetree.add((5, 4, 3))tree = tree.remove((5, 4, 3))print(list(tree.inorder()))# [<KDNode - (2, 3, 4)>, <KDNode - [4, 5, 6]>, <KDNode - Point(x=5, y=3, z=2)>]## # Retrieving the Tree in level orderprint(list(kdtree.level_order(tree)))# [<KDNode - [4, 5, 6]>, <KDNode - (2, 3, 4)>, <KDNode - Point(x=5, y=3, z=2)>]## # Find the nearest node to the location (1, 2, 3)print(tree.search_nn((1, 2, 3)))