GPHIKRawClassifier.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /**
  2. * @file GPHIKRawClassifier.cpp
  3. * @brief Main interface for our GP HIK classifier (similar to the feature pool classifier interface in vislearning) (Implementation)
  4. * @author Erik Rodner, 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 <core/algebra/ILSConjugateGradients.h>
  13. // gp-hik-core includes
  14. #include "GPHIKRawClassifier.h"
  15. #include "GMHIKernelRaw.h"
  16. using namespace std;
  17. using namespace NICE;
  18. /////////////////////////////////////////////////////
  19. /////////////////////////////////////////////////////
  20. // PROTECTED METHODS
  21. /////////////////////////////////////////////////////
  22. /////////////////////////////////////////////////////
  23. /////////////////////////////////////////////////////
  24. /////////////////////////////////////////////////////
  25. // PUBLIC METHODS
  26. /////////////////////////////////////////////////////
  27. /////////////////////////////////////////////////////
  28. GPHIKRawClassifier::GPHIKRawClassifier( )
  29. {
  30. this->b_isTrained = false;
  31. this->confSection = "";
  32. this->nnz_per_dimension = NULL;
  33. // in order to be sure about all necessary variables be setup with default values, we
  34. // run initFromConfig with an empty config
  35. NICE::Config tmpConfEmpty ;
  36. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  37. }
  38. GPHIKRawClassifier::GPHIKRawClassifier( const Config *_conf,
  39. const string & _confSection
  40. )
  41. {
  42. ///////////
  43. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  44. ///////////
  45. this->b_isTrained = false;
  46. this->confSection = "";
  47. this->q = NULL;
  48. ///////////
  49. // here comes the new code part different from the empty constructor
  50. ///////////
  51. this->confSection = _confSection;
  52. // if no config file was given, we either restore the classifier from an external file, or run ::init with
  53. // an emtpy config (using default values thereby) when calling the train-method
  54. if ( _conf != NULL )
  55. {
  56. this->initFromConfig( _conf, _confSection );
  57. }
  58. else
  59. {
  60. // if no config was given, we create an empty one
  61. NICE::Config tmpConfEmpty ;
  62. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  63. }
  64. }
  65. GPHIKRawClassifier::~GPHIKRawClassifier()
  66. {
  67. delete solver;
  68. }
  69. void GPHIKRawClassifier::initFromConfig(const Config *_conf,
  70. const string & _confSection
  71. )
  72. {
  73. this->d_noise = _conf->gD( _confSection, "noise", 0.01);
  74. this->confSection = _confSection;
  75. this->b_verbose = _conf->gB( _confSection, "verbose", false);
  76. this->b_debug = _conf->gB( _confSection, "debug", false);
  77. this->f_tolerance = _conf->gD( _confSection, "f_tolerance", 1e-10);
  78. string ilssection = "FMKGPHyperparameterOptimization";
  79. uint ils_max_iterations = _conf->gI( ilssection, "ils_max_iterations", 1000 );
  80. double ils_min_delta = _conf->gD( ilssection, "ils_min_delta", 1e-7 );
  81. double ils_min_residual = _conf->gD( ilssection, "ils_min_residual", 1e-7 );
  82. bool ils_verbose = _conf->gB( ilssection, "ils_verbose", false );
  83. this->solver = new ILSConjugateGradients( ils_verbose, ils_max_iterations, ils_min_delta, ils_min_residual );
  84. }
  85. ///////////////////// ///////////////////// /////////////////////
  86. // GET / SET
  87. ///////////////////// ///////////////////// /////////////////////
  88. std::set<uint> GPHIKRawClassifier::getKnownClassNumbers ( ) const
  89. {
  90. if ( ! this->b_isTrained )
  91. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  92. fthrow(Exception, "GPHIKRawClassifier::getKnownClassNumbers() not yet implemented");
  93. }
  94. ///////////////////// ///////////////////// /////////////////////
  95. // CLASSIFIER STUFF
  96. ///////////////////// ///////////////////// /////////////////////
  97. void GPHIKRawClassifier::classify ( const NICE::SparseVector * _xstar,
  98. uint & _result,
  99. SparseVector & _scores
  100. ) const
  101. {
  102. if ( ! this->b_isTrained )
  103. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  104. _scores.clear();
  105. GMHIKernelRaw::sparseVectorElement **dataMatrix = gm->getDataMatrix();
  106. uint maxClassNo = 0;
  107. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  108. {
  109. uint classno = i->first;
  110. maxClassNo = std::max ( maxClassNo, classno );
  111. double beta = 0;
  112. if ( this->q != NULL ) {
  113. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  114. double *T = j->second;
  115. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++ )
  116. {
  117. uint dim = i->first;
  118. double v = i->second;
  119. uint qBin = q->quantize( v, dim );
  120. beta += T[dim * q->getNumberOfBins() + qBin];
  121. }
  122. } else {
  123. const PrecomputedType & A = i->second;
  124. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  125. const PrecomputedType & B = j->second;
  126. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++)
  127. {
  128. uint dim = i->first;
  129. double fval = i->second;
  130. uint nnz = this->nnz_per_dimension[dim];
  131. uint nz = this->num_examples - nnz;
  132. if ( nnz == 0 ) continue;
  133. if ( fval < this->f_tolerance ) continue;
  134. uint position = 0;
  135. //this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  136. GMHIKernelRaw::sparseVectorElement fval_element;
  137. fval_element.value = fval;
  138. GMHIKernelRaw::sparseVectorElement *it = upper_bound ( dataMatrix[dim], dataMatrix[dim] + nnz, fval_element );
  139. position = distance ( dataMatrix[dim], it );
  140. bool posIsZero ( position == 0 );
  141. if ( !posIsZero )
  142. position--;
  143. double firstPart = 0.0;
  144. if ( !posIsZero && ((position-nz) < this->num_examples) )
  145. firstPart = (A[dim][position-nz]);
  146. double secondPart( B[dim][this->num_examples-1-nz]);
  147. if ( !posIsZero && (position >= nz) )
  148. secondPart -= B[dim][position-nz];
  149. // but apply using the transformed one
  150. beta += firstPart + secondPart* fval;
  151. }
  152. }
  153. _scores[ classno ] = beta;
  154. }
  155. _scores.setDim ( *this->knownClasses.rbegin() + 1 );
  156. if ( this->knownClasses.size() > 2 )
  157. { // multi-class classification
  158. _result = _scores.maxElement();
  159. }
  160. else if ( this->knownClasses.size() == 2 ) // binary setting
  161. {
  162. uint class1 = *(this->knownClasses.begin());
  163. uint class2 = *(this->knownClasses.rbegin());
  164. uint class_for_which_we_have_a_score = _scores.begin()->first;
  165. uint class_for_which_we_dont_have_a_score = (class1 == class_for_which_we_have_a_score ? class2 : class1);
  166. _scores[class_for_which_we_dont_have_a_score] = - _scores[class_for_which_we_have_a_score];
  167. _result = _scores[class_for_which_we_have_a_score] > 0.0 ? class_for_which_we_have_a_score : class_for_which_we_dont_have_a_score;
  168. }
  169. }
  170. /** training process */
  171. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  172. const NICE::Vector & _labels
  173. )
  174. {
  175. // security-check: examples and labels have to be of same size
  176. if ( _examples.size() != _labels.size() )
  177. {
  178. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  179. }
  180. this->num_examples = _examples.size();
  181. this->knownClasses.clear();
  182. for ( uint i = 0; i < _labels.size(); i++ )
  183. this->knownClasses.insert((uint)_labels[i]);
  184. std::map<uint, NICE::Vector> binLabels;
  185. for ( set<uint>::const_iterator j = knownClasses.begin(); j != knownClasses.end(); j++ )
  186. {
  187. uint current_class = *j;
  188. Vector labels_binary ( _labels.size() );
  189. for ( uint i = 0; i < _labels.size(); i++ )
  190. labels_binary[i] = ( _labels[i] == current_class ) ? 1.0 : -1.0;
  191. binLabels.insert ( pair<uint, NICE::Vector>( current_class, labels_binary) );
  192. }
  193. // handle special binary case
  194. if ( knownClasses.size() == 2 )
  195. {
  196. std::map<uint, NICE::Vector>::iterator it = binLabels.begin();
  197. it++;
  198. binLabels.erase( binLabels.begin(), it );
  199. }
  200. train ( _examples, binLabels );
  201. }
  202. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  203. std::map<uint, NICE::Vector> & _binLabels
  204. )
  205. {
  206. // security-check: examples and labels have to be of same size
  207. for ( std::map< uint, NICE::Vector >::const_iterator binLabIt = _binLabels.begin();
  208. binLabIt != _binLabels.end();
  209. binLabIt++
  210. )
  211. {
  212. if ( _examples.size() != binLabIt->second.size() )
  213. {
  214. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  215. }
  216. }
  217. if ( this->b_verbose )
  218. std::cerr << "GPHIKRawClassifier::train" << std::endl;
  219. Timer t;
  220. t.start();
  221. precomputedA.clear();
  222. precomputedB.clear();
  223. precomputedT.clear();
  224. // sort examples in each dimension and "transpose" the feature matrix
  225. // set up the GenericMatrix interface
  226. gm = new GMHIKernelRaw ( _examples, this->d_noise );
  227. nnz_per_dimension = gm->getNNZPerDimension();
  228. // solve linear equations for each class
  229. // be careful when parallising this!
  230. for ( map<uint, NICE::Vector>::const_iterator i = _binLabels.begin();
  231. i != _binLabels.end(); i++ )
  232. {
  233. uint classno = i->first;
  234. if (b_verbose)
  235. std::cerr << "Training for class " << classno << endl;
  236. const Vector & y = i->second;
  237. Vector alpha;
  238. solver->solveLin( *gm, y, alpha );
  239. // TODO: get lookup tables, A, B, etc. and store them
  240. gm->updateTables(alpha);
  241. double **A = gm->getTableA();
  242. double **B = gm->getTableB();
  243. precomputedA.insert ( pair<uint, PrecomputedType> ( classno, A ) );
  244. precomputedB.insert ( pair<uint, PrecomputedType> ( classno, B ) );
  245. }
  246. t.stop();
  247. if ( this->b_verbose )
  248. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  249. //indicate that we finished training successfully
  250. this->b_isTrained = true;
  251. // clean up all examples ??
  252. if ( this->b_verbose )
  253. std::cerr << "Learning finished" << std::endl;
  254. }