KMedian.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. ///////////////////// ///////////////////// /////////////////////
  32. // CONSTRUCTORS / DESTRUCTORS
  33. ///////////////////// ///////////////////// /////////////////////
  34. KMedian::KMedian() : ClusterAlgorithm()
  35. {
  36. this->noClusters = 20;
  37. this->distanceType = "euclidean";
  38. this->distancefunction = NULL;
  39. this->d_minDelta = 1e-5;
  40. this->i_maxIterations = 200;
  41. }
  42. KMedian::KMedian(const int & _noClusters, const std::string & _distanceType) :
  43. noClusters(_noClusters), distanceType(_distanceType)
  44. {
  45. //srand(time(NULL));
  46. this->distancefunction = GenericDistanceSelection::selectDistance( this->distanceType );
  47. this->d_minDelta = 1e-5;
  48. this->i_maxIterations = 200;
  49. }
  50. KMedian::KMedian( const NICE::Config * _conf, const std::string & _confSection)
  51. {
  52. this->initFromConfig( _conf, _confSection );
  53. }
  54. KMedian::~KMedian()
  55. {
  56. if ( this->distancefunction != NULL )
  57. {
  58. delete this->distancefunction;
  59. this->distancefunction = NULL ;
  60. }
  61. }
  62. void KMedian::initFromConfig( const NICE::Config* _conf, const std::string& _confSection )
  63. {
  64. this->noClusters = _conf->gI( _confSection, "noClusters", 20);
  65. this->distanceType = _conf->gS( _confSection, "distanceType", "euclidean" );
  66. this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
  67. this->d_minDelta = _conf->gD( _confSection, "minDelta", 1e-5 );
  68. this->i_maxIterations = _conf->gI( _confSection, "maxIterations", 200);
  69. }
  70. ///////////////////// ///////////////////// /////////////////////
  71. // CLUSTERING STUFF
  72. ///////////////////// ///////////////////// //////////////////
  73. void KMedian::initial_guess(const VVector & features, VVector & prototypes)
  74. {
  75. int j = 0;
  76. std::set<int, std::greater<int> > mark;
  77. for (VVector::iterator i = prototypes.begin(); i != prototypes.end(); i++, j++)
  78. {
  79. int k;
  80. do
  81. {
  82. k = rand() % features.size();
  83. } while (mark.find(k) != mark.end());
  84. mark.insert(mark.begin(), k);
  85. *i = features[k];
  86. }
  87. }
  88. int KMedian::compute_prototypes(const VVector & features, VVector & prototypes,
  89. std::vector<double> & weights, const std::vector<int> & assignment)
  90. {
  91. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  92. std::cerr << "initial assignments: ";
  93. for (std::vector<int>::const_iterator assignIt = assignment.begin(); assignIt != assignment.end(); assignIt++)
  94. {
  95. std::cerr << " " << *assignIt;
  96. }
  97. std::cerr << std::endl;
  98. #endif
  99. //initialization
  100. for (int k = 0; k < noClusters; k++)
  101. {
  102. prototypes[k].set(0);
  103. weights[k] = 0;
  104. }
  105. NICE::VectorT<int> numberOfCurrentAssignments ( noClusters ) ;
  106. numberOfCurrentAssignments.set ( 0 );
  107. int exCnt = 0;
  108. //how many examples are assigned to the current clusters?
  109. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, exCnt++)
  110. {
  111. int k = assignment[exCnt];
  112. //increase counter for assigned cluster
  113. numberOfCurrentAssignments[ k ] ++;
  114. }
  115. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  116. std::cerr << "k-median -- current assignmens: " << numberOfCurrentAssignments << std::endl << "noClusters: " << noClusters << std::endl;
  117. #endif
  118. //compute the median for every cluster
  119. #pragma omp parallel for
  120. for (int clusterCnt = 0; clusterCnt < noClusters; clusterCnt++)
  121. {
  122. NICE::Vector overallDistances ( numberOfCurrentAssignments[ clusterCnt ] );
  123. VVector::const_iterator lastExampleWorkedOn = features.begin();
  124. int i_idxOfLastExampleWorkedOn ( 0 );
  125. uint i_exCntInt ( 0 );
  126. //this map will contain overall distances of all examples within the current clusters
  127. //we need separate maps for every cluster to allow parallelization
  128. std::map<int,double> distancesWithinCluster;
  129. for (VVector::const_iterator featIt = features.begin(); featIt != features.end(); featIt++, i_exCntInt++)
  130. {
  131. int k = assignment[i_exCntInt];
  132. //only considere examples currently assigned to cluster clusterCnt
  133. if ( k != clusterCnt)
  134. {
  135. continue;
  136. }
  137. uint exCntIntTmp ( i_idxOfLastExampleWorkedOn ); //idx going over all features
  138. for (VVector::const_iterator j = lastExampleWorkedOn ; j != features.end(); j++, exCntIntTmp++)
  139. {
  140. int kTmp;
  141. if ( exCntIntTmp < assignment.size() )
  142. kTmp = assignment[exCntIntTmp];
  143. else
  144. {
  145. //actually, this will be never be reached :)
  146. std::cerr << "ERROR: exCntIntTmp >= assignment.size() " << exCntIntTmp << " " << assignment.size() << std::endl;
  147. }
  148. //only considere examples currently assigned to cluster clusterCnt
  149. if ( kTmp != clusterCnt)
  150. continue;
  151. double dist ( distancefunction->calculate( *featIt, *j) );
  152. if ( i_exCntInt < features.size() )
  153. {
  154. distancesWithinCluster[ i_exCntInt ] += dist;
  155. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  156. std::cerr << "increase " << i_exCntInt << " by " << dist << " for " <<*featIt << " and " << *j << std::endl;
  157. #endif
  158. }
  159. else
  160. {
  161. //actually, this will be never be reached :)
  162. std::cerr << "ERROR: i_exCntInt >= features.size() " << i_exCntInt << " " << features.size() << std::endl;
  163. }
  164. if ( i_exCntInt != exCntIntTmp )
  165. {
  166. if (exCntIntTmp < features.size() )
  167. {
  168. distancesWithinCluster[ exCntIntTmp ] += dist;
  169. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  170. std::cerr << "increase also " << exCntIntTmp << " by " << dist << std::endl;
  171. #endif
  172. }
  173. else
  174. std::cerr << "ERROR: exCntIntTmp >= features.size() " << exCntIntTmp << " " << features.size() << std::endl;
  175. }
  176. }
  177. //inc by one to avoid calculating some distances twice
  178. if ( ( featIt != features.end()) && ( (featIt +1 ) != features.end()) )
  179. {
  180. lastExampleWorkedOn = ( featIt + 1 );
  181. i_idxOfLastExampleWorkedOn = i_exCntInt+1;
  182. }
  183. }
  184. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  185. std::cerr << "distances for cluster " << clusterCnt << " ";
  186. for(std::map<int,double>::const_iterator distIt = distancesWithinCluster.begin(); distIt != distancesWithinCluster.end(); distIt++)
  187. {
  188. std::cerr << distIt->first << " " << distIt->second << " ";
  189. }
  190. std::cerr << std::endl;
  191. #endif
  192. //now compute the index of example with min overall distance
  193. int idxOfClusterMedian ( (min_element(distancesWithinCluster.begin(), distancesWithinCluster.end(), CompareSecond()))->first );
  194. #pragma omp critical
  195. prototypes[clusterCnt] = features[idxOfClusterMedian];
  196. //finished computations for cluster k
  197. }
  198. #ifdef DEBUG_KMEDIAN_PROTOCOMP
  199. std::cerr << " ---- prototypes after current iteration: --- " << std::endl;
  200. for (NICE::VVector::const_iterator protoIt = prototypes.begin(); protoIt != prototypes.end(); protoIt++)
  201. {
  202. std::cerr << *protoIt << " ";
  203. }
  204. std::cerr << std::endl;
  205. #endif
  206. return 0;
  207. }
  208. double KMedian::compute_delta(const VVector & oldprototypes,
  209. const VVector & prototypes)
  210. {
  211. double distance = 0;
  212. for (uint k = 0; k < oldprototypes.size(); k++)
  213. {
  214. distance += distancefunction->calculate(oldprototypes[k], prototypes[k]);
  215. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  216. fprintf(stderr, "KMedian::compute_delta: Distance:",
  217. distancefunction->calculate(oldprototypes[k], prototypes[k]));
  218. #endif
  219. }
  220. return distance;
  221. }
  222. double KMedian::compute_assignments(const VVector & features,
  223. const VVector & prototypes,
  224. std::vector<int> & assignment)
  225. {
  226. int index = 0;
  227. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, index++)
  228. {
  229. const NICE::Vector & x = *i;
  230. double mindist = std::numeric_limits<double>::max();
  231. int minclass = 0;
  232. int c = 0;
  233. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  234. fprintf(stderr, "computing nearest prototype for std::vector %d\n",
  235. index);
  236. #endif
  237. for (VVector::const_iterator j = prototypes.begin(); j
  238. != prototypes.end(); j++, c++)
  239. {
  240. const NICE::Vector & p = *j;
  241. double distance = distancefunction->calculate(p, x);
  242. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  243. fprintf(stderr, "KMedian::compute_delta: Distance: %f\n",
  244. distancefunction->calculate(p, x));
  245. #endif
  246. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  247. cerr << p << endl;
  248. cerr << x << endl;
  249. fprintf(stderr, "distance to prototype %d is %f\n", c, distance);
  250. #endif
  251. if (distance < mindist)
  252. {
  253. minclass = c;
  254. mindist = distance;
  255. }
  256. }
  257. assignment[index] = minclass;
  258. }
  259. return 0.0;
  260. }
  261. double KMedian::compute_weights(const VVector & features,
  262. std::vector<double> & weights,
  263. std::vector<int> & assignment)
  264. {
  265. for (int k = 0; k < noClusters; k++)
  266. weights[k] = 0;
  267. int j = 0;
  268. for (VVector::const_iterator i = features.begin(); i != features.end(); i++, j++)
  269. {
  270. int k = assignment[j];
  271. weights[k]++;
  272. }
  273. for (int k = 0; k < noClusters; k++)
  274. weights[k] = weights[k] / features.size();
  275. return 0.0;
  276. }
  277. void KMedian::cluster(const NICE::VVector & features,
  278. NICE::VVector & prototypes,
  279. std::vector<double> & weights,
  280. std::vector<int> & assignment)
  281. {
  282. NICE::VVector oldprototypes;
  283. prototypes.clear();
  284. weights.clear();
  285. assignment.clear();
  286. weights.resize(noClusters, 0);
  287. assignment.resize(features.size(), 0);
  288. int dimension;
  289. if ((int) features.size() >= noClusters)
  290. dimension = features[0].size();
  291. else
  292. {
  293. fprintf(stderr,
  294. "FATAL ERROR: Not enough feature vectors provided for kMedians -- number of Features: %i - number of clusters: %i\n", (int) features.size(), noClusters);
  295. exit(-1);
  296. }
  297. for (int k = 0; k < noClusters; k++)
  298. {
  299. prototypes.push_back( NICE::Vector(dimension) );
  300. prototypes[k].set(0);
  301. }
  302. bool successKMedian ( false );
  303. int iterations ( 0 );
  304. double delta ( std::numeric_limits<double>::max() );
  305. while ( !successKMedian )
  306. {
  307. //we assume that this run will be successful
  308. successKMedian = true;
  309. this->initial_guess(features, prototypes);
  310. iterations = 0;
  311. delta = std::numeric_limits<double>::max();
  312. //until-loop over iterations
  313. do
  314. {
  315. iterations++;
  316. // #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  317. std::cerr << "k-median iteration " << iterations << std::endl;
  318. // #endif
  319. this->compute_assignments( features, prototypes, assignment );
  320. if (iterations > 1)
  321. oldprototypes = prototypes;
  322. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  323. fprintf(stderr, "KMedian::cluster compute_prototypes\n");
  324. #endif
  325. if ( this->compute_prototypes( features, prototypes, weights, assignment ) < 0 )
  326. {
  327. fprintf(stderr, "KMedian::cluster restart\n");
  328. successKMedian = false;
  329. break;
  330. }
  331. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  332. fprintf(stderr, "KMedian::cluster compute_delta\n");
  333. #endif
  334. if (iterations > 1)
  335. delta = this->compute_delta( oldprototypes, prototypes );
  336. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  337. this->print_iteration( iterations, prototypes, delta );
  338. #endif
  339. } while ((delta > d_minDelta) && (iterations < i_maxIterations));
  340. }
  341. std::cerr << "ended optimization -- delta: " << delta << " of d_minDelta: " << d_minDelta << " --- and iterations: " << iterations << " of i_maxIterations: " << i_maxIterations << std::endl;
  342. #ifdef DEBUG_KMEDIAN_ASSIGNMENTS
  343. fprintf(stderr, "KMedian::cluster: iterations = %d, delta = %f\n",
  344. iterations, delta);
  345. #endif
  346. this->compute_weights( features, weights, assignment );
  347. }
  348. void KMedian::print_iteration( int iterations, VVector & prototypes, double delta )
  349. {
  350. if (iterations > 1)
  351. fprintf(stderr, "KMedian::cluster: iteration=%d delta=%f\n", iterations,
  352. delta);
  353. else
  354. fprintf(stderr, "KMedian::cluster: iteration=%d\n", iterations);
  355. int k = 0;
  356. for (VVector::const_iterator i = prototypes.begin(); i != prototypes.end(); i++, k++)
  357. {
  358. fprintf(stderr, "class (%d)\n", k);
  359. cerr << "prototype = " << (*i) << endl;
  360. }
  361. }
  362. ///////////////////// INTERFACE PERSISTENT /////////////////////
  363. // interface specific methods for store and restore
  364. ///////////////////// INTERFACE PERSISTENT /////////////////////
  365. void KMedian::restore ( std::istream & is, int format )
  366. {
  367. //delete everything we knew so far...
  368. this->clear();
  369. if ( is.good() )
  370. {
  371. std::string tmp;
  372. is >> tmp; //class name
  373. if ( ! this->isStartTag( tmp, "KMedian" ) )
  374. {
  375. std::cerr << " WARNING - attempt to restore KMedian, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  376. throw;
  377. }
  378. bool b_endOfBlock ( false ) ;
  379. while ( !b_endOfBlock )
  380. {
  381. is >> tmp; // start of block
  382. if ( this->isEndTag( tmp, "KMedian" ) )
  383. {
  384. b_endOfBlock = true;
  385. continue;
  386. }
  387. tmp = this->removeStartTag ( tmp );
  388. if ( tmp.compare("noClusters") == 0 )
  389. {
  390. is >> this->noClusters;
  391. is >> tmp; // end of block
  392. tmp = this->removeEndTag ( tmp );
  393. }
  394. else if ( tmp.compare("distanceType") == 0 )
  395. {
  396. is >> this->distanceType;
  397. //TODO fixme
  398. this->distancefunction = OBJREC::GenericDistanceSelection::selectDistance( this->distanceType );
  399. is >> tmp; // end of block
  400. tmp = this->removeEndTag ( tmp );
  401. }
  402. else if ( tmp.compare("distancefunction") == 0 )
  403. {
  404. //TODO is >> this->distancefunction;
  405. is >> tmp; // end of block
  406. tmp = this->removeEndTag ( tmp );
  407. }
  408. else if ( tmp.compare("d_minDelta") == 0 )
  409. {
  410. is >> this->d_minDelta;
  411. is >> tmp; // end of block
  412. tmp = this->removeEndTag ( tmp );
  413. }
  414. else if ( tmp.compare("i_maxIterations") == 0 )
  415. {
  416. is >> this->i_maxIterations;
  417. is >> tmp; // end of block
  418. tmp = this->removeEndTag ( tmp );
  419. }
  420. else
  421. {
  422. std::cerr << "WARNING -- unexpected KMedian object -- " << tmp << " -- for restoration... aborting" << std::endl;
  423. throw;
  424. }
  425. }
  426. }
  427. else
  428. {
  429. std::cerr << "KMedian::restore -- InStream not initialized - restoring not possible!" << std::endl;
  430. throw;
  431. }
  432. }
  433. void KMedian::store ( std::ostream & os, int format ) const
  434. {
  435. if (os.good())
  436. {
  437. // show starting point
  438. os << this->createStartTag( "KMedian" ) << std::endl;
  439. os << this->createStartTag( "noClusters" ) << std::endl;
  440. os << this->noClusters << std::endl;
  441. os << this->createEndTag( "noClusters" ) << std::endl;
  442. os << this->createStartTag( "distanceType" ) << std::endl;
  443. os << this->distanceType << std::endl;
  444. os << this->createEndTag( "distanceType" ) << std::endl;
  445. os << this->createStartTag( "distancefunction" ) << std::endl;
  446. //TODO os << this->distancefunction << std::endl;
  447. os << this->createEndTag( "distancefunction" ) << std::endl;
  448. os << this->createStartTag( "d_minDelta" ) << std::endl;
  449. os << this->d_minDelta << std::endl;
  450. os << this->createEndTag( "d_minDelta" ) << std::endl;
  451. os << this->createStartTag( "i_maxIterations" ) << std::endl;
  452. os << this->i_maxIterations << std::endl;
  453. os << this->createEndTag( "i_maxIterations" ) << std::endl;
  454. // done
  455. os << this->createEndTag( "KMedian" ) << std::endl;
  456. }
  457. else
  458. {
  459. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  460. }
  461. }
  462. void KMedian::clear ()
  463. {
  464. if ( this->distancefunction != NULL )
  465. {
  466. delete this->distancefunction;
  467. this->distancefunction = NULL ;
  468. }
  469. }