现在的位置: 首页 > 综合 > 正文

KNN算法的实现

2012年07月03日 ⁄ 综合 ⁄ 共 1459字 ⁄ 字号 评论关闭
Knn.h

#pragma once

class Knn
{
private:
 double** trainingDataset;
 double* arithmeticMean;
 double* standardDeviation;
 int m, n;

 void RescaleDistance(double* row);
 void RescaleTrainingDataset();
 void ComputeArithmeticMean();
 void ComputeStandardDeviation();

 double Distance(double* x, double* y);
public:
 Knn(double** trainingDataset, int m, int n);
 ~Knn();
 double Vote(double* test, int k);
};

 

Knn.cpp

 

#include "Knn.h"
#include 
#include 

using namespace std;

Knn::Knn(double** trainingDataset, int m, int n)
{
 this->trainingDataset = trainingDataset;
 this->m = m;
 this->n = n;
 ComputeArithmeticMean();
 ComputeStandardDeviation();
 RescaleTrainingDataset();
}

void Knn::ComputeArithmeticMean()
{
 arithmeticMean = new double[n - 1];

 double sum;

 for(int i = 0; i ::iterator max;

 map mins;

 for(int i = 0; i ::value_type(i, distance));
  else
  {
   max = mins.begin();
   for(map::iterator it = mins.begin(); it != mins.end(); it++)
   {
    if(it->second > max->second)
     max = it;
   }
   if(distance second)
   {
    mins.erase(max);
    mins.insert(map::value_type(i, distance));
   }
  }
 }

 map votes;
 double temp;

 for(map::iterator it = mins.begin(); it != mins.end(); it++)
 {
  temp = trainingDataset[it->first][n-1];
  map::iterator voteIt = votes.find(temp);
  if(voteIt != votes.end())
   voteIt->second ++;
  else
   votes.insert(map::value_type(temp, 1));
 }

 map::iterator maxVote = votes.begin();

 for(map::iterator it = votes.begin(); it != votes.end(); it++)
 {
  if(it->second > maxVote->second)
   maxVote = it;
 }

 test[n-1] = maxVote->first;

 return maxVote->first;
}

 

main.cpp

 

#include 
#include "Knn.h"

using namespace std;

int main(const int& argc, const char* argv[])
{
 double** train = new double* [14];
 for(int i = 0; i 

抱歉!评论已关闭.