GPHIKRawClassifier.cpp 13 KB

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