KMedian.cpp 12 KB

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