GPHIKRawClassifier.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 "gp-hik-core/GPHIKRawClassifier.h"
  16. #include "gp-hik-core/GMHIKernelRaw.h"
  17. //
  18. #include "gp-hik-core/quantization/Quantization1DAequiDist0To1.h"
  19. #include "gp-hik-core/quantization/Quantization1DAequiDist0ToMax.h"
  20. #include "gp-hik-core/quantization/QuantizationNDAequiDist0ToMax.h"
  21. using namespace std;
  22. using namespace NICE;
  23. /////////////////////////////////////////////////////
  24. /////////////////////////////////////////////////////
  25. // PROTECTED METHODS
  26. /////////////////////////////////////////////////////
  27. /////////////////////////////////////////////////////
  28. void GPHIKRawClassifier::clearSetsOfTablesAandB( )
  29. {
  30. // delete all LUTs A which are needed when no quantization is activated
  31. for ( std::map< uint,PrecomputedType >::iterator itA = this->precomputedA.begin();
  32. itA != this->precomputedA.end();
  33. itA++
  34. )
  35. {
  36. for ( uint idxDim = 0 ; idxDim < this->num_dimension; idxDim++ )
  37. {
  38. if ( (itA->second)[idxDim] != NULL )
  39. delete [] (itA->second)[idxDim];
  40. }
  41. delete [] itA->second;
  42. }
  43. this->precomputedA.clear();
  44. // delete all LUTs B which are needed when no quantization is activated
  45. for ( std::map< uint,PrecomputedType >::iterator itB = this->precomputedB.begin();
  46. itB != this->precomputedB.end();
  47. itB++
  48. )
  49. {
  50. for ( uint idxDim = 0 ; idxDim < this->num_dimension; idxDim++ )
  51. {
  52. if ( (itB->second)[idxDim] != NULL )
  53. delete [] (itB->second)[idxDim];
  54. }
  55. delete [] itB->second;
  56. }
  57. this->precomputedB.clear();
  58. }
  59. void GPHIKRawClassifier::clearSetsOfTablesT( )
  60. {
  61. // delete all LUTs used for quantization
  62. for ( std::map< uint, double * >::iterator itT = this->precomputedT.begin();
  63. itT != this->precomputedT.end();
  64. itT++
  65. )
  66. {
  67. delete [] itT->second;
  68. }
  69. this->precomputedT.clear();
  70. }
  71. /////////////////////////////////////////////////////
  72. /////////////////////////////////////////////////////
  73. // PUBLIC METHODS
  74. /////////////////////////////////////////////////////
  75. /////////////////////////////////////////////////////
  76. GPHIKRawClassifier::GPHIKRawClassifier( )
  77. {
  78. this->b_isTrained = false;
  79. this->confSection = "";
  80. this->nnz_per_dimension = NULL;
  81. this->num_examples = 0;
  82. this->num_dimension = 0;
  83. this->q = NULL;
  84. this->gm = NULL;
  85. // in order to be sure about all necessary variables be setup with default values, we
  86. // run initFromConfig with an empty config
  87. NICE::Config tmpConfEmpty ;
  88. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  89. }
  90. GPHIKRawClassifier::GPHIKRawClassifier( const Config *_conf,
  91. const string & _confSection
  92. )
  93. {
  94. ///////////
  95. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  96. ///////////
  97. this->b_isTrained = false;
  98. this->confSection = "";
  99. this->nnz_per_dimension = NULL;
  100. this->num_examples = 0;
  101. this->num_dimension = 0;
  102. this->q = NULL;
  103. this->gm = NULL;
  104. ///////////
  105. // here comes the new code part different from the empty constructor
  106. ///////////
  107. this->confSection = _confSection;
  108. // if no config file was given, we either restore the classifier from an external file, or run ::init with
  109. // an emtpy config (using default values thereby) when calling the train-method
  110. if ( _conf != NULL )
  111. {
  112. this->initFromConfig( _conf, _confSection );
  113. }
  114. else
  115. {
  116. // if no config was given, we create an empty one
  117. NICE::Config tmpConfEmpty ;
  118. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  119. }
  120. }
  121. GPHIKRawClassifier::~GPHIKRawClassifier()
  122. {
  123. if ( this->solver != NULL )
  124. {
  125. delete this->solver;
  126. this->solver = NULL;
  127. }
  128. if ( this->gm != NULL)
  129. {
  130. delete this->gm;
  131. this->gm = NULL;
  132. }
  133. this->clearSetsOfTablesAandB();
  134. this->clearSetsOfTablesT();
  135. if ( this->q != NULL )
  136. {
  137. delete this->q;
  138. this->q = NULL;
  139. }
  140. }
  141. void GPHIKRawClassifier::initFromConfig(const Config *_conf,
  142. const string & _confSection
  143. )
  144. {
  145. this->d_noise = _conf->gD( _confSection, "noise", 0.01);
  146. this->confSection = _confSection;
  147. this->b_verbose = _conf->gB( _confSection, "verbose", false);
  148. this->b_debug = _conf->gB( _confSection, "debug", false);
  149. this->f_tolerance = _conf->gD( _confSection, "f_tolerance", 1e-10);
  150. //FIXME this is not used in that way for the standard GPHIKClassifier
  151. //string ilssection = "FMKGPHyperparameterOptimization";
  152. string ilssection = _confSection;
  153. uint ils_max_iterations = _conf->gI( ilssection, "ils_max_iterations", 1000 );
  154. double ils_min_delta = _conf->gD( ilssection, "ils_min_delta", 1e-7 );
  155. double ils_min_residual = _conf->gD( ilssection, "ils_min_residual", 1e-7 );
  156. bool ils_verbose = _conf->gB( ilssection, "ils_verbose", false );
  157. this->solver = new ILSConjugateGradients( ils_verbose,
  158. ils_max_iterations,
  159. ils_min_delta,
  160. ils_min_residual
  161. );
  162. if ( this->b_verbose )
  163. {
  164. std::cerr << "GPHIKRawClassifier::initFromConfig " <<std::endl;
  165. std::cerr << " confSection " << confSection << std::endl;
  166. std::cerr << " d_noise " << d_noise << std::endl;
  167. std::cerr << " f_tolerance " << f_tolerance << std::endl;
  168. std::cerr << " ils_max_iterations " << ils_max_iterations << std::endl;
  169. std::cerr << " ils_min_delta " << ils_min_delta << std::endl;
  170. std::cerr << " ils_min_residual " << ils_min_residual << std::endl;
  171. std::cerr << " ils_verbose " << ils_verbose << std::endl;
  172. }
  173. //quantization during classification?
  174. bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
  175. if ( this->b_verbose )
  176. {
  177. std::cerr << "_confSection: " << _confSection << std::endl;
  178. std::cerr << "use_quantization: " << useQuantization << std::endl;
  179. }
  180. if ( _conf->gB ( _confSection, "use_quantization", false ) )
  181. {
  182. int numBins = _conf->gI ( _confSection, "num_bins", 100 );
  183. if ( this->b_verbose )
  184. std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
  185. std::string s_quantType = _conf->gS( _confSection, "s_quantType", "1d-aequi-0-1" );
  186. if ( s_quantType == "1d-aequi-0-1" )
  187. {
  188. this->q = new NICE::Quantization1DAequiDist0To1 ( numBins );
  189. }
  190. else if ( s_quantType == "1d-aequi-0-max" )
  191. {
  192. this->q = new NICE::Quantization1DAequiDist0ToMax ( numBins );
  193. }
  194. else if ( s_quantType == "nd-aequi-0-max" )
  195. {
  196. this->q = new NICE::QuantizationNDAequiDist0ToMax ( numBins );
  197. }
  198. else
  199. {
  200. fthrow(Exception, "Quantization type is unknown " << s_quantType);
  201. }
  202. }
  203. else
  204. {
  205. this->q = NULL;
  206. }
  207. }
  208. ///////////////////// ///////////////////// /////////////////////
  209. // GET / SET
  210. ///////////////////// ///////////////////// /////////////////////
  211. std::set<uint> GPHIKRawClassifier::getKnownClassNumbers ( ) const
  212. {
  213. if ( ! this->b_isTrained )
  214. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  215. return this->knownClasses;
  216. }
  217. ///////////////////// ///////////////////// /////////////////////
  218. // CLASSIFIER STUFF
  219. ///////////////////// ///////////////////// /////////////////////
  220. void GPHIKRawClassifier::classify ( const NICE::SparseVector * _xstar,
  221. uint & _result,
  222. SparseVector & _scores
  223. ) const
  224. {
  225. if ( ! this->b_isTrained )
  226. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  227. _scores.clear();
  228. // classification with quantization of test inputs
  229. if ( this->q != NULL )
  230. {
  231. uint maxClassNo = 0;
  232. for ( std::map< uint, double * >::const_iterator itT = this->precomputedT.begin() ;
  233. itT != this->precomputedT.end();
  234. itT++
  235. )
  236. {
  237. uint classno = itT->first;
  238. maxClassNo = std::max ( maxClassNo, classno );
  239. double beta = 0;
  240. double *T = itT->second;
  241. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++ )
  242. {
  243. uint dim = i->first;
  244. double v = i->second;
  245. uint qBin = this->q->quantize( v, dim );
  246. beta += T[dim * this->q->getNumberOfBins() + qBin];
  247. }//for-loop over dimensions of test input
  248. _scores[ classno ] = beta;
  249. }//for-loop over 1-vs-all models
  250. }
  251. // classification with exact test inputs, i.e., no quantization involved
  252. else
  253. {
  254. uint maxClassNo = 0;
  255. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  256. {
  257. uint classno = i->first;
  258. maxClassNo = std::max ( maxClassNo, classno );
  259. double beta = 0;
  260. GMHIKernelRaw::sparseVectorElement **dataMatrix = gm->getDataMatrix();
  261. const PrecomputedType & A = i->second;
  262. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  263. const PrecomputedType & B = j->second;
  264. for (SparseVector::const_iterator i = _xstar->begin(); i != _xstar->end(); i++)
  265. {
  266. uint dim = i->first;
  267. double fval = i->second;
  268. uint nnz = this->nnz_per_dimension[dim];
  269. uint nz = this->num_examples - nnz;
  270. if ( nnz == 0 ) continue;
  271. // useful
  272. //if ( fval < this->f_tolerance ) continue;
  273. uint position = 0;
  274. //this->X_sorted.findFirstLargerInDimension(dim, fval, position);
  275. GMHIKernelRaw::sparseVectorElement fval_element;
  276. fval_element.value = fval;
  277. //std::cerr << "value to search for " << fval << endl;
  278. //std::cerr << "data matrix in dimension " << dim << endl;
  279. //for (int j = 0; j < nnz; j++)
  280. // std::cerr << dataMatrix[dim][j].value << std::endl;
  281. GMHIKernelRaw::sparseVectorElement *it = upper_bound ( dataMatrix[dim], dataMatrix[dim] + nnz, fval_element );
  282. position = distance ( dataMatrix[dim], it );
  283. // add zero elements
  284. if ( fval_element.value > 0.0 )
  285. position += nz;
  286. bool posIsZero ( position == 0 );
  287. if ( !posIsZero )
  288. position--;
  289. double firstPart = 0.0;
  290. if ( !posIsZero && ((position-nz) < this->num_examples) )
  291. firstPart = (A[dim][position-nz]);
  292. double secondPart( B[dim][this->num_examples-1-nz]);
  293. if ( !posIsZero && (position >= nz) )
  294. secondPart -= B[dim][position-nz];
  295. // but apply using the transformed one
  296. beta += firstPart + secondPart* fval;
  297. }//for-loop over dimensions of test input
  298. _scores[ classno ] = beta;
  299. }//for-loop over 1-vs-all models
  300. } // if-condition wrt quantization
  301. _scores.setDim ( *this->knownClasses.rbegin() + 1 );
  302. if ( this->knownClasses.size() > 2 )
  303. { // multi-class classification
  304. _result = _scores.maxElement();
  305. }
  306. else if ( this->knownClasses.size() == 2 ) // binary setting
  307. {
  308. uint class1 = *(this->knownClasses.begin());
  309. uint class2 = *(this->knownClasses.rbegin());
  310. uint class_for_which_we_have_a_score = _scores.begin()->first;
  311. uint class_for_which_we_dont_have_a_score = (class1 == class_for_which_we_have_a_score ? class2 : class1);
  312. _scores[class_for_which_we_dont_have_a_score] = - _scores[class_for_which_we_have_a_score];
  313. _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;
  314. }
  315. }
  316. /** training process */
  317. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  318. const NICE::Vector & _labels
  319. )
  320. {
  321. // security-check: examples and labels have to be of same size
  322. if ( _examples.size() != _labels.size() )
  323. {
  324. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  325. }
  326. this->num_examples = _examples.size();
  327. this->knownClasses.clear();
  328. for ( uint i = 0; i < _labels.size(); i++ )
  329. this->knownClasses.insert((uint)_labels[i]);
  330. std::map<uint, NICE::Vector> binLabels;
  331. for ( set<uint>::const_iterator j = knownClasses.begin(); j != knownClasses.end(); j++ )
  332. {
  333. uint current_class = *j;
  334. Vector labels_binary ( _labels.size() );
  335. for ( uint i = 0; i < _labels.size(); i++ )
  336. labels_binary[i] = ( _labels[i] == current_class ) ? 1.0 : -1.0;
  337. binLabels.insert ( pair<uint, NICE::Vector>( current_class, labels_binary) );
  338. }
  339. // handle special binary case
  340. if ( knownClasses.size() == 2 )
  341. {
  342. std::map<uint, NICE::Vector>::iterator it = binLabels.begin();
  343. it++;
  344. binLabels.erase( binLabels.begin(), it );
  345. }
  346. this->train ( _examples, binLabels );
  347. }
  348. void GPHIKRawClassifier::train ( const std::vector< const NICE::SparseVector *> & _examples,
  349. std::map<uint, NICE::Vector> & _binLabels
  350. )
  351. {
  352. // security-check: examples and labels have to be of same size
  353. for ( std::map< uint, NICE::Vector >::const_iterator binLabIt = _binLabels.begin();
  354. binLabIt != _binLabels.end();
  355. binLabIt++
  356. )
  357. {
  358. if ( _examples.size() != binLabIt->second.size() )
  359. {
  360. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  361. }
  362. }
  363. if ( this->b_verbose )
  364. std::cerr << "GPHIKRawClassifier::train" << std::endl;
  365. Timer t;
  366. t.start();
  367. this->clearSetsOfTablesAandB();
  368. this->clearSetsOfTablesT();
  369. // sort examples in each dimension and "transpose" the feature matrix
  370. // set up the GenericMatrix interface
  371. if (gm != NULL)
  372. delete gm;
  373. gm = new GMHIKernelRaw ( _examples, this->d_noise, this->q );
  374. this->nnz_per_dimension = gm->getNNZPerDimension();
  375. this->num_dimension = gm->getNumberOfDimensions();
  376. // compute largest eigenvalue of our kernel matrix
  377. // note: this guy is shared among all categories,
  378. // since the kernel matrix is shared as well
  379. NICE::Vector eigenMax;
  380. NICE::Matrix eigenMaxV;
  381. // for reproducibility during debuggin
  382. srand ( 0 );
  383. srand48 ( 0 );
  384. NICE::EigValues * eig = new EVArnoldi ( false /* verbose flag */,
  385. 10 /*_maxiterations*/
  386. );
  387. eig->getEigenvalues( *gm, eigenMax, eigenMaxV, 1 /*rank*/ );
  388. delete eig;
  389. // set simple jacobi pre-conditioning
  390. NICE::Vector diagonalElements;
  391. gm->getDiagonalElements ( diagonalElements );
  392. solver->setJacobiPreconditioner ( diagonalElements );
  393. // solve linear equations for each class
  394. // be careful when parallising this!
  395. for ( std::map<uint, NICE::Vector>::const_iterator i = _binLabels.begin();
  396. i != _binLabels.end();
  397. i++
  398. )
  399. {
  400. uint classno = i->first;
  401. if (b_verbose)
  402. std::cerr << "Training for class " << classno << endl;
  403. const NICE::Vector & y = i->second;
  404. NICE::Vector alpha;
  405. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  406. * K~ = K + sigma^2 I
  407. *
  408. * K~ \approx lambda_max v v^T
  409. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  410. * => \lambda_max v^T alpha = v^T k_*
  411. * => alpha = k_* / lambda_max could be a good initial start
  412. * If we put everything in the first equation this gives us
  413. * v = k_*
  414. * This reduces the number of iterations by 5 or 8
  415. */
  416. alpha = (y * (1.0 / eigenMax[0]) );
  417. solver->solveLin( *gm, y, alpha );
  418. // get lookup tables, A, B, etc. and store them
  419. gm->updateTablesAandB( alpha );
  420. double **A = gm->getTableA();
  421. double **B = gm->getTableB();
  422. precomputedA.insert ( pair<uint, PrecomputedType> ( classno, A ) );
  423. precomputedB.insert ( pair<uint, PrecomputedType> ( classno, B ) );
  424. // Quantization for classification?
  425. if ( this->q != NULL )
  426. {
  427. gm->updateTableT( alpha );
  428. double *T = gm->getTableT ( );
  429. precomputedT.insert( pair<uint, double * > ( classno, T ) );
  430. }
  431. }
  432. // NOTE if quantization is turned on, we do not need LUTs A and B anymore
  433. if ( this->q != NULL )
  434. {
  435. this->clearSetsOfTablesAandB();
  436. }
  437. t.stop();
  438. if ( this->b_verbose )
  439. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  440. //indicate that we finished training successfully
  441. this->b_isTrained = true;
  442. // clean up all examples ??
  443. if ( this->b_verbose )
  444. std::cerr << "Learning finished" << std::endl;
  445. }