Pseudo Code of KNN

We can implement a KNN model by following the below steps:

  1. Load the data
  2. Initialise the value of k
  3. For getting the predicted class, iterate from 1 to total number of training data points
    1. 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.
    2. Sort the calculated distances in ascending order based on distance values
    3. Get top k rows from the sorted array
    4. Get the most frequent class of these rows
    5. Return the predicted class

Iris Data Set

把数据作为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++的更多相关文章

  1. 【Machine Learning】KNN算法虹膜图片识别

    K-近邻算法虹膜图片识别实战 作者:白宁超 2017年1月3日18:26:33 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...

  2. K近邻法(KNN)原理小结

    K近邻法(k-nearst neighbors,KNN)是一种很基本的机器学习方法了,在我们平常的生活中也会不自主的应用.比如,我们判断一个人的人品,只需要观察他来往最密切的几个人的人品好坏就可以得出 ...

  3. kd树和knn算法的c语言实现

    基于kd树的knn的实现原理可以参考文末的链接,都是一些好文章. 这里参考了别人的代码.用c语言写的包括kd树的构建与查找k近邻的程序. code: #include<stdio.h> # ...

  4. k近邻算法(knn)的c语言实现

    最近在看knn算法,顺便敲敲代码. knn属于数据挖掘的分类算法.基本思想是在距离空间里,如果一个样本的最接近的k个邻居里,绝大多数属于某个类别,则该样本也属于这个类别.俗话叫,"随大流&q ...

  5. 室内定位系列(三)——位置指纹法的实现(KNN)

    位置指纹法中最常用的算法是k最近邻(kNN):选取与当前RSS最邻近的k个指纹的位置估计当前位置,简单直观有效.本文介绍kNN用于定位的基本原理与具体实现(matlab.python). 基本原理 位 ...

  6. KNN识别图像上的数字及python实现

    领导让我每天手工录入BI系统中的数据并判断数据是否存在异常,若有异常点,则检测是系统问题还是业务问题.为了解放双手,我决定写个程序完成每天录入管理驾驶舱数据的任务.首先用按键精灵录了一套脚本把系统中的 ...

  7. k近邻(KNN)复习总结

    摘要: 1.算法概述 2.算法推导 3.算法特性及优缺点 4.注意事项 5.实现和具体例子 6.适用场合内容: 1.算法概述 K近邻算法是一种基本分类和回归方法:分类时,根据其K个最近邻的训练实例的类 ...

  8. KNN算法

    1.算法讲解 KNN算法是一个最基本.最简单的有监督算法,基本思路就是给定一个样本,先通过距离计算,得到这个样本最近的topK个样本,然后根据这topK个样本的标签,投票决定给定样本的标签: 训练过程 ...

  9. 【十大经典数据挖掘算法】kNN

    [十大经典数据挖掘算法]系列 C4.5 K-Means SVM Apriori EM PageRank AdaBoost kNN Naïve Bayes CART 1. 引言 顶级数据挖掘会议ICDM ...

  10. K近邻模型(k-NN)

    原理 K最近邻(k-Nearest Neighbor,KNN)分类算法,是一个理论上比较成熟的方法,也是最简单的机器学习算法之一.该方法的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻 ...

随机推荐

  1. CSS——text-indent

    在h1标签里套入a标签并写上文字,有利于seo,但是文字如何隐藏呢?一般都是a标签变成内联块并首行缩进为负值. <!DOCTYPE html> <html lang="en ...

  2. python2升级成python3

    系统环境centos 6.5原python版本2.6.6目标python版本3.5.11.下载python3.5wget --no-check-certificate  http://www.pyth ...

  3. Oracle基础理论笔记(一):模式概念

    ---oracle 10g 1.在oracle数据库中,数据对象是以模式为单位进行组织和管理的.模式是指一系列的逻辑数据结构或对象的集合. 2.模式与用户名相对应,一个模式只能对应一个用户,并且该模式 ...

  4. 更改计算机名后DB2不能启动的解决方法

    1.找到以下位置目录下相应的文件db2nodes.cfg C:\Documents and Settings\All Users\Application Data\IBM\DB2\DB2COPY1\D ...

  5. (转) SolrCloud之分布式索引及与Zookeeper的集成

    http://blog.csdn.net/ebay/article/details/46549481 作者:Wang, Josh 一.概述 Lucene是一个Java语言编写的利用倒排原理实现的文本检 ...

  6. iOS crash log 解析 symbol address = stack address - slide 运行时获取slide的api 利用dwarfdump从dsym文件中得到symbol

    概述: 为什么 crash log 内 Exception Backtrace 部分的地址(stack address)不能从 dsym 文件中查出对应的代码? 因为 ASLR(Address spa ...

  7. unable to get system library for the project

    当向eclipse导入项目实例后,项目上出现红叉的错误提示,在项目属性里的Java Build Path里发现了错误提示复选选项: unable to get system library for t ...

  8. JS实现随机颜色的3种方法与颜色格式的转化

    JS实现随机颜色的3种方法与颜色格式的转化   随机颜色和颜色格式是我们在开发中经常要用到的一个小功能,网上相关的资料也很多,想着有必要总结一下自己的经验.所以这篇文章主要介绍了JS实现随机颜色的3种 ...

  9. windows环境安装python虚拟环境

    虚拟环境安装参考 https://www.cnblogs.com/suke99/p/5355894.html workon环境变量配置参照 https://www.cnblogs.com/jiuyan ...

  10. CDR真实图片转水墨画效果制作教程

    CorelDRAW创造性滤镜组是最具有创造力的滤镜,使用里面的散开滤镜能够实现类似于水墨的表现手法,然后再结合图层的合并模式,让您的图片产生意想不到的视觉效果.本文将利用CorelDRAW软件中提供的 ...