当前位置:   article > 正文

【机器学习实战之一】:C++实现K-近邻算法KNN_两个图像的特征向量应用knn模型进行匹配

两个图像的特征向量应用knn模型进行匹配

本文不对KNN算法做过多的理论上的解释,主要是针对问题,进行算法的设计和代码的注解。

KNN算法:

优点:精度高、对异常值不敏感、无数据输入假定。

缺点:计算复杂度高、空间复杂度高。

适用数据范围:数值型和标称性。

工作原理:存在一个样本数据集合,也称作训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一个数据与所属分类的对应关系。输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应的特征进行比较,然后算法提取样本集中特征最相似数据(最近邻)的分类标签。一般来说,我们只选择样本数据及中前k个最相似的数据,这就是k-近邻算法中k的出处,通常k选择不大于20的整数。最后,选择k个最相似数据中出现次数最多的分类,作为新数据的分类。

K-近邻算法的一般流程:

(1)收集数据:可以使用任何方法

(2)准备数据:距离计算所需要的数值,最好是结构化的数据格式

(3)分析数据:可以使用任何方法

(4)训练算法:此步骤不适用k-邻近算法

(5)测试算法:计算错误率

(6)使用算法:首先需要输入样本数据和结构化的输出结果,然后运行k-近邻算法判定输入数据分别属于哪个分类,最后应用对计算出的分类执行后续的处理。


问题一:现在我们假设一个场景,就是要为坐标上的点进行分类,如下图所示:



上图一共12个左边点,每个坐标点都有相应的坐标(x,y)以及它所属的类别A/B,那么现在需要做的就是给定一个点坐标(x1,y1),判断它属于的类别A或者B。

所有的坐标点在data.txt文件中:

  1. 0.0 1.1 A
  2. 1.0 1.0 A
  3. 2.0 1.0 B
  4. 0.5 0.5 A
  5. 2.5 0.5 B
  6. 0.0 0.0 A
  7. 1.0 0.0 A
  8. 2.0 0.0 B
  9. 3.0 0.0 B
  10. 0.0 -1.0 A
  11. 1.0 -1.0 A
  12. 2.0 -1.0 B


step1:通过类的默认构造函数去初始化训练数据集dataSet和测试数据testData。

step2:用get_distance()来计算测试数据testData和每一个训练数据dataSet[index]的距离,用map_index_dis来保存键值对<index,distance>,其中index代表第几个训练数据,distance代表第index个训练数据和测试数据的距离。

step3:将map_index_dis按照value值(即distance值)从小到大的顺序排序,然后取前k个最小的value值,用map_label_freq来记录每一个类标签出现的频率。

step4:遍历map_label_freq中的value值,返回value最大的那个key值,就是测试数据属于的类。


看一下代码KNN_0.cc:

  1. #include<iostream>
  2. #include<map>
  3. #include<vector>
  4. #include<stdio.h>
  5. #include<cmath>
  6. #include<cstdlib>
  7. #include<algorithm>
  8. #include<fstream>
  9. using namespace std;
  10. typedef char tLabel;
  11. typedef double tData;
  12. typedef pair<int,double> PAIR;
  13. const int colLen = 2;
  14. const int rowLen = 12;
  15. ifstream fin;
  16. ofstream fout;
  17. class KNN
  18. {
  19. private:
  20. tData dataSet[rowLen][colLen];
  21. tLabel labels[rowLen];
  22. tData testData[colLen];
  23. int k;
  24. map<int,double> map_index_dis;
  25. map<tLabel,int> map_label_freq;
  26. double get_distance(tData *d1,tData *d2);
  27. public:
  28. KNN(int k);
  29. void get_all_distance();
  30. void get_max_freq_label();
  31. struct CmpByValue
  32. {
  33. bool operator() (const PAIR& lhs,const PAIR& rhs)
  34. {
  35. return lhs.second < rhs.second;
  36. }
  37. };
  38. };
  39. KNN::KNN(int k)
  40. {
  41. this->k = k;
  42. fin.open("data.txt");
  43. if(!fin)
  44. {
  45. cout<<"can not open the file data.txt"<<endl;
  46. exit(1);
  47. }
  48. /* input the dataSet */
  49. for(int i=0;i<rowLen;i++)
  50. {
  51. for(int j=0;j<colLen;j++)
  52. {
  53. fin>>dataSet[i][j];
  54. }
  55. fin>>labels[i];
  56. }
  57. cout<<"please input the test data :"<<endl;
  58. /* inuput the test data */
  59. for(int i=0;i<colLen;i++)
  60. cin>>testData[i];
  61. }
  62. /*
  63. * calculate the distance between test data and dataSet[i]
  64. */
  65. double KNN:: get_distance(tData *d1,tData *d2)
  66. {
  67. double sum = 0;
  68. for(int i=0;i<colLen;i++)
  69. {
  70. sum += pow( (d1[i]-d2[i]) , 2 );
  71. }
  72. // cout<<"the sum is = "<<sum<<endl;
  73. return sqrt(sum);
  74. }
  75. /*
  76. * calculate all the distance between test data and each training data
  77. */
  78. void KNN:: get_all_distance()
  79. {
  80. double distance;
  81. int i;
  82. for(i=0;i<rowLen;i++)
  83. {
  84. distance = get_distance(dataSet[i],testData);
  85. //<key,value> => <i,distance>
  86. map_index_dis[i] = distance;
  87. }
  88. //traverse the map to print the index and distance
  89. map<int,double>::const_iterator it = map_index_dis.begin();
  90. while(it!=map_index_dis.end())
  91. {
  92. cout<<"index = "<<it->first<<" distance = "<<it->second<<endl;
  93. it++;
  94. }
  95. }
  96. /*
  97. * check which label the test data belongs to to classify the test data
  98. */
  99. void KNN:: get_max_freq_label()
  100. {
  101. //transform the map_index_dis to vec_index_dis
  102. vector<PAIR> vec_index_dis( map_index_dis.begin(),map_index_dis.end() );
  103. //sort the vec_index_dis by distance from low to high to get the nearest data
  104. sort(vec_index_dis.begin(),vec_index_dis.end(),CmpByValue());
  105. for(int i=0;i<k;i++)
  106. {
  107. cout<<"the index = "<<vec_index_dis[i].first<<" the distance = "<<vec_index_dis[i].second<<" the label = "<<labels[vec_index_dis[i].first]<<" the coordinate ( "<<dataSet[ vec_index_dis[i].first ][0]<<","<<dataSet[ vec_index_dis[i].first ][1]<<" )"<<endl;
  108. //calculate the count of each label
  109. map_label_freq[ labels[ vec_index_dis[i].first ] ]++;
  110. }
  111. map<tLabel,int>::const_iterator map_it = map_label_freq.begin();
  112. tLabel label;
  113. int max_freq = 0;
  114. //find the most frequent label
  115. while( map_it != map_label_freq.end() )
  116. {
  117. if( map_it->second > max_freq )
  118. {
  119. max_freq = map_it->second;
  120. label = map_it->first;
  121. }
  122. map_it++;
  123. }
  124. cout<<"The test data belongs to the "<<label<<" label"<<endl;
  125. }
  126. int main()
  127. {
  128. int k ;
  129. cout<<"please input the k value : "<<endl;
  130. cin>>k;
  131. KNN knn(k);
  132. knn.get_all_distance();
  133. knn.get_max_freq_label();
  134. system("pause");
  135. return 0;
  136. }


我们来测试一下这个分类器(k=5):

testData(5.0,5.0):



testData(-5.0,-5.0):



testData(1.6,0.5):



分类结果的正确性可以通过坐标系来判断,可以看出结果都是正确的。


问题二:使用k-近邻算法改进约会网站的匹配效果

情景如下:我的朋友海伦一直使用在线约会网站寻找合适自己的约会对象。尽管约会网站会推荐不同的人选,但她没有从中找到喜欢的人。经过一番总结,她发现曾交往过三种类型的人:

>不喜欢的人

>魅力一般的人

>极具魅力的人

尽管发现了上述规律,但海伦依然无法将约会网站推荐的匹配对象归入恰当的分类。她觉得可以在周一到周五约会哪些魅力一般的人,而周末则更喜欢与那些极具魅力的人为伴。海伦希望我们的分类软件可以更好的帮助她将匹配对象划分到确切的分类中。此外海伦还收集了一些约会网站未曾记录的数据信息,她认为这些数据更有助于匹配对象的归类。

海伦已经收集数据一段时间。她把这些数据存放在文本文件datingTestSet.txt(文件链接:http://yunpan.cn/QUL6SxtiJFPfN,提取码:f246)中,每个样本占据一行,总共有1000行。海伦的样本主要包含3中特征:

>每年获得的飞行常客里程数

>玩视频游戏所耗时间的百分比

>每周消费的冰淇淋公升数


数据预处理:归一化数据

我们可以看到,每年获取的飞行常客里程数对于计算结果的影响将远大于其他两个特征。而产生这种现象的唯一原因,仅仅是因为飞行常客书远大于其他特征值。但是这三种特征是同等重要的,因此作为三个等权重的特征之一,飞行常客数不应该如此严重地影响到计算结果。

处理这种不同取值范围的特征值时,我们通常采用的方法是数值归一化,如将取值范围处理为0到1或者-1到1之间。

公式为:newValue = (oldValue - min) / (max - min)

其中min和max分别是数据集中的最小特征值和最大特征值。我们增加一个auto_norm_data函数来归一化数据。

同事还要设计一个get_error_rate来计算分类的错误率,选总体数据的10%作为测试数据,90%作为训练数据,当然也可以自己设定百分比。

其他的算法设计都与问题一类似。


代码如下KNN_2.cc(k=7):

  1. /* add the get_error_rate function */
  2. #include<iostream>
  3. #include<map>
  4. #include<vector>
  5. #include<stdio.h>
  6. #include<cmath>
  7. #include<cstdlib>
  8. #include<algorithm>
  9. #include<fstream>
  10. using namespace std;
  11. typedef string tLabel;
  12. typedef double tData;
  13. typedef pair<int,double> PAIR;
  14. const int MaxColLen = 10;
  15. const int MaxRowLen = 10000;
  16. ifstream fin;
  17. ofstream fout;
  18. class KNN
  19. {
  20. private:
  21. tData dataSet[MaxRowLen][MaxColLen];
  22. tLabel labels[MaxRowLen];
  23. tData testData[MaxColLen];
  24. int rowLen;
  25. int colLen;
  26. int k;
  27. int test_data_num;
  28. map<int,double> map_index_dis;
  29. map<tLabel,int> map_label_freq;
  30. double get_distance(tData *d1,tData *d2);
  31. public:
  32. KNN(int k , int rowLen , int colLen , char *filename);
  33. void get_all_distance();
  34. tLabel get_max_freq_label();
  35. void auto_norm_data();
  36. void get_error_rate();
  37. struct CmpByValue
  38. {
  39. bool operator() (const PAIR& lhs,const PAIR& rhs)
  40. {
  41. return lhs.second < rhs.second;
  42. }
  43. };
  44. ~KNN();
  45. };
  46. KNN::~KNN()
  47. {
  48. fin.close();
  49. fout.close();
  50. map_index_dis.clear();
  51. map_label_freq.clear();
  52. }
  53. KNN::KNN(int k , int row ,int col , char *filename)
  54. {
  55. this->rowLen = row;
  56. this->colLen = col;
  57. this->k = k;
  58. test_data_num = 0;
  59. fin.open(filename);
  60. fout.open("result.txt");
  61. if( !fin || !fout )
  62. {
  63. cout<<"can not open the file"<<endl;
  64. exit(0);
  65. }
  66. for(int i=0;i<rowLen;i++)
  67. {
  68. for(int j=0;j<colLen;j++)
  69. {
  70. fin>>dataSet[i][j];
  71. fout<<dataSet[i][j]<<" ";
  72. }
  73. fin>>labels[i];
  74. fout<<labels[i]<<endl;
  75. }
  76. }
  77. void KNN:: get_error_rate()
  78. {
  79. int i,j,count = 0;
  80. tLabel label;
  81. cout<<"please input the number of test data : "<<endl;
  82. cin>>test_data_num;
  83. for(i=0;i<test_data_num;i++)
  84. {
  85. for(j=0;j<colLen;j++)
  86. {
  87. testData[j] = dataSet[i][j];
  88. }
  89. get_all_distance();
  90. label = get_max_freq_label();
  91. if( label!=labels[i] )
  92. count++;
  93. map_index_dis.clear();
  94. map_label_freq.clear();
  95. }
  96. cout<<"the error rate is = "<<(double)count/(double)test_data_num<<endl;
  97. }
  98. double KNN:: get_distance(tData *d1,tData *d2)
  99. {
  100. double sum = 0;
  101. for(int i=0;i<colLen;i++)
  102. {
  103. sum += pow( (d1[i]-d2[i]) , 2 );
  104. }
  105. //cout<<"the sum is = "<<sum<<endl;
  106. return sqrt(sum);
  107. }
  108. void KNN:: get_all_distance()
  109. {
  110. double distance;
  111. int i;
  112. for(i=test_data_num;i<rowLen;i++)
  113. {
  114. distance = get_distance(dataSet[i],testData);
  115. map_index_dis[i] = distance;
  116. }
  117. // map<int,double>::const_iterator it = map_index_dis.begin();
  118. // while(it!=map_index_dis.end())
  119. // {
  120. // cout<<"index = "<<it->first<<" distance = "<<it->second<<endl;
  121. // it++;
  122. // }
  123. }
  124. tLabel KNN:: get_max_freq_label()
  125. {
  126. vector<PAIR> vec_index_dis( map_index_dis.begin(),map_index_dis.end() );
  127. sort(vec_index_dis.begin(),vec_index_dis.end(),CmpByValue());
  128. for(int i=0;i<k;i++)
  129. {
  130. cout<<"the index = "<<vec_index_dis[i].first<<" the distance = "<<vec_index_dis[i].second<<" the label = "<<labels[ vec_index_dis[i].first ]<<" the coordinate ( ";
  131. int j;
  132. for(j=0;j<colLen-1;j++)
  133. {
  134. cout<<dataSet[ vec_index_dis[i].first ][j]<<",";
  135. }
  136. cout<<dataSet[ vec_index_dis[i].first ][j]<<" )"<<endl;
  137. map_label_freq[ labels[ vec_index_dis[i].first ] ]++;
  138. }
  139. map<tLabel,int>::const_iterator map_it = map_label_freq.begin();
  140. tLabel label;
  141. int max_freq = 0;
  142. while( map_it != map_label_freq.end() )
  143. {
  144. if( map_it->second > max_freq )
  145. {
  146. max_freq = map_it->second;
  147. label = map_it->first;
  148. }
  149. map_it++;
  150. }
  151. cout<<"The test data belongs to the "<<label<<" label"<<endl;
  152. return label;
  153. }
  154. void KNN::auto_norm_data()
  155. {
  156. tData maxa[colLen] ;
  157. tData mina[colLen] ;
  158. tData range[colLen] ;
  159. int i,j;
  160. for(i=0;i<colLen;i++)
  161. {
  162. maxa[i] = max(dataSet[0][i],dataSet[1][i]);
  163. mina[i] = min(dataSet[0][i],dataSet[1][i]);
  164. }
  165. for(i=2;i<rowLen;i++)
  166. {
  167. for(j=0;j<colLen;j++)
  168. {
  169. if( dataSet[i][j]>maxa[j] )
  170. {
  171. maxa[j] = dataSet[i][j];
  172. }
  173. else if( dataSet[i][j]<mina[j] )
  174. {
  175. mina[j] = dataSet[i][j];
  176. }
  177. }
  178. }
  179. for(i=0;i<colLen;i++)
  180. {
  181. range[i] = maxa[i] - mina[i] ;
  182. //normalize the test data set
  183. testData[i] = ( testData[i] - mina[i] )/range[i] ;
  184. }
  185. //normalize the training data set
  186. for(i=0;i<rowLen;i++)
  187. {
  188. for(j=0;j<colLen;j++)
  189. {
  190. dataSet[i][j] = ( dataSet[i][j] - mina[j] )/range[j];
  191. }
  192. }
  193. }
  194. int main(int argc , char** argv)
  195. {
  196. int k,row,col;
  197. char *filename;
  198. if( argc!=5 )
  199. {
  200. cout<<"The input should be like this : ./a.out k row col filename"<<endl;
  201. exit(1);
  202. }
  203. k = atoi(argv[1]);
  204. row = atoi(argv[2]);
  205. col = atoi(argv[3]);
  206. filename = argv[4];
  207. KNN knn(k,row,col,filename);
  208. knn.auto_norm_data();
  209. knn.get_error_rate();
  210. // knn.get_all_distance();
  211. // knn.get_max_freq_label();
  212. return 0;
  213. }

makefile:

  1. target:
  2. g++ KNN_2.cc
  3. ./a.out 7 1000 3 datingTestSet.txt


结果:

可以看到:在测试数据为10%和训练数据90%的比例下,可以看到错误率为4%,相对来讲还是很准确的。


构建完整可用系统:

已经通过使用数据对分类器进行了测试,现在可以使用分类器为海伦来对人进行分类。

代码KNN_1.cc(k=7):

  1. /* add the auto_norm_data */
  2. #include<iostream>
  3. #include<map>
  4. #include<vector>
  5. #include<stdio.h>
  6. #include<cmath>
  7. #include<cstdlib>
  8. #include<algorithm>
  9. #include<fstream>
  10. using namespace std;
  11. typedef string tLabel;
  12. typedef double tData;
  13. typedef pair<int,double> PAIR;
  14. const int MaxColLen = 10;
  15. const int MaxRowLen = 10000;
  16. ifstream fin;
  17. ofstream fout;
  18. class KNN
  19. {
  20. private:
  21. tData dataSet[MaxRowLen][MaxColLen];
  22. tLabel labels[MaxRowLen];
  23. tData testData[MaxColLen];
  24. int rowLen;
  25. int colLen;
  26. int k;
  27. map<int,double> map_index_dis;
  28. map<tLabel,int> map_label_freq;
  29. double get_distance(tData *d1,tData *d2);
  30. public:
  31. KNN(int k , int rowLen , int colLen , char *filename);
  32. void get_all_distance();
  33. tLabel get_max_freq_label();
  34. void auto_norm_data();
  35. struct CmpByValue
  36. {
  37. bool operator() (const PAIR& lhs,const PAIR& rhs)
  38. {
  39. return lhs.second < rhs.second;
  40. }
  41. };
  42. ~KNN();
  43. };
  44. KNN::~KNN()
  45. {
  46. fin.close();
  47. fout.close();
  48. map_index_dis.clear();
  49. map_label_freq.clear();
  50. }
  51. KNN::KNN(int k , int row ,int col , char *filename)
  52. {
  53. this->rowLen = row;
  54. this->colLen = col;
  55. this->k = k;
  56. fin.open(filename);
  57. fout.open("result.txt");
  58. if( !fin || !fout )
  59. {
  60. cout<<"can not open the file"<<endl;
  61. exit(0);
  62. }
  63. //input the training data set
  64. for(int i=0;i<rowLen;i++)
  65. {
  66. for(int j=0;j<colLen;j++)
  67. {
  68. fin>>dataSet[i][j];
  69. fout<<dataSet[i][j]<<" ";
  70. }
  71. fin>>labels[i];
  72. fout<<labels[i]<<endl;
  73. }
  74. //input the test data
  75. cout<<"frequent flier miles earned per year?";
  76. cin>>testData[0];
  77. cout<<"percentage of time spent playing video games?";
  78. cin>>testData[1];
  79. cout<<"liters of ice cream consumed per year?";
  80. cin>>testData[2];
  81. }
  82. double KNN:: get_distance(tData *d1,tData *d2)
  83. {
  84. double sum = 0;
  85. for(int i=0;i<colLen;i++)
  86. {
  87. sum += pow( (d1[i]-d2[i]) , 2 );
  88. }
  89. return sqrt(sum);
  90. }
  91. void KNN:: get_all_distance()
  92. {
  93. double distance;
  94. int i;
  95. for(i=0;i<rowLen;i++)
  96. {
  97. distance = get_distance(dataSet[i],testData);
  98. map_index_dis[i] = distance;
  99. }
  100. // map<int,double>::const_iterator it = map_index_dis.begin();
  101. // while(it!=map_index_dis.end())
  102. // {
  103. // cout<<"index = "<<it->first<<" distance = "<<it->second<<endl;
  104. // it++;
  105. // }
  106. }
  107. tLabel KNN:: get_max_freq_label()
  108. {
  109. vector<PAIR> vec_index_dis( map_index_dis.begin(),map_index_dis.end() );
  110. sort(vec_index_dis.begin(),vec_index_dis.end(),CmpByValue());
  111. for(int i=0;i<k;i++)
  112. {
  113. /*
  114. cout<<"the index = "<<vec_index_dis[i].first<<" the distance = "<<vec_index_dis[i].second<<" the label = "<<labels[ vec_index_dis[i].first ]<<" the coordinate ( ";
  115. int j;
  116. for(j=0;j<colLen-1;j++)
  117. {
  118. cout<<dataSet[ vec_index_dis[i].first ][j]<<",";
  119. }
  120. cout<<dataSet[ vec_index_dis[i].first ][j]<<" )"<<endl;
  121. */
  122. map_label_freq[ labels[ vec_index_dis[i].first ] ]++;
  123. }
  124. map<tLabel,int>::const_iterator map_it = map_label_freq.begin();
  125. tLabel label;
  126. int max_freq = 0;
  127. /*traverse the map_label_freq to get the most frequent label*/
  128. while( map_it != map_label_freq.end() )
  129. {
  130. if( map_it->second > max_freq )
  131. {
  132. max_freq = map_it->second;
  133. label = map_it->first;
  134. }
  135. map_it++;
  136. }
  137. return label;
  138. }
  139. /*
  140. * normalize the training data set
  141. */
  142. void KNN::auto_norm_data()
  143. {
  144. tData maxa[colLen] ;
  145. tData mina[colLen] ;
  146. tData range[colLen] ;
  147. int i,j;
  148. for(i=0;i<colLen;i++)
  149. {
  150. maxa[i] = max(dataSet[0][i],dataSet[1][i]);
  151. mina[i] = min(dataSet[0][i],dataSet[1][i]);
  152. }
  153. for(i=2;i<rowLen;i++)
  154. {
  155. for(j=0;j<colLen;j++)
  156. {
  157. if( dataSet[i][j]>maxa[j] )
  158. {
  159. maxa[j] = dataSet[i][j];
  160. }
  161. else if( dataSet[i][j]<mina[j] )
  162. {
  163. mina[j] = dataSet[i][j];
  164. }
  165. }
  166. }
  167. for(i=0;i<colLen;i++)
  168. {
  169. range[i] = maxa[i] - mina[i] ;
  170. //normalize the test data set
  171. testData[i] = ( testData[i] - mina[i] )/range[i] ;
  172. }
  173. //normalize the training data set
  174. for(i=0;i<rowLen;i++)
  175. {
  176. for(j=0;j<colLen;j++)
  177. {
  178. dataSet[i][j] = ( dataSet[i][j] - mina[j] )/range[j];
  179. }
  180. }
  181. }
  182. int main(int argc , char** argv)
  183. {
  184. int k,row,col;
  185. char *filename;
  186. if( argc!=5 )
  187. {
  188. cout<<"The input should be like this : ./a.out k row col filename"<<endl;
  189. exit(1);
  190. }
  191. k = atoi(argv[1]);
  192. row = atoi(argv[2]);
  193. col = atoi(argv[3]);
  194. filename = argv[4];
  195. KNN knn(k,row,col,filename);
  196. knn.auto_norm_data();
  197. knn.get_all_distance();
  198. cout<<"You will probably like this person : "<<knn.get_max_freq_label()<<endl;
  199. return 0;
  200. }


makefile:

  1. target:
  2. g++ KNN_1.cc
  3. ./a.out 7 1000 3 datingTestSet.txt

结果:



KNN_1.cc和KNN_2.cc的差别就在于后者对分类器的性能(即分类错误率)进行分析,而前者直接对具体实际的数据进行了分类。


注明出处:http://blog.csdn.net/lavorange/article/details/16924705


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/801244
推荐阅读
相关标签
  

闽ICP备14008679号

        
cppcmd=keepalive&