FPCGPHIK.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /**
  2. * @file FPCGPHIK.cpp
  3. * @brief feature pool interface for our GP HIK classifier
  4. * @author Alexander Freytag
  5. * @date 02/01/2012
  6. */
  7. // STL includes
  8. #include <iostream>
  9. // NICE-core includes
  10. #include <core/basics/numerictools.h>
  11. #include <core/basics/Timer.h>
  12. // NICE-vislearning includes
  13. #include "FPCGPHIK.h"
  14. using namespace std;
  15. using namespace NICE;
  16. using namespace OBJREC;
  17. void FPCGPHIK::init ( const NICE::Config *conf, const std::string & s_confSection )
  18. {
  19. this->verbose = conf->gB( s_confSection, "verbose", false );
  20. this->useSimpleBalancing = conf->gB( s_confSection, "use_simple_balancing", false );
  21. this->minSamples = conf->gI( s_confSection, "min_samples", -1 );
  22. this->performOptimizationAfterIncrement = conf->gB( s_confSection, "performOptimizationAfterIncrement", false );
  23. this->classifier = new GPHIKClassifier(conf, s_confSection);
  24. }
  25. FPCGPHIK::FPCGPHIK( )
  26. {
  27. this->classifier = NULL;
  28. }
  29. FPCGPHIK::FPCGPHIK( const Config *conf, const string & confSection )
  30. {
  31. this->classifier = NULL;
  32. // if no config file was given, we either restore the classifier from an external file, or run ::init with
  33. // an emtpy config (using default values thereby) when calling the train-method
  34. if ( conf != NULL )
  35. {
  36. this->init(conf, confSection);
  37. }
  38. }
  39. FPCGPHIK::~FPCGPHIK()
  40. {
  41. if ( this->classifier != NULL )
  42. delete this->classifier;
  43. this->classifier = NULL;
  44. }
  45. ClassificationResult FPCGPHIK::classify ( Example & pe )
  46. {
  47. const SparseVector *svec = pe.svec;
  48. if ( svec == NULL )
  49. fthrow(Exception, "FPCGPHIK requires example.svec (SparseVector stored in an Example struct)");
  50. return this->classify( svec );
  51. }
  52. ClassificationResult FPCGPHIK::classify ( const NICE::SparseVector * example )
  53. {
  54. if ( this->classifier == NULL )
  55. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  56. NICE::SparseVector scores;
  57. int result;
  58. double uncertainty;
  59. classifier->classify ( example, result, scores, uncertainty);
  60. if ( scores.size() == 0 ) {
  61. fthrow(Exception, "Zero scores, something is likely to be wrong here: svec.size() = " << example->size() );
  62. }
  63. int classes = scores.getDim();
  64. FullVector fvscores(classes);
  65. NICE::SparseVector::const_iterator it;
  66. for(int c = 0; c < classes; c++)
  67. {
  68. it = scores.find(c);
  69. if ( it == scores.end() )
  70. fvscores[c] = -std::numeric_limits<double>::max();
  71. else
  72. fvscores[c] = it->second;
  73. }
  74. ClassificationResult r ( fvscores.maxElement(), fvscores );
  75. r.uncertainty = uncertainty;
  76. if (verbose)
  77. {
  78. std::cerr << " FPCGPHIK::classify scores" << std::endl;
  79. scores.store(std::cerr);
  80. std::cerr << " FPCGPHIK::classify fvscores" << std::endl;
  81. fvscores.store(std::cerr);
  82. }
  83. return r;
  84. }
  85. /** training process */
  86. void FPCGPHIK::train ( FeaturePool & fp, Examples & examples )
  87. {
  88. if ( this->classifier == NULL )
  89. {
  90. std::cerr << "WARNING -- No config used so far, initialize values with empty config file now..." << std::endl;
  91. NICE::Config tmpConfEmpty ;
  92. this->init ( &tmpConfEmpty );
  93. }
  94. // we completely ignore the feature pool :)
  95. //
  96. initRand(0);
  97. Vector classCounts;
  98. int minClass = -1;
  99. if (verbose)
  100. std::cerr << "FPCGPHIK::train" << std::endl;
  101. if ( useSimpleBalancing)
  102. {
  103. classCounts.resize( examples.getMaxClassNo()+1 );
  104. classCounts.set( 0.0 );
  105. for ( uint i = 0 ; i < examples.size() ; i++ )
  106. classCounts[ examples[i].first ]++;
  107. // we need a probability distribution
  108. //classCounts.normalizeL1();
  109. // we need the class index of the class with the least non-zero examples
  110. for ( uint i = 0 ; i < classCounts.size(); i++ )
  111. if ( (classCounts[i] > 0) && ((minClass < 0) || (classCounts[i] < classCounts[minClass])) )
  112. minClass = i;
  113. if (verbose)
  114. {
  115. cerr << "Class distribution: " << classCounts << endl;
  116. cerr << "Class with the least number of examples: " << minClass << endl;
  117. }
  118. if(minSamples < 0)
  119. minSamples = classCounts[minClass];
  120. }
  121. // (multi-class) label vector
  122. Vector y ( examples.size() /* maximum size */ );
  123. // flat structure of our training data
  124. std::vector< const SparseVector * > sparseExamples;
  125. if (verbose)
  126. cerr << "Converting (and sampling) feature vectors" << endl;
  127. for ( uint i = 0 ; i < examples.size() ; i++ )
  128. {
  129. const Example & example = examples[i].second;
  130. int classno = examples[i].first;
  131. // simple weird balancing method
  132. if ( useSimpleBalancing )
  133. {
  134. double t = randDouble() * classCounts[classno];
  135. if ( t >= minSamples ) continue;
  136. }
  137. y[ sparseExamples.size() ] = classno;
  138. if ( example.svec == NULL )
  139. fthrow(Exception, "FPCGPHIK requires example.svec (SparseVector stored in an Example struct)");
  140. sparseExamples.push_back( example.svec );
  141. }
  142. // we only use a subset for training
  143. y.resize( sparseExamples.size() );
  144. classifier->train(sparseExamples, y);
  145. }
  146. /** training process */
  147. void FPCGPHIK::train ( const std::vector< const SparseVector *> & examples, std::map<int, NICE::Vector> & binLabels )
  148. {
  149. classifier->train(examples, binLabels);
  150. }
  151. void FPCGPHIK::clear ()
  152. {
  153. if ( classifier != NULL )
  154. delete classifier;
  155. classifier = NULL;
  156. }
  157. FeaturePoolClassifier *FPCGPHIK::clone () const
  158. {
  159. fthrow(Exception, "FPCGPHIK: clone() not yet implemented" );
  160. return NULL;
  161. }
  162. void FPCGPHIK::predictUncertainty( Example & pe, double & uncertainty )
  163. {
  164. const SparseVector *svec = pe.svec;
  165. if ( svec == NULL )
  166. fthrow(Exception, "FPCGPHIK requires example.svec (SparseVector stored in an Example struct)");
  167. classifier->predictUncertainty(svec, uncertainty);
  168. }
  169. void FPCGPHIK::predictUncertainty( const NICE::SparseVector * example, double & uncertainty )
  170. {
  171. classifier->predictUncertainty(example, uncertainty);
  172. }
  173. ///////////////////// INTERFACE PERSISTENT /////////////////////
  174. // interface specific methods for store and restore
  175. ///////////////////// INTERFACE PERSISTENT /////////////////////
  176. void FPCGPHIK::restore ( std::istream & is, int format )
  177. {
  178. if (is.good())
  179. {
  180. std::string tmp;
  181. is >> tmp; //class name
  182. if ( ! this->isStartTag( tmp, "FPCGPHIK" ) )
  183. {
  184. std::cerr << " WARNING - attempt to restore FPCGPHIK, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  185. throw;
  186. }
  187. is.precision (numeric_limits<double>::digits10 + 1);
  188. bool b_endOfBlock ( false ) ;
  189. while ( !b_endOfBlock )
  190. {
  191. is >> tmp; // start of block
  192. if ( this->isEndTag( tmp, "FPCGPHIK" ) )
  193. {
  194. b_endOfBlock = true;
  195. continue;
  196. }
  197. tmp = this->removeStartTag( tmp );
  198. if ( tmp.compare("classifier") == 0 )
  199. {
  200. if ( classifier == NULL )
  201. classifier = new NICE::GPHIKClassifier();
  202. //then, load everything that we stored explicitely,
  203. // including precomputed matrices, LUTs, eigenvalues, ... and all that stuff
  204. classifier->restore(is, format);
  205. is >> tmp; // end of block
  206. tmp = this->removeEndTag ( tmp );
  207. }
  208. else if ( tmp.compare("performOptimizationAfterIncrement") == 0 )
  209. {
  210. is >> performOptimizationAfterIncrement;
  211. is >> tmp; // end of block
  212. tmp = this->removeEndTag ( tmp );
  213. }
  214. else
  215. {
  216. std::cerr << "WARNING -- unexpected FPCGPHIK object -- " << tmp << " -- for restoration... aborting" << std::endl;
  217. throw;
  218. }
  219. } // while-loop
  220. }
  221. else
  222. {
  223. std::cerr << "FPCGPHIK::restore -- InStream not initialized - restoring not possible!" << std::endl;
  224. }
  225. }
  226. void FPCGPHIK::store ( std::ostream & os, int format ) const
  227. {
  228. if (os.good())
  229. {
  230. os.precision (numeric_limits<double>::digits10 + 1);
  231. // show starting point
  232. os << this->createStartTag( "FPCGPHIK" ) << std::endl;
  233. os << this->createStartTag( "classifier" ) << std::endl;
  234. classifier->store(os, format);
  235. os << this->createEndTag( "classifier" ) << std::endl;
  236. os << this->createStartTag( "performOptimizationAfterIncrement" ) << std::endl;
  237. os << performOptimizationAfterIncrement << std::endl;
  238. os << this->createEndTag( "performOptimizationAfterIncrement" ) << std::endl;
  239. // done
  240. os << this->createEndTag( "FPCGPHIK" ) << std::endl;
  241. }
  242. else
  243. {
  244. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  245. }
  246. }
  247. ///////////////////// INTERFACE ONLINE LEARNABLE (SIMILAR) /////////////////////
  248. // interface specific methods for incremental extensions
  249. ///////////////////// INTERFACE ONLINE LEARNABLE (SIMILAR) /////////////////////
  250. void FPCGPHIK::addExample( const Example & pe, const double & label)
  251. {
  252. const SparseVector *svec = pe.svec;
  253. classifier->addExample(svec, label, this->performOptimizationAfterIncrement);
  254. }
  255. void FPCGPHIK::addMultipleExamples( Examples & newExamples)
  256. {
  257. //are new examples available? If not, nothing has to be done
  258. if ( newExamples.size() < 1)
  259. return;
  260. // (multi-class) label vector
  261. NICE::Vector y ( newExamples.size() );
  262. // flat structure of our training data
  263. std::vector< const SparseVector * > sparseExamples;
  264. if (verbose)
  265. cerr << "Converting (and sampling) feature vectors" << endl;
  266. for ( uint i = 0 ; i < newExamples.size() ; i++ )
  267. {
  268. const Example & example = newExamples[i].second;
  269. int classno = newExamples[i].first;
  270. y[ i ] = classno;
  271. if ( example.svec == NULL )
  272. fthrow(Exception, "FPCGPHIK requires example.svec (SparseVector stored in an Example struct)");
  273. sparseExamples.push_back( example.svec );
  274. }
  275. classifier->addMultipleExamples(sparseExamples, y, this->performOptimizationAfterIncrement);
  276. }