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. JS——dom

    节点的获取 <script> var div = document.getElementById("box");//返回指定标签 var div = document. ...

  2. Android studio在使用过程中的问题总汇!

    使用android studio也有一段时间了,汇总了一下这段时间内遇到一些常见问题,希望能够帮助到大家! 一.字体大小问题 在android studio的使用过程中没有发现类似于Eclipse中的 ...

  3. (三)Python 学习第三天--GUI桌面项目

    (代码参考了别人的代码,只做学习用途!!!最近因为写论文,好久没有记录,好内疚...今天学习了一个小案例,做一下) 主要使用模块:tkinter 代码如下: from tkinter import * ...

  4. 【转】SSH中 整合spring和proxool 连接池

    [摘要:比来做的一个项目中应用到了毗邻池技巧,大概我们人人比拟认识的开源毗邻池有dbcp,c3p0,proxool.对那三种毗邻池来讲,从机能战失足率来讲,proxool轻微比前两种好些.本日我首要简 ...

  5. Django中图片的上传并显示

    一.settings配置文件中配置 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'medias').replace('\\', ...

  6. win10系统安装postgresql后无法连接

    win10系统安装postgresql后在系统服务列表中找不到,连接不上数据库. 可以尝试关闭系统防火墙后重启电脑或者重装程序.

  7. Light Oj - 1134 Be Efficient

    题目传送门:Be Efficient 题意:输入n和m,然后输入有n个元素的一个序列,问有多少个子序列元素的和能整除m. 思路:求前缀和,利用一个前缀的一个定理求解. 前缀和的一个定理是:每次求的前缀 ...

  8. 303. Range Sum Query - Immutable(动态规划)

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  9. 【Codeforces 1114D】Flood Fill

    [链接] 我是链接,点我呀:) [题意] 你选择一个point作为start_position 然后每次你可以将包含该start_position的所有联通块变成任意颜色 问你最少要多少次变换才能将所 ...

  10. 清北学堂模拟赛d6t3 反击数

    分析:显然是一道数位dp题,不过需要一些奇怪的姿势.常规的数位dp能统计出一个区间内满足条件的数的个数,可是我们要求第k个,怎么办呢?转化为经典的二分问题,我们二分当前数的大小,看它是第几大的,就可以 ...