KMedian.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /**
  2. * @file KMedian.cpp
  3. * @brief KMedian (aka K-medoid)
  4. * @author Alexander Freytag
  5. * @date 23-04-2013 (dd-mm-yyyy)
  6. */
  7. #ifdef NICE_USELIB_OPENMP
  8. #include <omp.h>
  9. #endif
  10. #include <iostream>
  11. #include <map>
  12. #include <algorithm> //to easily find the smallest value in a map
  13. #include "vislearning/math/cluster/KMedian.h"
  14. #include "vislearning/math/distances/genericDistance.h"
  15. #include <set>
  16. using namespace OBJREC;
  17. using namespace std;
  18. using namespace NICE;
  19. typedef std::pair<int, double> MyPairType;
  20. struct CompareSecond
  21. {
  22. bool operator()(const MyPairType& left, const MyPairType& right) const
  23. {
  24. return left.second < right.second;
  25. }
  26. };
  27. #undef DEBUG_KMEDIAN_ASSIGNMENTS
  28. // #define DEBUG_KMEDIAN_ASSIGNMENTS
  29. #undef DEBUG_KMEDIAN_PROTOCOMP
  30. // #define DEBUG_KMEDIAN_PROTOCOMP
  31. <<<<<<< .merge_file_tPxeyL
  32. KMedian::KMedian(const int & _noClasses, const std::string & _distanceType) :
  33. noClasses(_noClasses), distanceType(_distanceType)
  34. =======
  35. KMedian::KMedian(const int & _noClusters, const std::string & _distanceType) :
  36. noClusters(_noClusters), distanceType(_distanceType)
  37. >>>>>>> .merge_file_aM3NwI
  38. {
  39. //srand(time(NULL));
  40. distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  41. this->d_minDelta = 1e-5;
  42. this->i_maxIterations = 200;
  43. }
  44. KMedian::KMedian( const NICE::Config *conf, const std::string & _section)
  45. {
  46. this->distanceType = conf->gS( _section, "distanceType", "euclidean" );
  47. this->distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  48. this->d_minDelta = conf->gD( _section, "minDelta", 1e-5 );
  49. this->i_maxIterations = conf->gI( _section, "maxIterations", 200);
  50. <<<<<<< .merge_file_tPxeyL
  51. this->noClasses = conf->gI( _section, "noClasses", 20);
  52. =======
  53. this->noClusters = conf->gI( _section, "noClusters", 20);
  54. >>>>>>> .merge_file_aM3NwI
  55. }
  56. KMedian::~KMedian()
  57. {
  58. }
  59. void KMedian::initial_guess(const VVector & features, VVector & prototypes)
  60. {
  61. int j = 0;
  62. std::set<int, std::greater<int> > mark;
  63. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
  64. {
  65. int k;
  66. do
  67. {
  68. k = rand() % features.size();
  69. } while (mark.find(k) != mark.end());
  70. mark.insert(mark.begin(), k);
  71. *i = features[k];
  72. }
  73. }
  74. int KMedian::compute_prototypes(const VVector & features, VVector & prototypes,
  75. std::vector<double> & weights, const std::vector<int> & assignment)
  76. {
  77. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  78. std::cerr << "initial assignments: ";
  79. for (std::vector<int>::const_iterator assignIt = assignment.begin(); assignIt != assignment.end(); assignIt++)
  80. {
  81. std::cerr << " " << *assignIt;
  82. }
  83. std::cerr << std::endl;
  84. #endif
  85. //initialization
  86. <<<<<<< .merge_file_tPxeyL
  87. for (int k = 0; k < noClasses; k++)
  88. =======
  89. for (int k = 0; k < noClusters; k++)
  90. >>>>>>> .merge_file_aM3NwI
  91. {
  92. prototypes[k].set(0);
  93. weights[k] = 0;
  94. }
  95. <<<<<<< .merge_file_tPxeyL
  96. NICE::VectorT<int> numberOfCurrentAssignments ( noClasses ) ;
  97. =======
  98. NICE::VectorT<int> numberOfCurrentAssignments ( noClusters ) ;
  99. >>>>>>> .merge_file_aM3NwI
  100. numberOfCurrentAssignments.set ( 0 );
  101. int exCnt = 0;
  102. //how many examples are assigned to the current clusters?
  103. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, exCnt++)
  104. {
  105. int k = assignment[exCnt];
  106. //increase counter for assigned cluster
  107. numberOfCurrentAssignments[ k ] ++;
  108. }
  109. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  110. <<<<<<< .merge_file_tPxeyL
  111. std::cerr << "k-median -- current assignmens: " << numberOfCurrentAssignments << std::endl << "noClasses: " << noClasses << std::endl;
  112. =======
  113. std::cerr << "k-median -- current assignmens: " << numberOfCurrentAssignments << std::endl << "noClusters: " << noClusters << std::endl;
  114. >>>>>>> .merge_file_aM3NwI
  115. #endif
  116. //compute the median for every cluster
  117. #pragma omp parallel for
  118. <<<<<<< .merge_file_tPxeyL
  119. for (int clusterCnt = 0; clusterCnt < noClasses; clusterCnt++)
  120. =======
  121. for (int clusterCnt = 0; clusterCnt < noClusters; clusterCnt++)
  122. >>>>>>> .merge_file_aM3NwI
  123. {
  124. NICE::Vector overallDistances ( numberOfCurrentAssignments[ clusterCnt ] );
  125. VVector::const_iterator lastExampleWorkedOn = features.begin();
  126. int i_idxOfLastExampleWorkedOn ( 0 );
  127. uint i_exCntInt ( 0 );
  128. //this map will contain overall distances of all examples within the current clusters
  129. //we need separate maps for every cluster to allow parallelization
  130. std::map<int,double> distancesWithinCluster;
  131. for (VVector::const_iterator featIt = features.begin(); featIt != features.end(); featIt++, i_exCntInt++)
  132. {
  133. int k = assignment[i_exCntInt];
  134. //only considere examples currently assigned to cluster clusterCnt
  135. if ( k != clusterCnt)
  136. {
  137. continue;
  138. }
  139. uint exCntIntTmp ( i_idxOfLastExampleWorkedOn ); //idx going over all features
  140. for (VVector::const_iterator j = lastExampleWorkedOn ; j != features.end(); j++, exCntIntTmp++)
  141. {
  142. int kTmp;
  143. if ( exCntIntTmp < assignment.size() )
  144. kTmp = assignment[exCntIntTmp];
  145. else
  146. {
  147. //actually, this will be never be reached :)
  148. std::cerr << "ERROR: exCntIntTmp >= assignment.size() " << exCntIntTmp << " " << assignment.size() << std::endl;
  149. }
  150. //only considere examples currently assigned to cluster clusterCnt
  151. if ( kTmp != clusterCnt)
  152. continue;
  153. double dist ( distancefunction->calculate( *featIt, *j) );
  154. if ( i_exCntInt < features.size() )
  155. {
  156. distancesWithinCluster[ i_exCntInt ] += dist;
  157. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  158. std::cerr << "increase " << i_exCntInt << " by " << dist << " for " <<*featIt << " and " << *j << std::endl;
  159. #endif
  160. }
  161. else
  162. {
  163. //actually, this will be never be reached :)
  164. std::cerr << "ERROR: i_exCntInt >= features.size() " << i_exCntInt << " " << features.size() << std::endl;
  165. }
  166. if ( i_exCntInt != exCntIntTmp )
  167. {
  168. if (exCntIntTmp < features.size() )
  169. {
  170. distancesWithinCluster[ exCntIntTmp ] += dist;
  171. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  172. std::cerr << "increase also " << exCntIntTmp << " by " << dist << std::endl;
  173. #endif
  174. }
  175. else
  176. std::cerr << "ERROR: exCntIntTmp >= features.size() " << exCntIntTmp << " " << features.size() << std::endl;
  177. }
  178. }
  179. //inc by one to avoid calculating some distances twice
  180. if ( ( featIt != features.end()) && ( (featIt +1 ) != features.end()) )
  181. {
  182. lastExampleWorkedOn = ( featIt + 1 );
  183. i_idxOfLastExampleWorkedOn = i_exCntInt+1;
  184. }
  185. }
  186. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  187. std::cerr << "distances for cluster " << clusterCnt << " ";
  188. for(std::map<int,double>::const_iterator distIt = distancesWithinCluster.begin(); distIt != distancesWithinCluster.end(); distIt++)
  189. {
  190. std::cerr << distIt->first << " " << distIt->second << " ";
  191. }
  192. std::cerr << std::endl;
  193. #endif
  194. //now compute the index of example with min overall distance
  195. int idxOfClusterMedian ( (min_element(distancesWithinCluster.begin(), distancesWithinCluster.end(), CompareSecond()))->first );
  196. #pragma omp critical
  197. prototypes[clusterCnt] = features[idxOfClusterMedian];
  198. //finished computations for cluster k
  199. }
  200. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  201. std::cerr << " ---- prototypes after current iteration: --- " << std::endl;
  202. for (NICE::VVector::const_iterator protoIt = prototypes.begin(); protoIt != prototypes.end(); protoIt++)
  203. {
  204. std::cerr << *protoIt << " ";
  205. }
  206. std::cerr << std::endl;
  207. #endif
  208. return 0;
  209. }
  210. double KMedian::compute_delta(const VVector & oldprototypes,
  211. const VVector & prototypes)
  212. {
  213. double distance = 0;
  214. for (uint k = 0; k < oldprototypes.size(); k++)
  215. {
  216. distance += distancefunction->calculate(oldprototypes[k], prototypes[k]);
  217. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  218. fprintf(stderr, "KMedian::compute_delta: Distance:",
  219. distancefunction->calculate(oldprototypes[k], prototypes[k]));
  220. #endif
  221. }
  222. return distance;
  223. }
  224. double KMedian::compute_assignments(const VVector & features,
  225. const VVector & prototypes,
  226. std::vector<int> & assignment)
  227. {
  228. int index = 0;
  229. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
  230. {
  231. const NICE::Vector & x = *i;
  232. double mindist = std::numeric_limits<double>::max();
  233. int minclass = 0;
  234. int c = 0;
  235. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  236. fprintf(stderr, "computing nearest prototype for std::vector %d\n",
  237. index);
  238. #endif
  239. for (VVector::const_iterator j = prototypes.begin(); j
  240. != prototypes.end(); j++, c++)
  241. {
  242. const NICE::Vector & p = *j;
  243. double distance = distancefunction->calculate(p, x);
  244. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  245. fprintf(stderr, "KMedian::compute_delta: Distance: %f\n",
  246. distancefunction->calculate(p, x));
  247. #endif
  248. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  249. cerr << p << endl;
  250. cerr << x << endl;
  251. fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
  252. #endif
  253. if (distance < mindist)
  254. {
  255. minclass = c;
  256. mindist = distance;
  257. }
  258. }
  259. assignment[index] = minclass;
  260. }
  261. return 0.0;
  262. }
  263. double KMedian::compute_weights(const VVector & features,
  264. std::vector<double> & weights,
  265. std::vector<int> & assignment)
  266. {
  267. <<<<<<< .merge_file_tPxeyL
  268. for (int k = 0; k < noClasses; k++)
  269. =======
  270. for (int k = 0; k < noClusters; k++)
  271. >>>>>>> .merge_file_aM3NwI
  272. weights[k] = 0;
  273. int j = 0;
  274. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  275. {
  276. int k = assignment[j];
  277. weights[k]++;
  278. }
  279. <<<<<<< .merge_file_tPxeyL
  280. for (int k = 0; k < noClasses; k++)
  281. =======
  282. for (int k = 0; k < noClusters; k++)
  283. >>>>>>> .merge_file_aM3NwI
  284. weights[k] = weights[k] / features.size();
  285. return 0.0;
  286. }
  287. void KMedian::cluster(const NICE::VVector & features,
  288. NICE::VVector & prototypes,
  289. std::vector<double> & weights,
  290. std::vector<int> & assignment)
  291. {
  292. NICE::VVector oldprototypes;
  293. prototypes.clear();
  294. weights.clear();
  295. assignment.clear();
  296. <<<<<<< .merge_file_tPxeyL
  297. weights.resize(noClasses, 0);
  298. =======
  299. weights.resize(noClusters, 0);
  300. >>>>>>> .merge_file_aM3NwI
  301. assignment.resize(features.size(), 0);
  302. int dimension;
  303. <<<<<<< .merge_file_tPxeyL
  304. if ((int) features.size() >= noClasses)
  305. =======
  306. if ((int) features.size() >= noClusters)
  307. >>>>>>> .merge_file_aM3NwI
  308. dimension = features[0].size();
  309. else
  310. {
  311. fprintf(stderr,
  312. <<<<<<< .merge_file_tPxeyL
  313. "FATAL ERROR: Not enough feature vectors provided for kMeans\n");
  314. exit(-1);
  315. }
  316. for (int k = 0; k < noClasses; k++)
  317. =======
  318. "FATAL ERROR: Not enough feature vectors provided for kMedians -- number of Features: %i - number of clusters: %i\n", (int) features.size(), noClusters);
  319. exit(-1);
  320. }
  321. for (int k = 0; k < noClusters; k++)
  322. >>>>>>> .merge_file_aM3NwI
  323. {
  324. prototypes.push_back( NICE::Vector(dimension) );
  325. prototypes[k].set(0);
  326. }
  327. bool successKMedian ( false );
  328. int iterations ( 0 );
  329. double delta ( std::numeric_limits<double>::max() );
  330. while ( !successKMedian )
  331. {
  332. //we assume that this run will be successful
  333. successKMedian = true;
  334. this->initial_guess(features, prototypes);
  335. iterations = 0;
  336. delta = std::numeric_limits<double>::max();
  337. //until-loop over iterations
  338. do
  339. {
  340. iterations++;
  341. // #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  342. std::cerr << "k-median iteration " << iterations << std::endl;
  343. // #endif
  344. this->compute_assignments( features, prototypes, assignment );
  345. if (iterations > 1)
  346. oldprototypes = prototypes;
  347. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  348. fprintf(stderr, "KMedian::cluster compute_prototypes\n");
  349. #endif
  350. if ( this->compute_prototypes( features, prototypes, weights, assignment ) < 0 )
  351. {
  352. fprintf(stderr, "KMedian::cluster restart\n");
  353. successKMedian = false;
  354. break;
  355. }
  356. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  357. fprintf(stderr, "KMedian::cluster compute_delta\n");
  358. #endif
  359. if (iterations > 1)
  360. delta = this->compute_delta( oldprototypes, prototypes );
  361. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  362. this->print_iteration( iterations, prototypes, delta );
  363. #endif
  364. } while ((delta > d_minDelta) && (iterations < i_maxIterations));
  365. }
  366. std::cerr << "ended optimization -- delta: " << delta << " of d_minDelta: " << d_minDelta << " --- and iterations: " << iterations << " of i_maxIterations: " << i_maxIterations << std::endl;
  367. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  368. fprintf(stderr, "KMedian::cluster: iterations = %d, delta = %f\n",
  369. iterations, delta);
  370. #endif
  371. this->compute_weights( features, weights, assignment );
  372. }
  373. void KMedian::print_iteration( int iterations, VVector & prototypes, double delta )
  374. {
  375. if (iterations > 1)
  376. fprintf(stderr, "KMedian::cluster: iteration=%d delta=%f\n", iterations,
  377. delta);
  378. else
  379. fprintf(stderr, "KMedian::cluster: iteration=%d\n", iterations);
  380. int k = 0;
  381. for (VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
  382. {
  383. fprintf(stderr, "class (%d)\n", k);
  384. cerr << "prototype = " << (*i) << endl;
  385. }
  386. }