GPHIKClassifierNICE.cpp 9.9 KB

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