k近邻法课后习题解答

3.2 求得的最近邻点是(2,3)

3.3 k近邻算法如下:

(思路:求得一个最近邻后,从kd树中删除这个结点)

#include <iostream>
#include <algorithm>
#include <stack>
#include <math.h>
using namespace std;
/*function of this program: build a 2d tree using the input training data
 the input is exm_set which contains a list of tuples (x,y)
 the output is a 2d tree pointer*/


struct data
{
	double x = 0;
	double y = 0;
};

struct Tnode
{
	struct data dom_elt;
    int split;
    struct Tnode * left;
    struct Tnode * right;
};

bool cmp1(data a, data b){
	return a.x < b.x;
}

bool cmp2(data a, data b){
	return a.y < b.y;
}

bool equal(data a, data b){
	if (a.x == b.x && a.y == b.y)
	{
		return true;
	}
	else{
		return false;
	}
}

void ChooseSplit(data exm_set[], int size, int &split, data &SplitChoice){
	/*compute the variance on every dimension. Set split as the dismension that have the biggest
     variance. Then choose the instance which is the median on this split dimension.*/
	/*compute variance on the x,y dimension. DX=EX^2-(EX)^2*/
    double tmp1,tmp2;
    tmp1 = tmp2 = 0;
    for (int i = 0; i < size; ++i)
    {
    	tmp1 += 1.0 / (double)size * exm_set[i].x * exm_set[i].x;
    	tmp2 += 1.0 / (double)size * exm_set[i].x;
    }
    double v1 = tmp1 - tmp2 * tmp2;  //compute variance on the x dimension
    
    tmp1 = tmp2 = 0;
    for (int i = 0; i < size; ++i)
    {
    	tmp1 += 1.0 / (double)size * exm_set[i].y * exm_set[i].y;
    	tmp2 += 1.0 / (double)size * exm_set[i].y;
    }
    double v2 = tmp1 - tmp2 * tmp2;  //compute variance 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值