KNN in c++
Pseudo Code of KNN
We can implement a KNN model by following the below steps:
- Load the data
- Initialise the value of k
- For getting the predicted class, iterate from 1 to total number of training data points
- Calculate the distance between test data and each row of training data. Here we will use Euclidean distance as our distance metric since it’s the most popular method. The other metrics that can be used are Chebyshev, cosine, etc.
- Sort the calculated distances in ascending order based on distance values
- Get top k rows from the sorted array
- Get the most frequent class of these rows
- Return the predicted class
把数据作为string类型处理,进行string和double类型转换。
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>
#include <functional>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
template <class T1, class T2>
double ManhattanDistance(std::vector<T1> &inst1, std::vector<T2> &inst2) {
if(inst1.size() != inst2.size()) {
std::cout<<"the size of the vectors is not the same\n";
return -1;
}
std::vector<double> temp;
for(size_t i=0;i<inst1.size();++i) {
temp.push_back(std::abs(inst1.at(i)-inst2.at(i)));
}
double distance=accumulate(temp.begin(), temp.end(), 0.0);
return distance;
}
template <class DataType1, class DataType2>
double EuclideanDistance(const std::vector<DataType1> &inst1, const std::vector<DataType2> &inst2) {
if(inst1.size() != inst2.size()) {
std::cout<<"the size of the vectors is not the same\n";
return -1;
}
std::vector<double> temp;
for(size_t i=0; i<inst1.size(); ++i) {
temp.push_back(pow(inst1.at(i)-inst2.at(i), 2.0));
}
double distance=accumulate(temp.begin(), temp.end(), 0.0);
distance=sqrt(distance);
return distance;
}
void vstr2vdouble(std::vector<std::string>::const_iterator beg, std::vector<std::string>::const_iterator end, std::vector<double> &vdouble) {
for(std::vector<std::string>::const_iterator it=beg; it!=end; ++it) {
double d;
std::stringstream ss;
ss<<*it;
ss>>d;
vdouble.push_back(d);
}
}
void knn(std::vector<std::vector<std::string> > &trainset, std::vector<std::string> &testdata, int &k) {
std::vector<double> testitem;
vstr2vdouble(testdata.begin(), testdata.end(), testitem);
std::multimap<std::string, std::string> mmap;
for(size_t i=0;i<trainset.size();++i) {
std::vector<double> trainitem;
vstr2vdouble(trainset[i].begin(), trainset[i].end()-1, trainitem);
double distance=EuclideanDistance(testitem, trainitem);
std::string strdis;
std::stringstream ss;
ss<<distance;
ss>>strdis;
mmap.insert(std::pair<std::string, std::string>(strdis, trainset[i].back()));
}
size_t i=0;
for(std::multimap<std::string, std::string>::const_iterator it=mmap.begin(); i<k; ++i,++it) {
std::cout<<it->first<<" "<<it->second<<"\n";
}
}
template <class DataType>
void ReadDataFromFile(std::string &filename, std::vector<std::vector<DataType> > &lines_feat) {
std::ifstream vm_info(filename.c_str());
std::string lines, var;
std::vector<std::string> row;
lines_feat.clear();
while(!vm_info.eof()) {
getline(vm_info, lines);
if(lines.empty())
break;
std::replace(lines.begin(), lines.end(), ',', ' ');
std::stringstream stringin(lines);
row.clear();
while(stringin >> var) {
row.push_back(var);
}
lines_feat.push_back(row);
}
}
template <class DataType>
void Display2DVector(std::vector<std::vector<DataType> > &vv) {
std::cout<<"the total rows of 2d vector_data: "<<vv.size()<<std::endl;
for(size_t i=0;i<vv.size();++i) {
for(typename::std::vector<DataType>::const_iterator it=vv[i].begin();it!=vv[i].end();++it) {
std::cout<<*it<<" ";
}
std::cout<<"\n";
}
std::cout<<"--------the end of the Display2DVector()--------\n";
}
int main() {
std::string trainpath="Iris.data", testpath="knntest.data";
std::vector<std::vector<std::string> > knn_data, test_data;
ReadDataFromFile(trainpath, knn_data);
ReadDataFromFile(testpath, test_data);
Display2DVector(test_data);
int k=3;
for(size_t i=0;i<test_data.size();++i) {
knn(knn_data, test_data[i], k);
}
return 0;
}
KNN in c++的更多相关文章
- 【Machine Learning】KNN算法虹膜图片识别
K-近邻算法虹膜图片识别实战 作者:白宁超 2017年1月3日18:26:33 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...
- K近邻法(KNN)原理小结
K近邻法(k-nearst neighbors,KNN)是一种很基本的机器学习方法了,在我们平常的生活中也会不自主的应用.比如,我们判断一个人的人品,只需要观察他来往最密切的几个人的人品好坏就可以得出 ...
- kd树和knn算法的c语言实现
基于kd树的knn的实现原理可以参考文末的链接,都是一些好文章. 这里参考了别人的代码.用c语言写的包括kd树的构建与查找k近邻的程序. code: #include<stdio.h> # ...
- k近邻算法(knn)的c语言实现
最近在看knn算法,顺便敲敲代码. knn属于数据挖掘的分类算法.基本思想是在距离空间里,如果一个样本的最接近的k个邻居里,绝大多数属于某个类别,则该样本也属于这个类别.俗话叫,"随大流&q ...
- 室内定位系列(三)——位置指纹法的实现(KNN)
位置指纹法中最常用的算法是k最近邻(kNN):选取与当前RSS最邻近的k个指纹的位置估计当前位置,简单直观有效.本文介绍kNN用于定位的基本原理与具体实现(matlab.python). 基本原理 位 ...
- KNN识别图像上的数字及python实现
领导让我每天手工录入BI系统中的数据并判断数据是否存在异常,若有异常点,则检测是系统问题还是业务问题.为了解放双手,我决定写个程序完成每天录入管理驾驶舱数据的任务.首先用按键精灵录了一套脚本把系统中的 ...
- k近邻(KNN)复习总结
摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 6.适用场合内容: 1.算法概述 K近邻算法是一种基本分类和回归方法:分类时,根据其K个最近邻的训练实例的类 ...
- KNN算法
1.算法讲解 KNN算法是一个最基本.最简单的有监督算法,基本思路就是给定一个样本,先通过距离计算,得到这个样本最近的topK个样本,然后根据这topK个样本的标签,投票决定给定样本的标签: 训练过程 ...
- 【十大经典数据挖掘算法】kNN
[十大经典数据挖掘算法]系列 C4.5 K-Means SVM Apriori EM PageRank AdaBoost kNN Naïve Bayes CART 1. 引言 顶级数据挖掘会议ICDM ...
- K近邻模型(k-NN)
原理 K最近邻(k-Nearest Neighbor,KNN)分类算法,是一个理论上比较成熟的方法,也是最简单的机器学习算法之一.该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻 ...
随机推荐
- JS高级——instanceof语法
基本语法 对象 instanceof 构造函数 基本使用 <script> function Person() { } //p--->Person.prototype--->O ...
- 在python中调用js或者nodejs
在python中调用js或者nodejs要使用PyExecJs第三方包. pip install pyexecjs 示例代码 >>> import execjs >>&g ...
- ats 与 https
一些证书相关的描述: https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKe ...
- Map 键值对 set get delete
- 11.11如何卖到一个亿:从0到1的电商爆品打造术 电子书 PDF
内容转自:https://download.csdn.net/download/chenyao1994/11191034 下载地址:https://pan.baidu.com/s/1uQ1cjm9QH ...
- HDU - 1087 Super Jumping!Jumping!Jumping!(dp求最长上升子序列的和)
传送门:HDU_1087 题意:现在要玩一个跳棋类游戏,有棋盘和棋子.从棋子st开始,跳到棋子en结束.跳动棋子的规则是下一个落脚的棋子的号码必须要大于当前棋子的号码.st的号是所有棋子中最小的,en ...
- SQL上门
学习这个 介绍:SQL 是用于访问和处理数据库的标准的计算机语言.结构化化查询语言! SQL可以分为两大部分:数据操作语言(DML)和数据定义语言(DDL) 数据操作语言:select.update. ...
- Problem 30
Problem 30 https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be ...
- Python基础-List找重复数
请从L=[1,10,20,50,20,20,1]中找出重复数. L=[1,10,20,50,20,20,1] L1=[] for i in L: if(L.count(i)>1): L1.app ...
- EF--model is being created异常
使用EF的时候出现了下面的异常,我使用了TASK和saveChangeAsync()异步 The context cannot be used while the model is being cre ...