GPHIKRawClassifier.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. #include <core/algebra/EigValues.h>
  14. // gp-hik-core includes
  15. #include "GPHIKRawClassifier.h"
  16. #include "GMHIKernelRaw.h"
  17. using namespace std;
  18. using namespace NICE;
  19. /////////////////////////////////////////////////////
  20. /////////////////////////////////////////////////////
  21. // PROTECTED METHODS
  22. /////////////////////////////////////////////////////
  23. /////////////////////////////////////////////////////
  24. /////////////////////////////////////////////////////
  25. /////////////////////////////////////////////////////
  26. // PUBLIC METHODS
  27. /////////////////////////////////////////////////////
  28. /////////////////////////////////////////////////////
  29. GPHIKRawClassifier::GPHIKRawClassifier( )
  30. {
  31. this->b_isTrained = false;
  32. this->confSection = "";
  33. this->nnz_per_dimension = NULL;
  34. // in order to be sure about all necessary variables be setup with default values, we
  35. // run initFromConfig with an empty config
  36. NICE::Config tmpConfEmpty ;
  37. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  38. }
  39. GPHIKRawClassifier::GPHIKRawClassifier( const Config *_conf,
  40. const string & _confSection
  41. )
  42. {
  43. ///////////
  44. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  45. ///////////
  46. this->b_isTrained = false;
  47. this->confSection = "";
  48. this->q = NULL;
  49. ///////////
  50. // here comes the new code part different from the empty constructor
  51. ///////////
  52. this->confSection = _confSection;
  53. // if no config file was given, we either restore the classifier from an external file, or run ::init with
  54. // an emtpy config (using default values thereby) when calling the train-method
  55. if ( _conf != NULL )
  56. {
  57. this->initFromConfig( _conf, _confSection );
  58. }
  59. else
  60. {
  61. // if no config was given, we create an empty one
  62. NICE::Config tmpConfEmpty ;
  63. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  64. }
  65. }
  66. GPHIKRawClassifier::~GPHIKRawClassifier()
  67. {
  68. delete this->solver;
  69. this->solver = NULL;
  70. }
  71. void GPHIKRawClassifier::initFromConfig(const Config *_conf,
  72. const string & _confSection
  73. )
  74. {
  75. this->d_noise = _conf->gD( _confSection, "noise", 0.01);
  76. this->confSection = _confSection;
  77. this->b_verbose = _conf->gB( _confSection, "verbose", false);
  78. this->b_debug = _conf->gB( _confSection, "debug", false);
  79. this->f_tolerance = _conf->gD( _confSection, "f_tolerance", 1e-10);
  80. //FIXME this is not used in that way for the standard GPHIKClassifier
  81. //string ilssection = "FMKGPHyperparameterOptimization";
  82. string ilssection = _confSection;
  83. uint ils_max_iterations = _conf->gI( ilssection, "ils_max_iterations", 1000 );
  84. double ils_min_delta = _conf->gD( ilssection, "ils_min_delta", 1e-7 );
  85. double ils_min_residual = _conf->gD( ilssection, "ils_min_residual", 1e-7 );
  86. bool ils_verbose = _conf->gB( ilssection, "ils_verbose", false );
  87. this->solver = new ILSConjugateGradients( ils_verbose,
  88. ils_max_iterations,
  89. ils_min_delta,
  90. ils_min_residual
  91. );
  92. if ( this->b_verbose )
  93. {
  94. std::cerr << "GPHIKRawClassifier::initFromConfig " <<std::endl;
  95. std::cerr << " confSection " << confSection << std::endl;
  96. std::cerr << " d_noise " << d_noise << std::endl;
  97. std::cerr << " f_tolerance " << f_tolerance << std::endl;
  98. std::cerr << " ils_max_iterations " << ils_max_iterations << std::endl;
  99. std::cerr << " ils_min_delta " << ils_min_delta << std::endl;
  100. std::cerr << " ils_min_residual " << ils_min_residual << std::endl;
  101. std::cerr << " ils_verbose " << ils_verbose << std::endl;
  102. }
  103. }
  104. ///////////////////// ///////////////////// /////////////////////
  105. // GET / SET
  106. ///////////////////// ///////////////////// /////////////////////
  107. std::set<uint> GPHIKRawClassifier::getKnownClassNumbers ( ) const
  108. {
  109. if ( ! this->b_isTrained )
  110. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  111. return this->knownClasses;
  112. }
  113. ///////////////////// ///////////////////// /////////////////////
  114. // CLASSIFIER STUFF
  115. ///////////////////// ///////////////////// /////////////////////
  116. void GPHIKRawClassifier::classify ( const NICE::SparseVector * _xstar,
  117. uint & _result,
  118. SparseVector & _scores
  119. ) const
  120. {
  121. if ( ! this->b_isTrained )
  122. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  123. _scores.clear();
  124. GMHIKernelRaw::sparseVectorElement **dataMatrix = gm->getDataMatrix();
  125. uint maxClassNo = 0;
  126. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  127. {
  128. uint classno = i->first;
  129. maxClassNo = std::max ( maxClassNo, classno );
  130. double beta = 0;
  131. if ( this->q != NULL ) {
  132. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  133. double *T = j->second;
  134. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++ )
  135. {
  136. uint dim = i->first;
  137. double v = i->second;
  138. uint qBin = q->quantize( v, dim );
  139. beta += T[dim * q->getNumberOfBins() + qBin];
  140. }
  141. } else {
  142. const PrecomputedType & A = i->second;
  143. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  144. const PrecomputedType & B = j->second;
  145. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++)
  146. {
  147. uint dim = i->first;
  148. double fval = i->second;
  149. uint nnz = this->nnz_per_dimension[dim];
  150. uint nz = this->num_examples - nnz;
  151. if ( nnz == 0 ) continue;
  152. if ( fval < this->f_tolerance ) continue;
  153. uint position = 0;
  154. //this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  155. GMHIKernelRaw::sparseVectorElement fval_element;
  156. fval_element.value = fval;
  157. GMHIKernelRaw::sparseVectorElement *it = upper_bound ( dataMatrix[dim], dataMatrix[dim] + nnz, fval_element );
  158. position = distance ( dataMatrix[dim], it );
  159. bool posIsZero ( position == 0 );
  160. if ( !posIsZero )
  161. position--;
  162. double firstPart = 0.0;
  163. if ( !posIsZero && ((position-nz) < this->num_examples) )
  164. firstPart = (A[dim][position-nz]);
  165. double secondPart( B[dim][this->num_examples-1-nz]);
  166. if ( !posIsZero && (position >= nz) )
  167. secondPart -= B[dim][position-nz];
  168. // but apply using the transformed one
  169. beta += firstPart + secondPart* fval;
  170. }
  171. }
  172. _scores[ classno ] = beta;
  173. }
  174. _scores.setDim ( *this->knownClasses.rbegin() + 1 );
  175. if ( this->knownClasses.size() > 2 )
  176. { // multi-class classification
  177. _result = _scores.maxElement();
  178. }
  179. else if ( this->knownClasses.size() == 2 ) // binary setting
  180. {
  181. uint class1 = *(this->knownClasses.begin());
  182. uint class2 = *(this->knownClasses.rbegin());
  183. uint class_for_which_we_have_a_score = _scores.begin()->first;
  184. uint class_for_which_we_dont_have_a_score = (class1 == class_for_which_we_have_a_score ? class2 : class1);
  185. _scores[class_for_which_we_dont_have_a_score] = - _scores[class_for_which_we_have_a_score];
  186. _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;
  187. }
  188. }
  189. /** training process */
  190. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  191. const NICE::Vector & _labels
  192. )
  193. {
  194. // security-check: examples and labels have to be of same size
  195. if ( _examples.size() != _labels.size() )
  196. {
  197. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  198. }
  199. this->num_examples = _examples.size();
  200. this->knownClasses.clear();
  201. for ( uint i = 0; i < _labels.size(); i++ )
  202. this->knownClasses.insert((uint)_labels[i]);
  203. std::map<uint, NICE::Vector> binLabels;
  204. for ( set<uint>::const_iterator j = knownClasses.begin(); j != knownClasses.end(); j++ )
  205. {
  206. uint current_class = *j;
  207. Vector labels_binary ( _labels.size() );
  208. for ( uint i = 0; i < _labels.size(); i++ )
  209. labels_binary[i] = ( _labels[i] == current_class ) ? 1.0 : -1.0;
  210. binLabels.insert ( pair<uint, NICE::Vector>( current_class, labels_binary) );
  211. }
  212. // handle special binary case
  213. if ( knownClasses.size() == 2 )
  214. {
  215. std::map<uint, NICE::Vector>::iterator it = binLabels.begin();
  216. it++;
  217. binLabels.erase( binLabels.begin(), it );
  218. }
  219. this->train ( _examples, binLabels );
  220. }
  221. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  222. std::map<uint, NICE::Vector> & _binLabels
  223. )
  224. {
  225. // security-check: examples and labels have to be of same size
  226. for ( std::map< uint, NICE::Vector >::const_iterator binLabIt = _binLabels.begin();
  227. binLabIt != _binLabels.end();
  228. binLabIt++
  229. )
  230. {
  231. if ( _examples.size() != binLabIt->second.size() )
  232. {
  233. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  234. }
  235. }
  236. if ( this->b_verbose )
  237. std::cerr << "GPHIKRawClassifier::train" << std::endl;
  238. Timer t;
  239. t.start();
  240. precomputedA.clear();
  241. precomputedB.clear();
  242. precomputedT.clear();
  243. // sort examples in each dimension and "transpose" the feature matrix
  244. // set up the GenericMatrix interface
  245. gm = new GMHIKernelRaw ( _examples, this->d_noise );
  246. nnz_per_dimension = gm->getNNZPerDimension();
  247. // compute largest eigenvalue of our kernel matrix
  248. // note: this guy is shared among all categories,
  249. // since the kernel matrix is shared as well
  250. NICE::Vector eigenMax;
  251. NICE::Matrix eigenMaxV;
  252. // for reproducibility during debuggin
  253. srand ( 0 );
  254. srand48 ( 0 );
  255. NICE::EigValues * eig = new EVArnoldi ( false /* verbose flag */,
  256. 10 /*_maxiterations*/
  257. );
  258. eig->getEigenvalues( *gm, eigenMax, eigenMaxV, 1 /*rank*/ );
  259. delete eig;
  260. std::cerr << " largest eigenvalue: " << eigenMax[0] << std::endl;
  261. // set simple jacobi pre-conditioning
  262. NICE::Vector diagonalElements;
  263. gm->getDiagonalElements ( diagonalElements );
  264. solver->setJacobiPreconditioner ( diagonalElements );
  265. // solve linear equations for each class
  266. // be careful when parallising this!
  267. for ( std::map<uint, NICE::Vector>::const_iterator i = _binLabels.begin();
  268. i != _binLabels.end();
  269. i++
  270. )
  271. {
  272. uint classno = i->first;
  273. if (b_verbose)
  274. std::cerr << "Training for class " << classno << endl;
  275. const NICE::Vector & y = i->second;
  276. NICE::Vector alpha;
  277. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  278. * K~ = K + sigma^2 I
  279. *
  280. * K~ \approx lambda_max v v^T
  281. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  282. * => \lambda_max v^T alpha = v^T k_*
  283. * => alpha = k_* / lambda_max could be a good initial start
  284. * If we put everything in the first equation this gives us
  285. * v = k_*
  286. * This reduces the number of iterations by 5 or 8
  287. */
  288. alpha = (y * (1.0 / eigenMax[0]) );
  289. //DEBUG!!!
  290. if ( this->b_debug && classno == 1 )
  291. {
  292. std::cerr << "Training for class " << classno << endl;
  293. std::cerr << y << std::endl;
  294. std::cerr << " alpha before and after linsolve" << classno << endl;
  295. std::cerr << " " << alpha << std::endl;
  296. }
  297. solver->solveLin( *gm, y, alpha );
  298. //DEBUG!!!
  299. if ( this->b_debug && classno == 1 )
  300. {
  301. // std::cerr << "Training for class " << classno << endl;
  302. std::cerr << " " << alpha << std::endl;
  303. }
  304. // TODO: get lookup tables, A, B, etc. and store them
  305. gm->updateTables(alpha);
  306. double **A = gm->getTableA();
  307. double **B = gm->getTableB();
  308. precomputedA.insert ( pair<uint, PrecomputedType> ( classno, A ) );
  309. precomputedB.insert ( pair<uint, PrecomputedType> ( classno, B ) );
  310. }
  311. t.stop();
  312. if ( this->b_verbose )
  313. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  314. //indicate that we finished training successfully
  315. this->b_isTrained = true;
  316. // clean up all examples ??
  317. if ( this->b_verbose )
  318. std::cerr << "Learning finished" << std::endl;
  319. }