GPHIKRawClassifier.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 this->solver;
  68. this->solver = NULL;
  69. }
  70. void GPHIKRawClassifier::initFromConfig(const Config *_conf,
  71. const string & _confSection
  72. )
  73. {
  74. this->d_noise = _conf->gD( _confSection, "noise", 0.01);
  75. this->confSection = _confSection;
  76. this->b_verbose = _conf->gB( _confSection, "verbose", false);
  77. this->b_debug = _conf->gB( _confSection, "debug", false);
  78. this->f_tolerance = _conf->gD( _confSection, "f_tolerance", 1e-10);
  79. //FIXME this is not used in that way for the standard GPHIKClassifier
  80. //string ilssection = "FMKGPHyperparameterOptimization";
  81. string ilssection = _confSection;
  82. uint ils_max_iterations = _conf->gI( ilssection, "ils_max_iterations", 1000 );
  83. double ils_min_delta = _conf->gD( ilssection, "ils_min_delta", 1e-7 );
  84. double ils_min_residual = _conf->gD( ilssection, "ils_min_residual", 1e-7 );
  85. bool ils_verbose = _conf->gB( ilssection, "ils_verbose", false );
  86. this->solver = new ILSConjugateGradients( ils_verbose,
  87. ils_max_iterations,
  88. ils_min_delta,
  89. ils_min_residual
  90. );
  91. if ( this->b_verbose )
  92. {
  93. std::cerr << "GPHIKRawClassifier::initFromConfig " <<std::endl;
  94. std::cerr << " confSection " << confSection << std::endl;
  95. std::cerr << " d_noise " << d_noise << std::endl;
  96. std::cerr << " f_tolerance " << f_tolerance << std::endl;
  97. std::cerr << " ils_max_iterations " << ils_max_iterations << std::endl;
  98. std::cerr << " ils_min_delta " << ils_min_delta << std::endl;
  99. std::cerr << " ils_min_residual " << ils_min_residual << std::endl;
  100. std::cerr << " ils_verbose " << ils_verbose << std::endl;
  101. }
  102. }
  103. ///////////////////// ///////////////////// /////////////////////
  104. // GET / SET
  105. ///////////////////// ///////////////////// /////////////////////
  106. std::set<uint> GPHIKRawClassifier::getKnownClassNumbers ( ) const
  107. {
  108. if ( ! this->b_isTrained )
  109. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  110. return this->knownClasses;
  111. }
  112. ///////////////////// ///////////////////// /////////////////////
  113. // CLASSIFIER STUFF
  114. ///////////////////// ///////////////////// /////////////////////
  115. void GPHIKRawClassifier::classify ( const NICE::SparseVector * _xstar,
  116. uint & _result,
  117. SparseVector & _scores
  118. ) const
  119. {
  120. if ( ! this->b_isTrained )
  121. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  122. _scores.clear();
  123. GMHIKernelRaw::sparseVectorElement **dataMatrix = gm->getDataMatrix();
  124. uint maxClassNo = 0;
  125. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  126. {
  127. uint classno = i->first;
  128. maxClassNo = std::max ( maxClassNo, classno );
  129. double beta = 0;
  130. if ( this->q != NULL ) {
  131. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  132. double *T = j->second;
  133. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++ )
  134. {
  135. uint dim = i->first;
  136. double v = i->second;
  137. uint qBin = q->quantize( v, dim );
  138. beta += T[dim * q->getNumberOfBins() + qBin];
  139. }
  140. } else {
  141. const PrecomputedType & A = i->second;
  142. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  143. const PrecomputedType & B = j->second;
  144. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++)
  145. {
  146. uint dim = i->first;
  147. double fval = i->second;
  148. uint nnz = this->nnz_per_dimension[dim];
  149. uint nz = this->num_examples - nnz;
  150. if ( nnz == 0 ) continue;
  151. if ( fval < this->f_tolerance ) continue;
  152. uint position = 0;
  153. //this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  154. GMHIKernelRaw::sparseVectorElement fval_element;
  155. fval_element.value = fval;
  156. GMHIKernelRaw::sparseVectorElement *it = upper_bound ( dataMatrix[dim], dataMatrix[dim] + nnz, fval_element );
  157. position = distance ( dataMatrix[dim], it );
  158. bool posIsZero ( position == 0 );
  159. if ( !posIsZero )
  160. position--;
  161. double firstPart = 0.0;
  162. if ( !posIsZero && ((position-nz) < this->num_examples) )
  163. firstPart = (A[dim][position-nz]);
  164. double secondPart( B[dim][this->num_examples-1-nz]);
  165. if ( !posIsZero && (position >= nz) )
  166. secondPart -= B[dim][position-nz];
  167. // but apply using the transformed one
  168. beta += firstPart + secondPart* fval;
  169. }
  170. }
  171. _scores[ classno ] = beta;
  172. }
  173. _scores.setDim ( *this->knownClasses.rbegin() + 1 );
  174. if ( this->knownClasses.size() > 2 )
  175. { // multi-class classification
  176. _result = _scores.maxElement();
  177. }
  178. else if ( this->knownClasses.size() == 2 ) // binary setting
  179. {
  180. uint class1 = *(this->knownClasses.begin());
  181. uint class2 = *(this->knownClasses.rbegin());
  182. uint class_for_which_we_have_a_score = _scores.begin()->first;
  183. uint class_for_which_we_dont_have_a_score = (class1 == class_for_which_we_have_a_score ? class2 : class1);
  184. _scores[class_for_which_we_dont_have_a_score] = - _scores[class_for_which_we_have_a_score];
  185. _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;
  186. }
  187. }
  188. /** training process */
  189. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  190. const NICE::Vector & _labels
  191. )
  192. {
  193. // security-check: examples and labels have to be of same size
  194. if ( _examples.size() != _labels.size() )
  195. {
  196. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  197. }
  198. this->num_examples = _examples.size();
  199. this->knownClasses.clear();
  200. for ( uint i = 0; i < _labels.size(); i++ )
  201. this->knownClasses.insert((uint)_labels[i]);
  202. std::map<uint, NICE::Vector> binLabels;
  203. for ( set<uint>::const_iterator j = knownClasses.begin(); j != knownClasses.end(); j++ )
  204. {
  205. uint current_class = *j;
  206. Vector labels_binary ( _labels.size() );
  207. for ( uint i = 0; i < _labels.size(); i++ )
  208. labels_binary[i] = ( _labels[i] == current_class ) ? 1.0 : -1.0;
  209. binLabels.insert ( pair<uint, NICE::Vector>( current_class, labels_binary) );
  210. }
  211. // handle special binary case
  212. if ( knownClasses.size() == 2 )
  213. {
  214. std::map<uint, NICE::Vector>::iterator it = binLabels.begin();
  215. it++;
  216. binLabels.erase( binLabels.begin(), it );
  217. }
  218. train ( _examples, binLabels );
  219. }
  220. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  221. std::map<uint, NICE::Vector> & _binLabels
  222. )
  223. {
  224. // security-check: examples and labels have to be of same size
  225. for ( std::map< uint, NICE::Vector >::const_iterator binLabIt = _binLabels.begin();
  226. binLabIt != _binLabels.end();
  227. binLabIt++
  228. )
  229. {
  230. if ( _examples.size() != binLabIt->second.size() )
  231. {
  232. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  233. }
  234. }
  235. if ( this->b_verbose )
  236. std::cerr << "GPHIKRawClassifier::train" << std::endl;
  237. Timer t;
  238. t.start();
  239. precomputedA.clear();
  240. precomputedB.clear();
  241. precomputedT.clear();
  242. // sort examples in each dimension and "transpose" the feature matrix
  243. // set up the GenericMatrix interface
  244. gm = new GMHIKernelRaw ( _examples, this->d_noise );
  245. nnz_per_dimension = gm->getNNZPerDimension();
  246. // solve linear equations for each class
  247. // be careful when parallising this!
  248. for ( map<uint, NICE::Vector>::const_iterator i = _binLabels.begin();
  249. i != _binLabels.end(); i++ )
  250. {
  251. uint classno = i->first;
  252. if (b_verbose)
  253. std::cerr << "Training for class " << classno << endl;
  254. const Vector & y = i->second;
  255. Vector alpha;
  256. solver->solveLin( *gm, y, alpha );
  257. // TODO: get lookup tables, A, B, etc. and store them
  258. gm->updateTables(alpha);
  259. double **A = gm->getTableA();
  260. double **B = gm->getTableB();
  261. precomputedA.insert ( pair<uint, PrecomputedType> ( classno, A ) );
  262. precomputedB.insert ( pair<uint, PrecomputedType> ( classno, B ) );
  263. }
  264. t.stop();
  265. if ( this->b_verbose )
  266. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  267. //indicate that we finished training successfully
  268. this->b_isTrained = true;
  269. // clean up all examples ??
  270. if ( this->b_verbose )
  271. std::cerr << "Learning finished" << std::endl;
  272. }