如何从 k-d 树实现 K-NN 分类
How to implement K-NN classification from a k-d tree?
我正在尝试使用 k-d 树编写 K-NN 分类的代码,而无需使用任何库。到目前为止,我已经能够为 k-d 树编写代码,但我似乎无法理解一旦树从训练集形成,我如何找到 k 最近邻。K-D 树代码:
#include<bits/stdc++.h>
using namespace std;
const int k = 2; // 2-dimensions
struct Node
{
int point[k];
Node *left, *right;
};
struct Node* newNode(int arr[])
{
struct Node* temp = new Node;
for (int i=0; i<k; i++)
temp->point[i] = arr[i];
temp->left = temp->right = NULL;
return temp;
}
// Inserts a new node and returns root of modified tree
Node *insertRec(Node *root, int point[], unsigned depth)
{
if (root == NULL)
return newNode(point);
unsigned cd = depth % k;
if (point[cd] < (root->point[cd]))
root->left = insertRec(root->left, point, depth + 1);
else
root->right = insertRec(root->right, point, depth + 1);
return root;
}
// Function to insert a new point with given point and return new root
Node* insert(Node *root, int point[])
{
return insertRec(root, point, 0);
}
// driver
int main()
{
struct Node *root = NULL;
int points[][k] = {{3, 6}, {17, 15}, {13, 15}, {6, 12},
{9, 1}, {2, 7}, {10, 19}};
int n = sizeof(points)/sizeof(points[0]);
for (int i=0; i<n; i++)
root = insert(root, points[i]);
return 0;
}
首先不要使用 <bits/stdc++.h>
。这是不对的。
要找到 k 个最近的元素,您需要以一种首先遍历最近元素的方式遍历树。然后,如果您没有足够的元素,请遍历更远的元素。
我不会在这里编写代码,只是伪代码(因为我很久以前就已经构建了一个(:
list l; # list of the elements, sorted by distance
heap p; # heap of nodes to traverse, sorted by distance
p.push(root)
while (!p.empty())
{
node = p.pop(); # Get a new node
d = distance(point, node); # compute the closest distance from the point to the node
if(l.empty() or distance(point, l.back()) > d)
{
add(node->left); # iteration on subnodes
add(node->right);
l.push(points); # Add points from the current node
}
l.pop_elements(k); # pop elements to keep only k
}
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 如何从 k-d 树实现 K-NN 分类