KMedian.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. KMedian::KMedian(int _noClasses, string _distanceType) :
  32. noClasses(_noClasses), distanceType(_distanceType)
  33. {
  34. //srand(time(NULL));
  35. distancefunction = GenericDistanceSelection::selectDistance(distanceType);
  36. this->d_minDelta = 1e-5;
  37. this->i_maxIterations = 200;
  38. }
  39. KMedian::~KMedian()
  40. {
  41. }
  42. void KMedian::initial_guess(const VVector & features, VVector & prototypes)
  43. {
  44. int j = 0;
  45. std::set<int, std::greater<int> > mark;
  46. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
  47. {
  48. int k;
  49. do
  50. {
  51. k = rand() % features.size();
  52. } while (mark.find(k) != mark.end());
  53. mark.insert(mark.begin(), k);
  54. *i = features[k];
  55. }
  56. }
  57. int KMedian::compute_prototypes(const VVector & features, VVector & prototypes,
  58. std::vector<double> & weights, const std::vector<int> & assignment)
  59. {
  60. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  61. std::cerr << "initial assignments: ";
  62. for (std::vector<int>::const_iterator assignIt = assignment.begin(); assignIt != assignment.end(); assignIt++)
  63. {
  64. std::cerr << " " << *assignIt;
  65. }
  66. std::cerr << std::endl;
  67. #endif
  68. //initialization
  69. for (int k = 0; k < noClasses; k++)
  70. {
  71. prototypes[k].set(0);
  72. weights[k] = 0;
  73. }
  74. NICE::VectorT<int> numberOfCurrentAssignments ( noClasses ) ;
  75. numberOfCurrentAssignments.set ( 0 );
  76. int exCnt = 0;
  77. //how many examples are assigned to the current clusters?
  78. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, exCnt++)
  79. {
  80. int k = assignment[exCnt];
  81. //increase counter for assigned cluster
  82. numberOfCurrentAssignments[ k ] ++;
  83. }
  84. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  85. std::cerr << "k-median -- current assignmens: " << numberOfCurrentAssignments << std::endl << "noClasses: " << noClasses << std::endl;
  86. #endif
  87. //compute the median for every cluster
  88. #pragma omp parallel for
  89. for (int clusterCnt = 0; clusterCnt < noClasses; clusterCnt++)
  90. {
  91. NICE::Vector overallDistances ( numberOfCurrentAssignments[ clusterCnt ] );
  92. VVector::const_iterator lastExampleWorkedOn = features.begin();
  93. int i_idxOfLastExampleWorkedOn ( 0 );
  94. uint i_exCntInt ( 0 );
  95. //this map will contain overall distances of all examples within the current clusters
  96. //we need separate maps for every cluster to allow parallelization
  97. std::map<int,double> distancesWithinCluster;
  98. for (VVector::const_iterator featIt = features.begin(); featIt != features.end(); featIt++, i_exCntInt++)
  99. {
  100. int k = assignment[i_exCntInt];
  101. //only considere examples currently assigned to cluster clusterCnt
  102. if ( k != clusterCnt)
  103. {
  104. continue;
  105. }
  106. uint exCntIntTmp ( i_idxOfLastExampleWorkedOn ); //idx going over all features
  107. for (VVector::const_iterator j = lastExampleWorkedOn ; j != features.end(); j++, exCntIntTmp++)
  108. {
  109. int kTmp;
  110. if ( exCntIntTmp < assignment.size() )
  111. kTmp = assignment[exCntIntTmp];
  112. else
  113. {
  114. //actually, this will be never be reached :)
  115. std::cerr << "ERROR: exCntIntTmp >= assignment.size() " << exCntIntTmp << " " << assignment.size() << std::endl;
  116. }
  117. //only considere examples currently assigned to cluster clusterCnt
  118. if ( kTmp != clusterCnt)
  119. continue;
  120. double dist ( distancefunction->calculate( *featIt, *j) );
  121. if ( i_exCntInt < features.size() )
  122. {
  123. distancesWithinCluster[ i_exCntInt ] += dist;
  124. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  125. std::cerr << "increase " << i_exCntInt << " by " << dist << " for " <<*featIt << " and " << *j << std::endl;
  126. #endif
  127. }
  128. else
  129. {
  130. //actually, this will be never be reached :)
  131. std::cerr << "ERROR: i_exCntInt >= features.size() " << i_exCntInt << " " << features.size() << std::endl;
  132. }
  133. if ( i_exCntInt != exCntIntTmp )
  134. {
  135. if (exCntIntTmp < features.size() )
  136. {
  137. distancesWithinCluster[ exCntIntTmp ] += dist;
  138. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  139. std::cerr << "increase also " << exCntIntTmp << " by " << dist << std::endl;
  140. #endif
  141. }
  142. else
  143. std::cerr << "ERROR: exCntIntTmp >= features.size() " << exCntIntTmp << " " << features.size() << std::endl;
  144. }
  145. }
  146. //inc by one to avoid calculating some distances twice
  147. if ( ( featIt != features.end()) && ( (featIt +1 ) != features.end()) )
  148. {
  149. lastExampleWorkedOn = ( featIt + 1 );
  150. i_idxOfLastExampleWorkedOn = i_exCntInt+1;
  151. }
  152. }
  153. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  154. std::cerr << "distances for cluster " << clusterCnt << " ";
  155. for(std::map<int,double>::const_iterator distIt = distancesWithinCluster.begin(); distIt != distancesWithinCluster.end(); distIt++)
  156. {
  157. std::cerr << distIt->first << " " << distIt->second << " ";
  158. }
  159. std::cerr << std::endl;
  160. #endif
  161. //now compute the index of example with min overall distance
  162. int idxOfClusterMedian ( (min_element(distancesWithinCluster.begin(), distancesWithinCluster.end(), CompareSecond()))->first );
  163. #pragma omp critical
  164. prototypes[clusterCnt] = features[idxOfClusterMedian];
  165. //finished computations for cluster k
  166. }
  167. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  168. std::cerr << " ---- prototypes after current iteration: --- " << std::endl;
  169. for (NICE::VVector::const_iterator protoIt = prototypes.begin(); protoIt != prototypes.end(); protoIt++)
  170. {
  171. std::cerr << *protoIt << " ";
  172. }
  173. std::cerr << std::endl;
  174. #endif
  175. return 0;
  176. }
  177. double KMedian::compute_delta(const VVector & oldprototypes,
  178. const VVector & prototypes)
  179. {
  180. double distance = 0;
  181. for (uint k = 0; k < oldprototypes.size(); k++)
  182. {
  183. distance += distancefunction->calculate(oldprototypes[k], prototypes[k]);
  184. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  185. fprintf(stderr, "KMedian::compute_delta: Distance:",
  186. distancefunction->calculate(oldprototypes[k], prototypes[k]));
  187. #endif
  188. }
  189. return distance;
  190. }
  191. double KMedian::compute_assignments(const VVector & features,
  192. const VVector & prototypes,
  193. std::vector<int> & assignment)
  194. {
  195. int index = 0;
  196. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
  197. {
  198. const NICE::Vector & x = *i;
  199. double mindist = std::numeric_limits<double>::max();
  200. int minclass = 0;
  201. int c = 0;
  202. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  203. fprintf(stderr, "computing nearest prototype for std::vector %d\n",
  204. index);
  205. #endif
  206. for (VVector::const_iterator j = prototypes.begin(); j
  207. != prototypes.end(); j++, c++)
  208. {
  209. const NICE::Vector & p = *j;
  210. double distance = distancefunction->calculate(p, x);
  211. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  212. fprintf(stderr, "KMedian::compute_delta: Distance: %f\n",
  213. distancefunction->calculate(p, x));
  214. #endif
  215. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  216. cerr << p << endl;
  217. cerr << x << endl;
  218. fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
  219. #endif
  220. if (distance < mindist)
  221. {
  222. minclass = c;
  223. mindist = distance;
  224. }
  225. }
  226. assignment[index] = minclass;
  227. }
  228. return 0.0;
  229. }
  230. double KMedian::compute_weights(const VVector & features,
  231. std::vector<double> & weights,
  232. std::vector<int> & assignment)
  233. {
  234. for (int k = 0; k < noClasses; k++)
  235. weights[k] = 0;
  236. int j = 0;
  237. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  238. {
  239. int k = assignment[j];
  240. weights[k]++;
  241. }
  242. for (int k = 0; k < noClasses; k++)
  243. weights[k] = weights[k] / features.size();
  244. return 0.0;
  245. }
  246. void KMedian::cluster(const NICE::VVector & features,
  247. NICE::VVector & prototypes,
  248. std::vector<double> & weights,
  249. std::vector<int> & assignment)
  250. {
  251. NICE::VVector oldprototypes;
  252. prototypes.clear();
  253. weights.clear();
  254. assignment.clear();
  255. weights.resize(noClasses, 0);
  256. assignment.resize(features.size(), 0);
  257. int dimension;
  258. if ((int) features.size() >= noClasses)
  259. dimension = features[0].size();
  260. else
  261. {
  262. fprintf(stderr,
  263. "FATAL ERROR: Not enough feature vectors provided for kMeans\n");
  264. exit(-1);
  265. }
  266. for (int k = 0; k < noClasses; k++)
  267. {
  268. prototypes.push_back( NICE::Vector(dimension) );
  269. prototypes[k].set(0);
  270. }
  271. bool successKMedian ( false );
  272. int iterations ( 0 );
  273. double delta ( std::numeric_limits<double>::max() );
  274. while ( !successKMedian )
  275. {
  276. //we assume that this run will be successful
  277. successKMedian = true;
  278. this->initial_guess(features, prototypes);
  279. iterations = 0;
  280. delta = std::numeric_limits<double>::max();
  281. //until-loop over iterations
  282. do
  283. {
  284. iterations++;
  285. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  286. std::cerr << "k-median iteration " << iterations << std::endl;
  287. #endif
  288. this->compute_assignments( features, prototypes, assignment );
  289. if (iterations > 1)
  290. oldprototypes = prototypes;
  291. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  292. fprintf(stderr, "KMedian::cluster compute_prototypes\n");
  293. #endif
  294. if ( this->compute_prototypes( features, prototypes, weights, assignment ) < 0 )
  295. {
  296. fprintf(stderr, "KMedian::cluster restart\n");
  297. successKMedian = false;
  298. break;
  299. }
  300. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  301. fprintf(stderr, "KMedian::cluster compute_delta\n");
  302. #endif
  303. if (iterations > 1)
  304. delta = this->compute_delta( oldprototypes, prototypes );
  305. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  306. this->print_iteration( iterations, prototypes, delta );
  307. #endif
  308. } while ((delta > d_minDelta) && (iterations < i_maxIterations));
  309. }
  310. std::cerr << "ended optimization -- delta: " << delta << " of d_minDelta: " << d_minDelta << " --- and iterations: " << iterations << " of i_maxIterations: " << i_maxIterations << std::endl;
  311. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  312. fprintf(stderr, "KMedian::cluster: iterations = %d, delta = %f\n",
  313. iterations, delta);
  314. #endif
  315. this->compute_weights( features, weights, assignment );
  316. }
  317. void KMedian::print_iteration( int iterations, VVector & prototypes, double delta )
  318. {
  319. if (iterations > 1)
  320. fprintf(stderr, "KMedian::cluster: iteration=%d delta=%f\n", iterations,
  321. delta);
  322. else
  323. fprintf(stderr, "KMedian::cluster: iteration=%d\n", iterations);
  324. int k = 0;
  325. for (VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
  326. {
  327. fprintf(stderr, "class (%d)\n", k);
  328. cerr << "prototype = " << (*i) << endl;
  329. }
  330. }