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高级库实现,尤其不利于初级学习者本人对模型的理 ...
随机推荐
- 史上最全PMP备考考点全攻略(上篇-五大过程组,附赠资料)
一.这可能是一篇史上最全的PMP备考考点全梳理文章 写在前面,这可能是史上最全的PMBOK考点全书考点梳理,由PMP备考自律营呕心沥血整理,内容较长,分为上下篇,绝对值得所有正在备考PMP的学员收藏! ...
- dpdk之路-环境部署
dpdk实验环境部署 1.实验环境说明 vmware workstatioin 12 centos 7.5.1804 dpdk-stable-18.11.1 2.实验步骤 (1)虚拟机安装 http: ...
- apue——读目录操作
头文件: #define _POSIX_C_SOURCE 200809L #include <sys/types.h> #include <sys/stat.h> #inclu ...
- HBase RowKey与索引设计
1. HBase的存储形式 hbase的内部使用KeyValue的形式存储,其key时rowKey:family:column:logTime,value是其存储的内容. 其在region内大多以升序 ...
- ArcGis Classic COM Add-Ins插件dll的安装与卸载
本文是去年<ArcGis Classic COM Add-Ins插件开发的一般流程 C#>一文(以下称“开发流程”)的后续.“开发流程”中写到会有“安装与卸载”系列的文章,今天把它补上. ...
- 《Java》第五周学习总结20175301
https://gitee.com/ShengHuoZaiDaXue/20175301.git 本周我学习了第六章的内容接口 重要内容有 理解接口 接口参数 面向接口编程 abstract类与接口的比 ...
- Promise库
标准 https://promisesaplus.com/ An open standard for sound, interoperable JavaScript promises—by imple ...
- 2、搭建一个简单的Web项目
一.创建一个Web项目: 1.File->new Project->Java->JavaEE->Web Application 2.为项目起名: 3.配置项目:在项目上击右键- ...
- Java IO与网络编程笔记
<!doctype html>Java IO&NIO figure:first-child { margin-top: -20px; } #write ol, #write ul ...
- ie浏览器部分图片不显示
前言 前几天做项目时,发现一个奇怪的现象,从后台获取的图片,在IE浏览器端,有一部分不会显示,仔细研究发现是图片本来是.jpg格式,后台传过来的图片后缀已经被改成了.png格式或者其它格式导致IE浏览 ...