KMeans.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * @file KMeans.cpp
  3. * @brief K-Means
  4. * @author Erik Rodner, Alexander Freytag
  5. * @date 29-10-2007 (dd-mm-yyyy)
  6. */
  7. #ifdef NICE_USELIB_OPENMP
  8. #include <omp.h>
  9. #endif
  10. #include <set>
  11. #include <iostream>
  12. #include <string>
  13. #include "vislearning/math/cluster/KMeans.h"
  14. #include "vislearning/math/distances/genericDistance.h"
  15. using namespace OBJREC;
  16. using namespace std;
  17. using namespace NICE;
  18. #undef DEBUG_KMEANS
  19. KMeans::KMeans(const int & _noClusters, const std::string & _distanceType) :
  20. noClusters(_noClusters), distanceType(_distanceType)
  21. {
  22. //srand(time(NULL));
  23. this->distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  24. }
  25. KMeans::KMeans( const NICE::Config *conf, const std::string & _section)
  26. {
  27. this->distanceType = conf->gS( _section, "distanceType", "euclidean" );
  28. this->distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  29. this->d_minDelta = conf->gD( _section, "minDelta", 1e-5 );
  30. this->i_maxIterations = conf->gI( _section, "maxIterations", 200);
  31. this->noClusters = conf->gI( _section, "noClusters", 20);
  32. std::cerr << "KMeans::KMeans -- noClusters: " << this->noClusters << std::endl;
  33. }
  34. KMeans::~KMeans()
  35. {
  36. }
  37. void KMeans::initial_guess(const NICE::VVector & features, NICE::VVector & prototypes)
  38. {
  39. int j = 0;
  40. std::set<int, std::greater<int> > mark;
  41. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
  42. {
  43. int k;
  44. do
  45. {
  46. k = rand() % features.size();
  47. } while (mark.find(k) != mark.end());
  48. mark.insert(mark.begin(), k);
  49. *i = features[k];
  50. }
  51. }
  52. int KMeans::compute_prototypes(const VVector & features, VVector & prototypes,
  53. std::vector<double> & weights, const std::vector<int> & assignment)
  54. {
  55. int j = 0;
  56. // fprintf (stderr, "KMeans::compute_prototypes: init noClusters=%d\n", noClusters);
  57. for (int k = 0; k < this->noClusters; k++)
  58. {
  59. prototypes[k].set(0);
  60. weights[k] = 0;
  61. }
  62. // fprintf (stderr, "KMeans::compute_prototypes: compute means\n");
  63. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  64. {
  65. int k = assignment[j];
  66. NICE::Vector & p = prototypes[k];
  67. const NICE::Vector & x = *i;
  68. #ifdef DEBUG_KMEANS
  69. fprintf(
  70. stderr,
  71. "KMeans::compute_prototypes: std::vector %d has assignment %d\n",
  72. j, k);
  73. #endif
  74. p += x;
  75. #ifdef DEBUG_KMEANS
  76. std::cerr << "vector was : " << x << std::endl;
  77. std::cerr << "prototype for this class is now : " << p << std::endl;
  78. #endif
  79. weights[k]++;
  80. }
  81. // fprintf (stderr, "KMeans::compute_prototypes: scaling\n");
  82. #pragma omp parallel for
  83. for (int k = 0; k < this->noClusters; k++)
  84. {
  85. NICE::Vector & p = prototypes[k];
  86. #ifdef DEBUG_KMEANS
  87. std::cerr << "prototype for this class before scaling : " << p << std::endl;
  88. #endif
  89. // if (weights[k] <= 0)
  90. // {
  91. // return -1;
  92. // }
  93. if (weights[k] > 0)
  94. {
  95. p *= (1.0 / weights[k]);
  96. weights[k] = weights[k] / features.size();
  97. #ifdef DEBUG_KMEANS
  98. std::cerr << "prototype for this class after scaling with " << weights[k]
  99. << " : " << p << std::endl;
  100. #endif
  101. }
  102. }
  103. return 0;
  104. }
  105. double KMeans::compute_delta(const NICE::VVector & oldprototypes,
  106. const NICE::VVector & prototypes)
  107. {
  108. double distance = 0;
  109. for (uint k = 0; k < oldprototypes.size(); k++)
  110. {
  111. distance += this->distancefunction->calculate(oldprototypes[k], prototypes[k]);
  112. #ifdef DEBUG_KMEANS
  113. fprintf(stderr, "KMeans::compute_delta: Distance: %f",
  114. distancefunction->calculate(oldprototypes[k], prototypes[k]));
  115. #endif
  116. }
  117. return distance;
  118. }
  119. double KMeans::compute_assignments(const NICE::VVector & features,
  120. const NICE::VVector & prototypes, std::vector<int> & assignment)
  121. {
  122. // int index = 0;
  123. // for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
  124. uint noFeatures ( features.size() );
  125. #pragma omp parallel for
  126. for (int index = 0; index < noFeatures; index++)
  127. {
  128. // const NICE::Vector & x = *i;
  129. const NICE::Vector & x = features[index];
  130. double mindist = std::numeric_limits<double>::max();
  131. int minclass = 0;
  132. int c = 0;
  133. #ifdef DEBUG_KMEANS
  134. fprintf(stderr, "computing nearest prototype for std::vector %d\n",
  135. index);
  136. #endif
  137. for (VVector::const_iterator j = prototypes.begin(); j
  138. != prototypes.end(); j++, c++)
  139. {
  140. const NICE::Vector & p = *j;
  141. double distance = this->distancefunction->calculate(p, x);
  142. #ifdef DEBUG_KMEANS
  143. fprintf(stderr, "KMeans::compute_delta: Distance: %f",
  144. this->distancefunction->calculate(p, x));
  145. #endif
  146. #ifdef DEBUG_KMEANS
  147. std::cerr << p << std::endl;
  148. std::cerr << x << std::endl;
  149. fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
  150. #endif
  151. if (distance < mindist)
  152. {
  153. minclass = c;
  154. mindist = distance;
  155. }
  156. }
  157. assignment[index] = minclass;
  158. }
  159. return 0.0;
  160. }
  161. double KMeans::compute_weights(const NICE::VVector & features,
  162. std::vector<double> & weights, std::vector<int> & assignment)
  163. {
  164. for (int k = 0; k < this->noClusters; k++)
  165. weights[k] = 0;
  166. int j = 0;
  167. for (NICE::VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  168. {
  169. int k = assignment[j];
  170. weights[k]++;
  171. }
  172. #pragma omp parallel for
  173. for (int k = 0; k < this->noClusters; k++)
  174. weights[k] = weights[k] / features.size();
  175. return 0.0;
  176. }
  177. void KMeans::cluster(const NICE::VVector & features, NICE::VVector & prototypes,
  178. std::vector<double> & weights, std::vector<int> & assignment)
  179. {
  180. NICE::VVector oldprototypes;
  181. prototypes.clear();
  182. weights.clear();
  183. assignment.clear();
  184. weights.resize(noClusters, 0);
  185. assignment.resize(features.size(), 0);
  186. int dimension;
  187. if ((int) features.size() >= this->noClusters)
  188. dimension = features[0].size();
  189. else
  190. {
  191. std::ostringstream stringStream;
  192. stringStream << "FATAL ERROR: Not enough feature vectors provided for kMeans \n k: " << this->noClusters << " numberOfFeatures: " << features.size() << "\n";
  193. std::string errormessage ( stringStream.str() );
  194. throw NICE::Exception( errormessage );
  195. }
  196. for (int k = 0; k < this->noClusters; k++)
  197. {
  198. prototypes.push_back(Vector(dimension));
  199. prototypes[k].set(0);
  200. }
  201. bool successKMeans ( false );
  202. int iterations ( 0 );
  203. double delta ( std::numeric_limits<double>::max() );
  204. while ( !successKMeans )
  205. {
  206. //we assume that this run will be successful
  207. successKMeans = true;
  208. this->initial_guess(features, prototypes);
  209. iterations = 0;
  210. delta = std::numeric_limits<double>::max();
  211. do
  212. {
  213. iterations++;
  214. this->compute_assignments(features, prototypes, assignment);
  215. if (iterations > 1)
  216. oldprototypes = prototypes;
  217. #ifdef DEBUG_KMEANS
  218. fprintf(stderr, "KMeans::cluster compute_prototypes\n");
  219. #endif
  220. if ( this->compute_prototypes(features, prototypes, weights, assignment) < 0 )
  221. {
  222. fprintf(stderr, "KMeans::cluster restart\n");
  223. successKMeans = false;
  224. break;
  225. }
  226. #ifdef DEBUG_KMEANS
  227. fprintf(stderr, "KMeans::cluster compute_delta\n");
  228. #endif
  229. if (iterations > 1)
  230. delta = this->compute_delta(oldprototypes, prototypes);
  231. #ifdef DEBUG_KMEANS
  232. print_iteration(iterations, prototypes, delta);
  233. #endif
  234. } while ((delta > d_minDelta) && (iterations < i_maxIterations));
  235. }
  236. #ifdef DEBUG_KMEANS
  237. fprintf(stderr, "KMeans::cluster: iterations = %d, delta = %f\n", iterations, delta);
  238. #endif
  239. this->compute_weights(features, weights, assignment);
  240. }
  241. void KMeans::print_iteration(int iterations, NICE::VVector & prototypes, double delta)
  242. {
  243. if (iterations > 1)
  244. fprintf(stderr, "KMeans::cluster: iteration=%d delta=%f\n", iterations,
  245. delta);
  246. else
  247. fprintf(stderr, "KMeans::cluster: iteration=%d\n", iterations);
  248. int k = 0;
  249. for (NICE::VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
  250. {
  251. fprintf(stderr, "class (%d)\n", k);
  252. std::cerr << "prototype = " << (*i) << std::endl;
  253. }
  254. }