GPHIKClassifier.cpp 19 KB

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