2 goooogle 8 goooogle_8 于 2015.06.06 08:19 提问

大家帮忙看看我这段代码逻辑是不是有问题?

#include "stdafx.h"
#include "KNN.h"
#include
#include
#include
#include
//设置K值
void KNN::setK()
{
// cout << "请输入K:";
// cin >> K;
}

//读入训练集数据,100组数据,108维,10类
bool KNN::ReadTraining(char *filename)
{
ifstream fin;
fin.open(filename,ios::in);

if( fin.fail() )
{
cerr << "File open error1." << endl;
return false;
}

for(int i=0; i {
Traindata m_tmp;
for(int j=0; j {
double dm_tmp;
fin >> dm_tmp;
m_tmp.first.push_back(dm_tmp);
}
// int nm_tmp;

if(i<10)
m_tmp.second = 0;
else if(i<20)
m_tmp.second = 1;
else if(i<30)
m_tmp.second = 2;
else if(i<40)
m_tmp.second = 3;
else if(i<50)
m_tmp.second = 4;
else if(i<60)
m_tmp.second = 5;
else if(i<70)
m_tmp.second = 6;
else if(i<80)
m_tmp.second = 7;
else if(i<90)
m_tmp.second = 8;
else if(i<100)
m_tmp.second = 9;

training_data.push_back( m_tmp );

}
return true;

}

//读入测试集数据,8组6维数据
bool KNN::ReadTest(char *filename)
{
ifstream fin(filename);
if( fin.fail() )
{
cerr << "File open error." << endl;
return false;
}

for(int i=0; i {
vector m_tmp;
test_data.push_back(m_tmp);
for(int j=0; j {
double dm_tmp;
fin >> dm_tmp;
test_data[i].push_back( dm_tmp );
}
}
return true;
}

double KNN:: computeEuclidDistance(vector&a, vector &b)
{
double distance = 0.0;
for(int i=0; i<108; i++)
{
distance += ( a[i]-b[i] ) * ( a[i]-b[i] );
}
return distance;
}

//KNN分类函数
int KNN::classify(vector & testData)
{
vector< Dis > distances;
//计算testData到训练集每个点的欧几里得距离
for(int i=0; i<test_data.size(); i++)
{
Dis m_tmp;
m_tmp.first = computeEuclidDistance(testData, training_data[i].first);
//记录分类号
m_tmp.second = training_data[i].second;
distances.push_back(m_tmp);
}

//对计算出的欧几里得距离排序,从小到大
sort(distances.begin(),distances.end());

//对于前K个,即距离最近的k个点,返回包含点数最多的分类号,即该点的分类
vector poll( 10, 0 );
for(i=0; i<5; i++)//K=5
{
int vot = distances[i].second;
poll[vot] ++;
}
int res = -1;
int vots = -1;
for(i=1; i<=10; i++)
{
if(vots < poll[i])
{
vots = poll[i];
res = i;
}
}

CString str,str1;
for(i=0;i<8;i++)
{
// if(poll[i]=8)
str.Format("%d ",poll[i]);

    str1+=str;
}

::MessageBox(NULL,str1,"识别结果",NULL);
 return res;

}
//打印测试集判断结果
void KNN::PrintTestResult(char *filename)
{
ofstream fout(filename);

for(int i=0; i<test_data.size(); i++)
{
    int clsf = classify(test_data[i]);
    for(int j=0; j<test_data[i].size(); j++)
    {
        fout << test_data[i][j] << "\t";
    }

    fout << clsf << endl;
}
fout.close();
cout << "结果数据保存在文件out1.txt中,请查看。\n" ;

}

3个回答

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.06.06 12:55

http://blog.csdn.net/xlm289348/article/details/8876353
对比着看看,你一说逻辑错误,我就必须在了解算法基础看,不容易短时间看出

qq_28791175
qq_28791175   2015.06.06 08:37

新手,来凑热闹,只看不说话

frank_20080215
frank_20080215   2015.06.06 08:57

不错,写得挺好。恭喜

Csdn user default icon
上传中...
上传图片
插入图片