Python 实现 KD-Tree 最近邻算法
这里将写了一个KDTree
类,仅实现了最近邻,K近邻之后若有时间再更新:
from collections import namedtuple
from operator import itemgetter
from pprint import pformat
import numpy as np
class Node(namedtuple('Node', 'location left_child right_child')):
def __repr__(self):
return pformat(tuple(self))
class KDTree():
def __init__(self, points):
self.tree = self._make_kdtree(points)
if len(points) > 0:
self.k = len(points[0])
else:
self.k = None
def _make_kdtree(self, points, depth=0):
if not points:
return None
k = len(points[0])
axis = depth % k
points.sort(key=itemgetter(axis))
median = len(points) // 2
return Node(
location=points[median],
left_child=self._make_kdtree(points[:median], depth + 1),
right_child=self._make_kdtree(points[median + 1:], depth + 1))
def find_nearest(self,
point,
root=None,
axis=0,
dist_func=lambda x, y: np.linalg.norm(x - y)):
if root is None:
root = self.tree
self._best = None
# 若不是叶节点,则继续向下走
if root.left_child or root.right_child:
new_axis = (axis + 1) % self.k
if point[axis] < root.location[axis] and root.left_child:
self.find_nearest(point, root.left_child, new_axis)
elif root.right_child:
self.find_nearest(point, root.right_child, new_axis)
# 回溯:尝试更新 best
dist = dist_func(root.location, point)
if self._best is None or dist < self._best[0]:
self._best = (dist, root.location)
# 若超球与另一边超矩形相交
if abs(point[axis] - root.location[axis]) < self._best[0]:
new_axis = (axis + 1) % self.k
if root.left_child and point[axis] >= root.location[axis]:
self.find_nearest(point, root.left_child, new_axis)
elif root.right_child and point[axis] < root.location[axis]:
self.find_nearest(point, root.right_child, new_axis)
return self._best
测试:
point_list = [(2, 3, 3), (5, 4, 4), (9, 6, 7), (4, 7, 7), (8, 1, 1), (7, 2, 2)]
kdtree = KDTree(point_list)
point = np.array([5, 5, 5])
print(kdtree.find_nearest(point))
输出:
(1.4142135623730951, (5, 4, 4))
与 Scikit-Learn 性能对比(上是我的实现,下是 Scikit-Learn 的实现):
可以看到仅相差 1 毫秒,所以性能说得过去。
(本文完)
Python 实现 KD-Tree 最近邻算法的更多相关文章
- K-D TREE算法原理及实现
博客转载自:https://leileiluoluo.com/posts/kdtree-algorithm-and-implementation.html k-d tree即k-dimensional ...
- k-d tree算法
k-d树(k-dimensional树的简称),是一种分割k维数据空间的数据结构.主要应用于多维空间关键数据的搜索(如:范围搜索和最近邻搜索). 应用背景 SIFT算法中做特征点匹配的时候就会利用到k ...
- 【数据结构与算法】k-d tree算法
k-d tree算法 k-d树(k-dimensional树的简称),是一种分割k维数据空间的数据结构.主要应用于多维空间关键数据的搜索(如:范围搜索和最近邻搜索). 应用背景 SIFT算法中做特征点 ...
- Python机器学习笔记 K-近邻算法
K近邻(KNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一. 所谓K最近邻,就是K个最近的邻居的意思,说的是每个样本都可以用它最接近的k个邻居来代表.KNN算法的 ...
- [转载]kd tree
[本文转自]http://www.cnblogs.com/eyeszjwang/articles/2429382.html k-d树(k-dimensional树的简称),是一种分割k维数据空间的数据 ...
- k-d tree 学习笔记
以下是一些奇怪的链接有兴趣的可以看看: https://blog.sengxian.com/algorithms/k-dimensional-tree http://zgjkt.blog.uoj.ac ...
- 【BZOJ-2648&2716】SJY摆棋子&天使玩偶 KD Tree
2648: SJY摆棋子 Time Limit: 20 Sec Memory Limit: 128 MBSubmit: 2459 Solved: 834[Submit][Status][Discu ...
- Python之路,Day21 - 常用算法学习
Python之路,Day21 - 常用算法学习 本节内容 算法定义 时间复杂度 空间复杂度 常用算法实例 1.算法定义 算法(Algorithm)是指解题方案的准确而完整的描述,是一系列解决问题的 ...
- K-D Tree题目泛做(CXJ第二轮)
题目1: BZOJ 2716 题目大意:给出N个二维平面上的点,M个操作,分为插入一个新点和询问到一个点最近点的Manhatan距离是多少. 算法讨论: K-D Tree 裸题,有插入操作. #inc ...
- [Python]基于K-Nearest Neighbors[K-NN]算法的鸢尾花分类问题解决方案
看了原理,总觉得需要用具体问题实现一下机器学习算法的模型,才算学习深刻.而写此博文的目的是,网上关于K-NN解决此问题的博文很多,但大都是调用Python高级库实现,尤其不利于初级学习者本人对模型的理 ...
随机推荐
- django-crontab实现定时任务
django-crontab实现服务端的定时任务 安装 pip install django-crontab 在Django项目中使用 settings.py INSTALLED_APPS = ( ' ...
- bootstrap: 内联表单;
<form class="form-inline"> <div class="form-group"> <label for=&q ...
- sshpass-Linux命令之非交互SSH密码验证
sshpass-Linux命令之非交互SSH密码验证 参考网址:https://www.cnblogs.com/chenlaichao/p/7727554.html ssh登陆不能在命令行中指定密码. ...
- (十) 编写UVC程序
目录 编写UVC程序 流程简述 11个ioctl函数 查询属性 VIDIOC_QUERYCAP 枚举格式 VIDIOC_ENUM_FMT 查询当前格式 VIDIOC_G_FMT 尝试某种格式 VIDI ...
- XGBboost 特征评分的计算原理
xgboost是基于GBDT原理进行改进的算法,效率高,并且可以进行并行化运算,而且可以在训练的过程中给出各个特征的评分,从而表明每个特征对模型训练的重要性, 调用的源码就不准备详述,本文主要侧重的是 ...
- C#使用Selenium+PhantomJS抓取数据
本文主要介绍了C#使用Selenium+PhantomJS抓取数据的方法步骤,具有很好的参考价值,下面跟着小编一起来看下吧 手头项目需要抓取一个用js渲染出来的网站中的数据.使用常用的httpclie ...
- Exp5 MSF基础应用 20164314
一.实践内容 本实践目标是掌握metasploit的基本应用方式,重点常用的三种攻击方式的思路.具体需要完成: 1.一个主动攻击实践,如ms08_067; (成功) 2.一个针对浏览器的攻击,如ms1 ...
- 第30月第13天 supportedInterfaceOrientationsForWindow旋转
1. 对于做视频横屏播放的情况下:做旋转有3种方法. 第一种:就是网上说的用旋转矩阵方法CGAffineTransformMakeRotation来做,直接旋转某个view,之后setFrame,至于 ...
- Groovy中的GString
在讨论GString之前,我们先讨论一下Groovy里面的String.在Groovy里面String有 println 'test string' println '''test string''' ...
- IDEA+MySQL实现登录注册的注册验证时出现 Cannot resolve query parameter '2'
问题描述: 在IDEA+MySQL+Tomcat 实现登录注册JSP的注册信息INSERT验证时出现 Cannot resolve query parameter '2' 贴上创建链接的代码: if( ...