GPHIKClassifier.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /**
  2. * @file GPHIKClassifier.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. // gp-hik-core includes
  13. #include "GPHIKClassifier.h"
  14. using namespace std;
  15. using namespace NICE;
  16. /////////////////////////////////////////////////////
  17. /////////////////////////////////////////////////////
  18. // PROTECTED METHODS
  19. /////////////////////////////////////////////////////
  20. /////////////////////////////////////////////////////
  21. /////////////////////////////////////////////////////
  22. /////////////////////////////////////////////////////
  23. // PUBLIC METHODS
  24. /////////////////////////////////////////////////////
  25. /////////////////////////////////////////////////////
  26. GPHIKClassifier::GPHIKClassifier( )
  27. {
  28. this->b_isTrained = false;
  29. this->confSection = "";
  30. this->gphyper = new NICE::FMKGPHyperparameterOptimization();
  31. // in order to be sure about all necessary variables be setup with default values, we
  32. // run initFromConfig with an empty config
  33. NICE::Config tmpConfEmpty ;
  34. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  35. }
  36. GPHIKClassifier::GPHIKClassifier( const Config *conf, const string & s_confSection )
  37. {
  38. ///////////
  39. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  40. ///////////
  41. this->b_isTrained = false;
  42. this->confSection = "";
  43. this->gphyper = new NICE::FMKGPHyperparameterOptimization();
  44. ///////////
  45. // here comes the new code part different from the empty constructor
  46. ///////////
  47. this->confSection = s_confSection;
  48. // if no config file was given, we either restore the classifier from an external file, or run ::init with
  49. // an emtpy config (using default values thereby) when calling the train-method
  50. if ( conf != NULL )
  51. {
  52. this->initFromConfig( conf, confSection );
  53. }
  54. else
  55. {
  56. // if no config was given, we create an empty one
  57. NICE::Config tmpConfEmpty ;
  58. this->initFromConfig ( &tmpConfEmpty, this->confSection );
  59. }
  60. }
  61. GPHIKClassifier::~GPHIKClassifier()
  62. {
  63. if ( gphyper != NULL )
  64. delete gphyper;
  65. }
  66. void GPHIKClassifier::initFromConfig(const Config *conf, const string & s_confSection)
  67. {
  68. this->noise = conf->gD(confSection, "noise", 0.01);
  69. this->confSection = confSection;
  70. this->verbose = conf->gB(confSection, "verbose", false);
  71. this->debug = conf->gB(confSection, "debug", false);
  72. this->uncertaintyPredictionForClassification = conf->gB( confSection, "uncertaintyPredictionForClassification", false );
  73. //how do we approximate the predictive variance for classification uncertainty?
  74. string s_varianceApproximation = conf->gS(confSection, "varianceApproximation", "approximate_fine"); //default: fine approximative uncertainty prediction
  75. if ( (s_varianceApproximation.compare("approximate_rough") == 0) || ((s_varianceApproximation.compare("1") == 0)) )
  76. {
  77. this->varianceApproximation = APPROXIMATE_ROUGH;
  78. //no additional eigenvalue is needed here at all.
  79. this->gphyper->setNrOfEigenvaluesToConsiderForVarApprox ( 0 );
  80. }
  81. else if ( (s_varianceApproximation.compare("approximate_fine") == 0) || ((s_varianceApproximation.compare("2") == 0)) )
  82. {
  83. this->varianceApproximation = APPROXIMATE_FINE;
  84. //security check - compute at least one eigenvalue for this approximation strategy
  85. this->gphyper->setNrOfEigenvaluesToConsiderForVarApprox ( std::max( conf->gI(confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 ), 1) );
  86. }
  87. else if ( (s_varianceApproximation.compare("exact") == 0) || ((s_varianceApproximation.compare("3") == 0)) )
  88. {
  89. this->varianceApproximation = EXACT;
  90. //no additional eigenvalue is needed here at all.
  91. this->gphyper->setNrOfEigenvaluesToConsiderForVarApprox ( 0 );
  92. }
  93. else
  94. {
  95. this->varianceApproximation = NONE;
  96. //no additional eigenvalue is needed here at all.
  97. this->gphyper->setNrOfEigenvaluesToConsiderForVarApprox ( 0 );
  98. }
  99. if ( this->verbose )
  100. std::cerr << "varianceApproximationStrategy: " << s_varianceApproximation << std::endl;
  101. //NOTE init all member pointer variables here as well
  102. this->gphyper->initFromConfig ( conf, confSection /*possibly delete the handing of confSection*/);
  103. }
  104. ///////////////////// ///////////////////// /////////////////////
  105. // GET / SET
  106. ///////////////////// ///////////////////// /////////////////////
  107. std::set<int> GPHIKClassifier::getKnownClassNumbers ( ) const
  108. {
  109. if ( ! this->b_isTrained )
  110. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  111. return gphyper->getKnownClassNumbers();
  112. }
  113. ///////////////////// ///////////////////// /////////////////////
  114. // CLASSIFIER STUFF
  115. ///////////////////// ///////////////////// /////////////////////
  116. void GPHIKClassifier::classify ( const SparseVector * example, int & result, SparseVector & scores ) const
  117. {
  118. double tmpUncertainty;
  119. this->classify( example, result, scores, tmpUncertainty );
  120. }
  121. void GPHIKClassifier::classify ( const NICE::Vector * example, int & result, SparseVector & scores ) const
  122. {
  123. double tmpUncertainty;
  124. this->classify( example, result, scores, tmpUncertainty );
  125. }
  126. void GPHIKClassifier::classify ( const SparseVector * example, int & result, SparseVector & scores, double & uncertainty ) const
  127. {
  128. if ( ! this->b_isTrained )
  129. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  130. scores.clear();
  131. result = gphyper->classify ( *example, scores );
  132. if ( scores.size() == 0 ) {
  133. fthrow(Exception, "Zero scores, something is likely to be wrong here: svec.size() = " << example->size() );
  134. }
  135. if (uncertaintyPredictionForClassification)
  136. {
  137. if (varianceApproximation != NONE)
  138. {
  139. this->predictUncertainty( example, uncertainty );
  140. }
  141. else
  142. {
  143. //do nothing
  144. uncertainty = std::numeric_limits<double>::max();
  145. }
  146. }
  147. else
  148. {
  149. //do nothing
  150. uncertainty = std::numeric_limits<double>::max();
  151. }
  152. }
  153. void GPHIKClassifier::classify ( const NICE::Vector * example, int & result, SparseVector & scores, double & uncertainty ) const
  154. {
  155. if ( ! this->b_isTrained )
  156. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  157. scores.clear();
  158. result = gphyper->classify ( *example, scores );
  159. if ( scores.size() == 0 ) {
  160. fthrow(Exception, "Zero scores, something is likely to be wrong here: svec.size() = " << example->size() );
  161. }
  162. if (uncertaintyPredictionForClassification)
  163. {
  164. if (varianceApproximation != NONE)
  165. {
  166. this->predictUncertainty( example, uncertainty );
  167. }
  168. else
  169. {
  170. //do nothing
  171. uncertainty = std::numeric_limits<double>::max();
  172. }
  173. }
  174. else
  175. {
  176. //do nothing
  177. uncertainty = std::numeric_limits<double>::max();
  178. }
  179. }
  180. /** training process */
  181. void GPHIKClassifier::train ( const std::vector< const NICE::SparseVector *> & examples, const NICE::Vector & labels )
  182. {
  183. // security-check: examples and labels have to be of same size
  184. if ( examples.size() != labels.size() )
  185. {
  186. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  187. }
  188. if (verbose)
  189. {
  190. std::cerr << "GPHIKClassifier::train" << std::endl;
  191. }
  192. Timer t;
  193. t.start();
  194. FastMinKernel *fmk = new FastMinKernel ( examples, noise, this->debug );
  195. gphyper->setFastMinKernel ( fmk );
  196. t.stop();
  197. if (verbose)
  198. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  199. if (verbose)
  200. cerr << "Learning ..." << endl;
  201. // go go go
  202. gphyper->optimize ( labels );
  203. if (verbose)
  204. std::cerr << "optimization done" << std::endl;
  205. if ( ( varianceApproximation != NONE ) )
  206. {
  207. switch (varianceApproximation)
  208. {
  209. case APPROXIMATE_ROUGH:
  210. {
  211. gphyper->prepareVarianceApproximationRough();
  212. break;
  213. }
  214. case APPROXIMATE_FINE:
  215. {
  216. gphyper->prepareVarianceApproximationFine();
  217. break;
  218. }
  219. case EXACT:
  220. {
  221. //nothing to prepare
  222. break;
  223. }
  224. default:
  225. {
  226. //nothing to prepare
  227. }
  228. }
  229. }
  230. //indicate that we finished training successfully
  231. this->b_isTrained = true;
  232. // clean up all examples ??
  233. if (verbose)
  234. std::cerr << "Learning finished" << std::endl;
  235. }
  236. /** training process */
  237. void GPHIKClassifier::train ( const std::vector< const NICE::SparseVector *> & examples, std::map<int, NICE::Vector> & binLabels )
  238. {
  239. // security-check: examples and labels have to be of same size
  240. for ( std::map< int, NICE::Vector >::const_iterator binLabIt = binLabels.begin();
  241. binLabIt != binLabels.end();
  242. binLabIt++
  243. )
  244. {
  245. if ( examples.size() != binLabIt->second.size() )
  246. {
  247. fthrow(Exception, "Given examples do not match label vector in size -- aborting!" );
  248. }
  249. }
  250. if (verbose)
  251. std::cerr << "GPHIKClassifier::train" << std::endl;
  252. Timer t;
  253. t.start();
  254. FastMinKernel *fmk = new FastMinKernel ( examples, noise, this->debug );
  255. gphyper->setFastMinKernel ( fmk );
  256. t.stop();
  257. if (verbose)
  258. std::cerr << "Time used for setting up the fmk object: " << t.getLast() << std::endl;
  259. if (verbose)
  260. cerr << "Learning ..." << endl;
  261. // go go go
  262. gphyper->optimize ( binLabels );
  263. if (verbose)
  264. std::cerr << "optimization done, now prepare for the uncertainty prediction" << std::endl;
  265. if ( ( varianceApproximation != NONE ) )
  266. {
  267. switch (varianceApproximation)
  268. {
  269. case APPROXIMATE_ROUGH:
  270. {
  271. gphyper->prepareVarianceApproximationRough();
  272. break;
  273. }
  274. case APPROXIMATE_FINE:
  275. {
  276. gphyper->prepareVarianceApproximationFine();
  277. break;
  278. }
  279. case EXACT:
  280. {
  281. //nothing to prepare
  282. break;
  283. }
  284. default:
  285. {
  286. //nothing to prepare
  287. }
  288. }
  289. }
  290. //indicate that we finished training successfully
  291. this->b_isTrained = true;
  292. // clean up all examples ??
  293. if (verbose)
  294. std::cerr << "Learning finished" << std::endl;
  295. }
  296. GPHIKClassifier *GPHIKClassifier::clone () const
  297. {
  298. fthrow(Exception, "GPHIKClassifier: clone() not yet implemented" );
  299. return NULL;
  300. }
  301. void GPHIKClassifier::predictUncertainty( const NICE::SparseVector * example, double & uncertainty ) const
  302. {
  303. if (gphyper == NULL)
  304. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  305. //we directly store the predictive variances in the vector, that contains the classification uncertainties lateron to save storage
  306. switch (varianceApproximation)
  307. {
  308. case APPROXIMATE_ROUGH:
  309. {
  310. gphyper->computePredictiveVarianceApproximateRough( *example, uncertainty );
  311. break;
  312. }
  313. case APPROXIMATE_FINE:
  314. {
  315. gphyper->computePredictiveVarianceApproximateFine( *example, uncertainty );
  316. break;
  317. }
  318. case EXACT:
  319. {
  320. gphyper->computePredictiveVarianceExact( *example, uncertainty );
  321. break;
  322. }
  323. default:
  324. {
  325. fthrow(Exception, "GPHIKClassifier - your settings disabled the variance approximation needed for uncertainty prediction.");
  326. }
  327. }
  328. }
  329. void GPHIKClassifier::predictUncertainty( const NICE::Vector * example, double & uncertainty ) const
  330. {
  331. if (gphyper == NULL)
  332. fthrow(Exception, "Classifier not trained yet -- aborting!" );
  333. //we directly store the predictive variances in the vector, that contains the classification uncertainties lateron to save storage
  334. switch (varianceApproximation)
  335. {
  336. case APPROXIMATE_ROUGH:
  337. {
  338. gphyper->computePredictiveVarianceApproximateRough( *example, uncertainty );
  339. break;
  340. }
  341. case APPROXIMATE_FINE:
  342. {
  343. gphyper->computePredictiveVarianceApproximateFine( *example, uncertainty );
  344. break;
  345. }
  346. case EXACT:
  347. {
  348. gphyper->computePredictiveVarianceExact( *example, uncertainty );
  349. break;
  350. }
  351. default:
  352. {
  353. fthrow(Exception, "GPHIKClassifier - your settings disabled the variance approximation needed for uncertainty prediction.");
  354. }
  355. }
  356. }
  357. ///////////////////// INTERFACE PERSISTENT /////////////////////
  358. // interface specific methods for store and restore
  359. ///////////////////// INTERFACE PERSISTENT /////////////////////
  360. void GPHIKClassifier::restore ( std::istream & is, int format )
  361. {
  362. //delete everything we knew so far...
  363. this->clear();
  364. bool b_restoreVerbose ( false );
  365. #ifdef B_RESTOREVERBOSE
  366. b_restoreVerbose = true;
  367. #endif
  368. if ( is.good() )
  369. {
  370. if ( b_restoreVerbose )
  371. std::cerr << " restore GPHIKClassifier" << std::endl;
  372. std::string tmp;
  373. is >> tmp; //class name
  374. if ( ! this->isStartTag( tmp, "GPHIKClassifier" ) )
  375. {
  376. std::cerr << " WARNING - attempt to restore GPHIKClassifier, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  377. throw;
  378. }
  379. if (gphyper != NULL)
  380. {
  381. delete gphyper;
  382. gphyper = NULL;
  383. }
  384. is.precision (numeric_limits<double>::digits10 + 1);
  385. bool b_endOfBlock ( false ) ;
  386. while ( !b_endOfBlock )
  387. {
  388. is >> tmp; // start of block
  389. if ( this->isEndTag( tmp, "GPHIKClassifier" ) )
  390. {
  391. b_endOfBlock = true;
  392. continue;
  393. }
  394. tmp = this->removeStartTag ( tmp );
  395. if ( b_restoreVerbose )
  396. std::cerr << " currently restore section " << tmp << " in GPHIKClassifier" << std::endl;
  397. if ( tmp.compare("confSection") == 0 )
  398. {
  399. is >> confSection;
  400. is >> tmp; // end of block
  401. tmp = this->removeEndTag ( tmp );
  402. }
  403. else if ( tmp.compare("gphyper") == 0 )
  404. {
  405. if ( gphyper == NULL )
  406. gphyper = new NICE::FMKGPHyperparameterOptimization();
  407. //then, load everything that we stored explicitely,
  408. // including precomputed matrices, LUTs, eigenvalues, ... and all that stuff
  409. gphyper->restore(is, format);
  410. is >> tmp; // end of block
  411. tmp = this->removeEndTag ( tmp );
  412. }
  413. else if ( tmp.compare("b_isTrained") == 0 )
  414. {
  415. is >> b_isTrained;
  416. is >> tmp; // end of block
  417. tmp = this->removeEndTag ( tmp );
  418. }
  419. else if ( tmp.compare("noise") == 0 )
  420. {
  421. is >> noise;
  422. is >> tmp; // end of block
  423. tmp = this->removeEndTag ( tmp );
  424. }
  425. else if ( tmp.compare("verbose") == 0 )
  426. {
  427. is >> verbose;
  428. is >> tmp; // end of block
  429. tmp = this->removeEndTag ( tmp );
  430. }
  431. else if ( tmp.compare("debug") == 0 )
  432. {
  433. is >> debug;
  434. is >> tmp; // end of block
  435. tmp = this->removeEndTag ( tmp );
  436. }
  437. else if ( tmp.compare("uncertaintyPredictionForClassification") == 0 )
  438. {
  439. is >> uncertaintyPredictionForClassification;
  440. is >> tmp; // end of block
  441. tmp = this->removeEndTag ( tmp );
  442. }
  443. else if ( tmp.compare("varianceApproximation") == 0 )
  444. {
  445. unsigned int ui_varianceApproximation;
  446. is >> ui_varianceApproximation;
  447. varianceApproximation = static_cast<VarianceApproximation> ( ui_varianceApproximation );
  448. is >> tmp; // end of block
  449. tmp = this->removeEndTag ( tmp );
  450. }
  451. else
  452. {
  453. std::cerr << "WARNING -- unexpected GPHIKClassifier object -- " << tmp << " -- for restoration... aborting" << std::endl;
  454. throw;
  455. }
  456. }
  457. }
  458. else
  459. {
  460. std::cerr << "GPHIKClassifier::restore -- InStream not initialized - restoring not possible!" << std::endl;
  461. throw;
  462. }
  463. }
  464. void GPHIKClassifier::store ( std::ostream & os, int format ) const
  465. {
  466. if (os.good())
  467. {
  468. // show starting point
  469. os << this->createStartTag( "GPHIKClassifier" ) << std::endl;
  470. os.precision (numeric_limits<double>::digits10 + 1);
  471. os << this->createStartTag( "confSection" ) << std::endl;
  472. os << confSection << std::endl;
  473. os << this->createEndTag( "confSection" ) << std::endl;
  474. os << this->createStartTag( "gphyper" ) << std::endl;
  475. //store the underlying data
  476. //will be done in gphyper->store(of,format)
  477. //store the optimized parameter values and all that stuff
  478. gphyper->store(os, format);
  479. os << this->createEndTag( "gphyper" ) << std::endl;
  480. /////////////////////////////////////////////////////////
  481. // store variables which we previously set via config
  482. /////////////////////////////////////////////////////////
  483. os << this->createStartTag( "b_isTrained" ) << std::endl;
  484. os << b_isTrained << std::endl;
  485. os << this->createEndTag( "b_isTrained" ) << std::endl;
  486. os << this->createStartTag( "noise" ) << std::endl;
  487. os << noise << std::endl;
  488. os << this->createEndTag( "noise" ) << std::endl;
  489. os << this->createStartTag( "verbose" ) << std::endl;
  490. os << verbose << std::endl;
  491. os << this->createEndTag( "verbose" ) << std::endl;
  492. os << this->createStartTag( "debug" ) << std::endl;
  493. os << debug << std::endl;
  494. os << this->createEndTag( "debug" ) << std::endl;
  495. os << this->createStartTag( "uncertaintyPredictionForClassification" ) << std::endl;
  496. os << uncertaintyPredictionForClassification << std::endl;
  497. os << this->createEndTag( "uncertaintyPredictionForClassification" ) << std::endl;
  498. os << this->createStartTag( "varianceApproximation" ) << std::endl;
  499. os << varianceApproximation << std::endl;
  500. os << this->createEndTag( "varianceApproximation" ) << std::endl;
  501. // done
  502. os << this->createEndTag( "GPHIKClassifier" ) << std::endl;
  503. }
  504. else
  505. {
  506. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  507. }
  508. }
  509. void GPHIKClassifier::clear ()
  510. {
  511. if ( gphyper != NULL )
  512. {
  513. delete gphyper;
  514. gphyper = NULL;
  515. }
  516. }
  517. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  518. // interface specific methods for incremental extensions
  519. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  520. void GPHIKClassifier::addExample( const NICE::SparseVector * example,
  521. const double & label,
  522. const bool & performOptimizationAfterIncrement
  523. )
  524. {
  525. if ( ! this->b_isTrained )
  526. {
  527. //call train method instead
  528. std::cerr << "Classifier not initially trained yet -- run initial training instead of incremental extension!" << std::endl;
  529. std::vector< const NICE::SparseVector *> examplesVec;
  530. examplesVec.push_back ( example );
  531. NICE::Vector labelsVec ( 1 , label );
  532. this->train ( examplesVec, labelsVec );
  533. }
  534. else
  535. {
  536. this->gphyper->addExample( example, label, performOptimizationAfterIncrement );
  537. }
  538. }
  539. void GPHIKClassifier::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  540. const NICE::Vector & newLabels,
  541. const bool & performOptimizationAfterIncrement
  542. )
  543. {
  544. //are new examples available? If not, nothing has to be done
  545. if ( newExamples.size() < 1)
  546. return;
  547. if ( ! this->b_isTrained )
  548. {
  549. //call train method instead
  550. std::cerr << "Classifier not initially trained yet -- run initial training instead of incremental extension!" << std::endl;
  551. this->train ( newExamples, newLabels );
  552. }
  553. else
  554. {
  555. this->gphyper->addMultipleExamples( newExamples, newLabels, performOptimizationAfterIncrement );
  556. }
  557. }