KMeansHeuristic.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /**
  2. * @file KMeansHeuristic.cpp
  3. * @brief K-Means
  4. * @author Erik Rodner, Michael Koch, Michael Trummer
  5. * @date 02/04/2011
  6. */
  7. #include <iostream>
  8. #include "vislearning/math/cluster/KMeansHeuristic.h"
  9. #include "vislearning/math/distances/genericDistance.h"
  10. #include <set>
  11. using namespace OBJREC;
  12. using namespace std;
  13. using namespace NICE;
  14. #undef DEBUG_KMeansHeuristic
  15. ///////////////////// ///////////////////// /////////////////////
  16. // CONSTRUCTORS / DESTRUCTORS
  17. ///////////////////// ///////////////////// /////////////////////
  18. KMeansHeuristic::KMeansHeuristic() : ClusterAlgorithm()
  19. {
  20. this->noClusters = 20;
  21. this->distanceType = "euclidean";
  22. this->distancefunction = NULL;
  23. }
  24. KMeansHeuristic::KMeansHeuristic(int _noClusters, string _distanceType) :
  25. noClusters(_noClusters), distanceType(_distanceType)
  26. {
  27. //srand(time(NULL));
  28. this->distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  29. }
  30. KMeansHeuristic::KMeansHeuristic( const NICE::Config * _conf, const std::string & _confSection)
  31. {
  32. this->initFromConfig( _conf, _confSection );
  33. }
  34. KMeansHeuristic::~KMeansHeuristic()
  35. {
  36. if ( this->distancefunction != NULL )
  37. {
  38. delete this->distancefunction;
  39. this->distancefunction = NULL ;
  40. }
  41. }
  42. void KMeansHeuristic::initFromConfig( const NICE::Config* _conf, const std::string& _confSection )
  43. {
  44. this->noClusters = _conf->gI( _confSection, "noClusters", 20);
  45. this->distanceType = _conf->gS( _confSection, "distanceType", "euclidean" );
  46. this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
  47. }
  48. ///////////////////// ///////////////////// /////////////////////
  49. // CLUSTERING STUFF
  50. ///////////////////// ///////////////////// //////////////////
  51. void KMeansHeuristic::initial_guess(const VVector & features,
  52. VVector & prototypes)
  53. {
  54. int j = 0;
  55. std::set<int, std::greater<int> > mark;
  56. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
  57. {
  58. int k;
  59. do
  60. {
  61. k = rand() % features.size();
  62. } while (mark.find(k) != mark.end());
  63. mark.insert(mark.begin(), k);
  64. *i = features[k];
  65. }
  66. }
  67. // re-init cluster means
  68. int KMeansHeuristic::robust_prototypes(const VVector &features, VVector &prototypes,
  69. std::vector<double> & weights, const std::vector<int> & assignment)
  70. {
  71. if (features.size() > 0)
  72. {
  73. int dim = features[0].size();
  74. weights.assign(weights.size(), 0.0);
  75. int m = 0;
  76. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, m++)
  77. {
  78. NICE::Vector & p = *i;
  79. if (NICE::isNaN(p[0]))
  80. {
  81. continue;
  82. }
  83. int clustersize = 0;
  84. vector<int> clusterassign(features.size(), 0);
  85. for (int a = 0; a < (int) assignment.size(); a++)
  86. {
  87. if (assignment[a] == m)
  88. {
  89. clusterassign[a] = 1;
  90. clustersize++;
  91. }
  92. }
  93. //cout << "size " << clustersize << endl;
  94. int cnt = 0;
  95. while (cnt < clustersize/4)
  96. {
  97. //find feature with largest distance to the cluster mean
  98. double dist = 0, maxdist = 0;
  99. int maxdistind = 0;
  100. for (int a = 0; a < (int) clusterassign.size(); a++)
  101. {
  102. if (clusterassign[a] == 1)
  103. {
  104. dist = 0;
  105. dist += distancefunction->calculate(p, features[a]);
  106. if (dist > maxdist)
  107. {
  108. maxdist = dist;
  109. maxdistind = a;
  110. }
  111. }
  112. }
  113. //detach max-dist feature from the cluster
  114. clusterassign[maxdistind] = 0;
  115. cnt++;
  116. }
  117. //recalculate the cluster mean
  118. p=0.0;
  119. for (int a = 0; a < (int) clusterassign.size(); a++)
  120. {
  121. if (clusterassign[a] == 1)
  122. {
  123. if (NICE::isNaN(features[a][0]))
  124. continue;
  125. p += features[a];
  126. weights[m]++;
  127. }
  128. }
  129. if (weights[m] <= 0)
  130. {
  131. return -1;
  132. }
  133. for (int d = 0; d < dim; d++)
  134. {
  135. p[d] /= weights[m];
  136. }
  137. #ifdef DEBUG_KMeansHeuristic
  138. cerr << "prototype for class" << m << ":" << p << endl;
  139. #endif
  140. }
  141. }
  142. return 0;
  143. }
  144. double KMeansHeuristic::compute_delta(const VVector & oldprototypes,
  145. const VVector & prototypes)
  146. {
  147. double distance = 0;
  148. for (uint k = 0; k < oldprototypes.size(); k++)
  149. distance
  150. += distancefunction->calculate(oldprototypes[k], prototypes[k]);
  151. return distance;
  152. }
  153. double KMeansHeuristic::compute_assignments(const VVector & features,
  154. const VVector & prototypes, std::vector<int> & assignment)
  155. {
  156. int index = 0;
  157. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
  158. {
  159. const NICE::Vector & x = *i;
  160. double mindist = std::numeric_limits<double>::max();
  161. int minclass = 0;
  162. int c = 0;
  163. #ifdef DEBUG_KMeansHeuristic
  164. fprintf(stderr, "computing nearest prototype for std::vector %d\n",
  165. index);
  166. #endif
  167. for (VVector::const_iterator j = prototypes.begin(); j
  168. != prototypes.end(); j++, c++)
  169. {
  170. const NICE::Vector & p = *j;
  171. double distance = distancefunction->calculate(p, x);
  172. #ifdef DEBUG_KMeansHeuristic
  173. fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
  174. #endif
  175. if (distance < mindist)
  176. {
  177. minclass = c;
  178. mindist = distance;
  179. }
  180. }
  181. assignment[index] = minclass;
  182. }
  183. return 0.0;
  184. }
  185. double KMeansHeuristic::compute_weights(const VVector & features, std::vector<
  186. double> & weights, std::vector<int> & assignment)
  187. {
  188. for (int k = 0; k < noClusters; k++)
  189. weights[k] = 0;
  190. int j = 0;
  191. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  192. {
  193. int k = assignment[j];
  194. weights[k]++;
  195. }
  196. for (int k = 0; k < noClusters; k++)
  197. weights[k] = weights[k] / features.size();
  198. return 0.0;
  199. }
  200. void KMeansHeuristic::cluster(const VVector & features, VVector & prototypes,
  201. std::vector<double> & weights, std::vector<int> & assignment)
  202. {
  203. VVector oldprototypes;
  204. prototypes.clear();
  205. weights.clear();
  206. assignment.clear();
  207. weights.resize(noClusters, 0);
  208. assignment.resize(features.size(), 0);
  209. int dimension;
  210. if ((int) features.size() >= noClusters)
  211. dimension = features[0].size();
  212. else
  213. {
  214. fprintf(stderr,
  215. "FATAL ERROR: Not enough feature vectors provided for KMeansHeuristic\n");
  216. exit(-1);
  217. }
  218. for (int k = 0; k < noClusters; k++)
  219. {
  220. prototypes.push_back(Vector(dimension));
  221. prototypes[k].set(0);
  222. }
  223. KMeansHeuristic_Restart:
  224. initial_guess(features, prototypes);
  225. int iterations = 0;
  226. double delta = std::numeric_limits<double>::max();
  227. const double minDelta = 1e-5;
  228. const int maxIterations = 200;
  229. do
  230. {
  231. iterations++;
  232. compute_assignments(features, prototypes, assignment);
  233. if (iterations > 1)
  234. oldprototypes = prototypes;
  235. #ifdef DEBUG_KMeansHeuristic
  236. fprintf(stderr, "KMeansHeuristic::cluster compute_prototypes\n");
  237. #endif
  238. //if (compute_prototypes(features, prototypes, weights, assignment) < 0)
  239. if (robust_prototypes(features, prototypes, weights, assignment) < 0)
  240. {
  241. fprintf(stderr, "KMeansHeuristic::cluster restart\n");
  242. goto KMeansHeuristic_Restart;
  243. }
  244. #ifdef DEBUG_KMeansHeuristic
  245. fprintf(stderr, "KMeansHeuristic::cluster compute_delta\n");
  246. #endif
  247. if (iterations > 1)
  248. delta = compute_delta(oldprototypes, prototypes);
  249. #ifdef DEBUG_KMeansHeuristic
  250. print_iteration(iterations, prototypes, delta);
  251. #endif
  252. } while ((delta > minDelta) && (iterations < maxIterations));
  253. #ifdef DEBUG_KMeansHeuristic
  254. fprintf(stderr, "KMeansHeuristic::cluster: iterations = %d, delta = %f\n",
  255. iterations, delta);
  256. #endif
  257. compute_weights(features, weights, assignment);
  258. }
  259. void KMeansHeuristic::print_iteration(int iterations, VVector & prototypes,
  260. double delta)
  261. {
  262. if (iterations > 1)
  263. fprintf(stderr, "KMeansHeuristic::cluster: iteration=%d delta=%f\n",
  264. iterations, delta);
  265. else
  266. fprintf(stderr, "KMeansHeuristic::cluster: iteration=%d\n", iterations);
  267. int k = 0;
  268. for (VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
  269. {
  270. fprintf(stderr, "class (%d)\n", k);
  271. cerr << "prototype = " << (*i) << endl;
  272. }
  273. }
  274. ///////////////////// INTERFACE PERSISTENT /////////////////////
  275. // interface specific methods for store and restore
  276. ///////////////////// INTERFACE PERSISTENT /////////////////////
  277. void KMeansHeuristic::restore ( std::istream & is, int format )
  278. {
  279. //delete everything we knew so far...
  280. this->clear();
  281. if ( is.good() )
  282. {
  283. std::string tmp;
  284. is >> tmp; //class name
  285. if ( ! this->isStartTag( tmp, "KMeansHeuristic" ) )
  286. {
  287. std::cerr << " WARNING - attempt to restore KMeansHeuristic, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  288. throw;
  289. }
  290. bool b_endOfBlock ( false ) ;
  291. while ( !b_endOfBlock )
  292. {
  293. is >> tmp; // start of block
  294. if ( this->isEndTag( tmp, "KMeansHeuristic" ) )
  295. {
  296. b_endOfBlock = true;
  297. continue;
  298. }
  299. tmp = this->removeStartTag ( tmp );
  300. if ( tmp.compare("noClusters") == 0 )
  301. {
  302. is >> this->noClusters;
  303. is >> tmp; // end of block
  304. tmp = this->removeEndTag ( tmp );
  305. }
  306. else if ( tmp.compare("distanceType") == 0 )
  307. {
  308. is >> this->distanceType;
  309. //TODO fixme
  310. this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
  311. is >> tmp; // end of block
  312. tmp = this->removeEndTag ( tmp );
  313. }
  314. else if ( tmp.compare("distancefunction") == 0 )
  315. {
  316. //TODO is >> this->distancefunction;
  317. is >> tmp; // end of block
  318. tmp = this->removeEndTag ( tmp );
  319. }
  320. else
  321. {
  322. std::cerr << "WARNING -- unexpected KMeansHeuristic object -- " << tmp << " -- for restoration... aborting" << std::endl;
  323. throw;
  324. }
  325. }
  326. }
  327. else
  328. {
  329. std::cerr << "KMeansHeuristic::restore -- InStream not initialized - restoring not possible!" << std::endl;
  330. throw;
  331. }
  332. }
  333. void KMeansHeuristic::store ( std::ostream & os, int format ) const
  334. {
  335. if (os.good())
  336. {
  337. // show starting point
  338. os << this->createStartTag( "KMeansHeuristic" ) << std::endl;
  339. os << this->createStartTag( "noClusters" ) << std::endl;
  340. os << this->noClusters << std::endl;
  341. os << this->createEndTag( "noClusters" ) << std::endl;
  342. os << this->createStartTag( "distanceType" ) << std::endl;
  343. os << this->distanceType << std::endl;
  344. os << this->createEndTag( "distanceType" ) << std::endl;
  345. os << this->createStartTag( "distancefunction" ) << std::endl;
  346. //TODO os << this->distancefunction << std::endl;
  347. os << this->createEndTag( "distancefunction" ) << std::endl;
  348. // done
  349. os << this->createEndTag( "KMeansHeuristic" ) << std::endl;
  350. }
  351. else
  352. {
  353. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  354. }
  355. }
  356. void KMeansHeuristic::clear ()
  357. {
  358. if ( this->distancefunction != NULL )
  359. {
  360. delete this->distancefunction;
  361. this->distancefunction = NULL ;
  362. }
  363. }