KNN简单实现
来源:互联网 发布:山东软件开发 编辑:程序博客网 时间:2024/06/07 12:36
KNN(K nearest neighbor Algorithm)
原理:取距离上训练数据上最近的K个点的均值作为估计值。
简单实现:
//A general realization of K nearest neighbors Algorithm#include <iostream> #include <vector>#include <algorithm>#include <cmath>using namespace std; struct ob{ double dis,val;};bool cmp(ob a,ob b){return a.dis<b.dis;}int main(){int K,n,x;cout<<"Please put in the value for parameter K:";cin>>K;cout<<"\nPlease put in the value for attribute amount x:";cin>>x;cout<<"\nPlease put in the value for data amount n:";cin>>n;cout<<"Please put in the data in the form of x1,...,xi,...xn,value repeatly\n";vector <vector<double> > data;for(int i=0;i<n;i++){vector <double> v;double tmp;for(int j=0;j<=x;j++){cin>>tmp;v.push_back(tmp);}data.push_back(v);}cout<<"Please put in the data to be predicted in the form of x1,...,xi,...xn\n";while(1){vector <double> v;double tmp,pred_val=0;for(int i=0;i<x;i++){cin>>tmp;v.push_back(tmp);}vector <ob> q;ob apiece;for(int i=0;i<n;i++){apiece.dis=0;for(int j=0;j<x;j++){apiece.dis+=(v[j]-data[i][j])*(v[j]-data[i][j]);}apiece.dis=sqrt(apiece.dis);apiece.val=data[i][x];q.push_back(apiece);}sort(q.begin(),q.end(),cmp);for(int i=0;i<K;i++){pred_val+=q[i].val;}pred_val/=K;cout<<"The predicted value is :"<<pred_val<<endl;}return 0;}
阅读全文
0 0
- KNN的简单实现
- numpy KNN简单实现
- KNN简单实现
- KNN简单实现
- Python 简单实现KNN算法
- KNN(一)--简单KNN原理及实现
- KNN(一)--简单KNN原理及实现
- KNN(一)--简单KNN原理及实现
- KNN的简单实现(python)
- KNN的matlab简单实现代码
- Knn实现简单的物品推荐
- opencv+KNN实现手写简单数字识别
- numpy KNN简单实现 分类:机器学习
- 利用sklearn实现简单的KNN
- 简单的KNN的python实现
- python之KNN算法的简单实现
- python KNN算法的简单实现
- 用Tensorflow实现简单的KNN
- HBase分析之Get、Scan(二)RegionScanner
- vmware虚拟机安装CentOS7后网络配置
- 一些android预装应用名字对应关系
- linux 下vi编辑的一些实用命令
- 大数--hdu5920 Ugly Problem
- KNN简单实现
- 欢迎使用CSDN-markdown编辑器
- html&css基础总结
- 使用国内镜像源来加速python pypi包的安装和tornado 4.5.2的安装
- TCP连接管理
- HBase分析之Get、Scan(三)StoreScanner
- 心境之旅
- mybatis 语句中where 后边要跟必要条件和多个选择条件处理方法
- DNS使用UDP/TCP