k-nn、radius邻近查找作业:

本文这套代码是开源的,来自黎嘉信老师的github.

import random
import math
import  numpy as npfrom result_set import  KNNResultSet,RadiusNNResultSetclass Node:                          #节点,每一个数都是一个分支节点def __init__(self,key,value=-1):self.left = Noneself.right = Noneself.key =keyself.value = value      #value可以用作储存其他数值,譬如点原来的序号def __str__(self):return "key: %s, value: %s" % (str(self.key), str(self.value))def insert(root,key,value=-1):    #构建二叉树if root is None:root = Node(key,value)      #赋初值else:if key < root.key:root.left = insert(root.left,key,value)   #小数放左边elif key > root.key:root.right = insert(root.right,key,value)  #大数放右边else:   # don't insert if key already exist in the treepassreturn  root#二叉树的三种应用
def inorder(root):# Inorder (Left, Root, Right)if root is not None:inorder(root.left)print(root)inorder(root.right)def preorder(root):# Preorder (Root, Left, Right)if root is not None:print(root)preorder(root.left)preorder(root.right)def postorder(root):# Postorder (Left, Right, Root)if root is not None:postorder(root.left)postorder(root.right)print(root)def knn_search(root:Node,result_set:KNNResultSet,key):if root is None:return False# compare the root itselfresult_set.add_point(math.fabs(root.key - key),root.value)       #计算worst_dist ,并把当前root.value(index二叉树)里的值加入到resut_set 中if result_set.worstDist() == 0:return Trueif root.key >= key:# iterate left branch firstif knn_search(root.left, result_set, key):return Trueelif math.fabs(root.key-key) < result_set.worstDist():return knn_search(root.right, result_set, key)return Falseelse:# iterate right branch firstif knn_search(root.right, result_set, key):return Trueelif math.fabs(root.key-key) < result_set.worstDist():return knn_search(root.left, result_set, key)return Falsedef radius_search(root: Node, result_set: RadiusNNResultSet, key):if root is None:return False# compare the root itselfresult_set.add_point(math.fabs(root.key - key), root.value)if root.key >= key:# iterate left branch firstif radius_search(root.left, result_set, key):return Trueelif math.fabs(root.key-key) < result_set.worstDist():return radius_search(root.right, result_set, key)return Falseelse:# iterate right branch firstif radius_search(root.right, result_set, key):return Trueelif math.fabs(root.key-key) < result_set.worstDist():return radius_search(root.left, result_set, key)return Falsedef search_recursively(root,key):               #1NN 搜索 ,递归法if root is None or root.key == key:return rootif key < root.key:return search_recursively(root.left,key)elif key > root.key:return search_recursively(root.right,key)def search_iterative(root, key):                #1NN 搜索 ,循环判断current_node = rootwhile current_node is not None:if current_node.key == key:return current_nodeelif key < current_node.key:current_node = current_node.leftelif key > current_node.key:current_node = current_node.rightreturn current_nodedef main():# Data generationdb_size = 100k = 5    #搜寻5个点radius = 2.0data = np.random.permutation(db_size).tolist()   #random.permutation 随机排列一个数组root =Nonefor i,point in enumerate(data):root = insert(root,point,i)query_key = 6result_set = KNNResultSet(capacity=k)knn_search(root, result_set, query_key)print('kNN Search:')print('index - distance')print(result_set)result_set = RadiusNNResultSet(radius=radius)radius_search(root, result_set, query_key)print('Radius NN Search:')print('index - distance')print(result_set)# print("inorder")# inorder(root)# print("preorder")# preorder(root)# print("postorder")# postorder(root)# node = search_recursive(root, 2)# print(node)## node = search_iterative(root, 2)# print(node)if __name__ == '__main__':main()

结果:

import copyclass DistIndex:def __init__(self, distance, index):self.distance = distanceself.index = indexdef __lt__(self, other):return self.distance < other.distanceclass KNNResultSet:def __init__(self, capacity):self.capacity = capacityself.count = 0self.worst_dist = 1e10self.dist_index_list = []for i in range(capacity):self.dist_index_list.append(DistIndex(self.worst_dist, 0))self.comparison_counter = 0def size(self):return self.countdef full(self):return self.count == self.capacitydef worstDist(self):return self.worst_distdef add_point(self, dist, index):self.comparison_counter += 1if dist > self.worst_dist:returnif self.count < self.capacity:self.count += 1i = self.count - 1while i > 0:if self.dist_index_list[i - 1].distance > dist:self.dist_index_list[i] = copy.deepcopy(self.dist_index_list[i - 1])i -= 1else:breakself.dist_index_list[i].distance = distself.dist_index_list[i].index = indexself.worst_dist = self.dist_index_list[self.capacity - 1].distancedef __str__(self):output = ''for i, dist_index in enumerate(self.dist_index_list):output += '%d - %.2f\n' % (dist_index.index, dist_index.distance)output += 'In total %d comparison operations.' % self.comparison_counterreturn outputclass RadiusNNResultSet:def __init__(self, radius):self.radius = radiusself.count = 0self.worst_dist = radiusself.dist_index_list = []self.comparison_counter = 0def size(self):return self.countdef worstDist(self):return self.radiusdef add_point(self, dist, index):self.comparison_counter += 1if dist > self.radius:returnself.count += 1self.dist_index_list.append(DistIndex(dist, index))def __str__(self):self.dist_index_list.sort()output = ''for i, dist_index in enumerate(self.dist_index_list):output += '%d - %.2f\n' % (dist_index.index, dist_index.distance)output += 'In total %d neighbors within %f.\nThere are %d comparison operations.' \% (self.count, self.radius, self.comparison_counter)return output

三维点云处理: k-nn、radius邻近查找作业相关推荐

  1. 三维点云学习(4)5-DBSCNA python 复现-3-kd-tree radius NN 三方库 scipy 与 sklearn速度比较

    三维点云学习(4)5-DBSCNA python 复现-3-kd-tree radius NN 三方库 scipy 与 sklearn速度比较 import from scipy.spatial im ...

  2. 三维点云学习(4)7-ransac 地面分割+ DBSCAN聚类比较

    三维点云学习(4)7-ransac 地面分割+ DBSCAN聚类比较 回顾: 实现ransac地面分割 DBSCNA python 复现-1- 距离矩阵法 DBSCNA python 复现-2-kd- ...

  3. 三维点云学习(4)5-DBSCNA python 复现-2-kd-_tree加速

    三维点云学习(4)5-DBSCNA python 复现-2-kd-tree加速 因为在上一章DBSCAN在构建距离矩阵时,需要构建一个NN的距离矩阵,严重占用资源,古采用kd_tree搜索进行进一步的 ...

  4. 三维点云学习(4)2-mean shift dbscan

    三维点云学习(4)2-mean shift & dbscan mean shift hill climbing爬山算法 1个圆包含的点尽可能最多点: step1:随机选取一个点作为radius ...

  5. 三维点云学习(2)五种算法比较

    三维点云学习(2)五种算法比较 代码参考来自 黎老师github 本次测试包含五种算法比较: octree print("octree --------------")#时间统计c ...

  6. 三维点云学习(2)上- 二叉树实现K-NN Radius-NN Search

    三维点云学习(2)上 二叉树实现K-NN Radius-NN Search 代码来自 黎老师github 个人心得 二叉树的搜寻方法 正如老师课堂所说,实现二叉树的搜寻有两种方法,一种是递归,一种是循 ...

  7. 三维点云学习(5)5-实现Deeplearning-PointNet-2-classfication

    三维点云学习(5)5-实现Deeplearning-PointNet-2-classfication Github PointNet源码 数据集下载:为40种物体的三维点云数据集 提取码:es14 运 ...

  8. 三维点云学习(4)5-DBSCNA python 复现-1- 距离矩阵法

    三维点云学习(4)5-DBSCNA python 复现-1- 距离矩阵法 代码参考,及伪代码参考: DBSCAN 对点云障碍物聚类 使用Kdtree加速的DBSCAN进行点云聚类 DBSCAN 课程笔 ...

  9. 三维点云学习(4)1- Spectral的理论推导与解释

    三维点云学习(4)1- Spectral的理论推导与解释 回顾谱聚类的步骤 Graph Cut RatioCut -> Unnormalized Ncut->Normalized Min- ...

最新文章

  1. 独热编码(One-Hot)的理解
  2. android 常用类
  3. 到底什么是MiddleWare(中间件),请用plain English描述
  4. 一张截图,告诉你字节跳动的 Java 开发能力到底有多强...
  5. Linux命令【第一篇】
  6. 基于容器服务 ACK 发行版打造 CNStack 社区版
  7. Using Delegates with Data Readers to Control DAL Responsibility[转]
  8. js实现全国省份下拉
  9. matlab在常微分方程的应用,Matlab在常微分方程教学中的应用
  10. 降维算法原理篇:主成分分析PCA、奇异值分解SVD、因子分析法FA、独立成分分析ICA等原理详推
  11. UVM中drain_time使用
  12. iPhone iPad Cydia 软件源 大全
  13. 安卓的数据共享——从一个APP中调用另一个APP数据的方法
  14. 网络安全法条例-黑客违法判刑标准国家安全法介绍和案例
  15. CYPRESS S6E1C3 系列 FM0+ 32位单片机串口uart0 问题
  16. [Kubic] Lines
  17. python用input输入字典_python输入字典_输入字典python_python用input输入字典 - 云+社区 - 腾讯云...
  18. 服务器基本故障及排查方法
  19. Ubuntu20.04软件主要管理工具包详细介绍:离线安装dpkg、在线安装apt、源码安装(适用于Github程序下载)
  20. 美通企业日报 | 洽洽开启中国坚果品牌全球化新征程;创维上半年净利同比增两成...

热门文章

  1. 奖学金用计算机怎表达,奖学金感谢信怎么写
  2. 高精度小数乘法c语言程序设计教程课后答案,级C语言程序设计基教程课后习题答案.doc...
  3. 把一串汉字转换为对应大写拼音字头 VB
  4. Android验证码输入框支持粘贴
  5. add-apt-repository PPA
  6. 文华财经-DMI趋势模型-螺纹指数
  7. 高德地图发布全国美食地图:火锅最受欢迎
  8. Redis导致Linux服务器中病毒、成肉鸡了。
  9. Oracle 11g新特性
  10. 「 硬核教学」 ❤️ C语言编写扫雷游戏外挂❤️「 完整源码」