FMKGPHyperparameterOptimization.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190
  1. /**
  2. * @file FMKGPHyperparameterOptimization.cpp
  3. * @brief Heart of the framework to set up everything, perform optimization, classification, and variance prediction (Implementation)
  4. * @author Erik Rodner, Alexander Freytag
  5. * @date 01/02/2012
  6. */
  7. // STL includes
  8. #include <iostream>
  9. #include <map>
  10. // NICE-core includes
  11. #include <core/algebra/ILSConjugateGradients.h>
  12. #include <core/algebra/ILSConjugateGradientsLanczos.h>
  13. #include <core/algebra/ILSSymmLqLanczos.h>
  14. #include <core/algebra/ILSMinResLanczos.h>
  15. #include <core/algebra/ILSPlainGradient.h>
  16. #include <core/algebra/EigValuesTRLAN.h>
  17. #include <core/algebra/CholeskyRobust.h>
  18. //
  19. #include <core/basics/Timer.h>
  20. #include <core/basics/ResourceStatistics.h>
  21. #include <core/basics/Exception.h>
  22. //
  23. #include <core/vector/Algorithms.h>
  24. #include <core/vector/Eigen.h>
  25. //
  26. #include <core/optimization/blackbox/DownhillSimplexOptimizer.h>
  27. // gp-hik-core includes
  28. #include "FMKGPHyperparameterOptimization.h"
  29. #include "FastMinKernel.h"
  30. #include "GMHIKernel.h"
  31. #include "IKMNoise.h"
  32. using namespace NICE;
  33. using namespace std;
  34. /////////////////////////////////////////////////////
  35. /////////////////////////////////////////////////////
  36. // PROTECTED METHODS
  37. /////////////////////////////////////////////////////
  38. /////////////////////////////////////////////////////
  39. void FMKGPHyperparameterOptimization::updateAfterSingleIncrement (
  40. const NICE::SparseVector & x,
  41. const std::set < int > newClasses,
  42. const bool & performOptimizationAfterIncrement )
  43. {
  44. NICE::Timer t;
  45. t.start();
  46. if ( this->fmk == NULL )
  47. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  48. std::map<int, NICE::Vector> binaryLabels;
  49. std::set<int> classesToUse;
  50. //TODO this could be made faster when storing the previous binary label vectors...
  51. this->prepareBinaryLabels ( binaryLabels, this->labels , classesToUse );
  52. if ( this->verbose )
  53. std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
  54. NICE::Timer t1;
  55. NICE::GPLikelihoodApprox * gplike;
  56. uint parameterVectorSize;
  57. std::cerr << "setup GPLikelihoodApprox object " << std::endl;
  58. t1.start();
  59. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  60. t1.stop();
  61. if ( this->verboseTime )
  62. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  63. std::cerr << "setup previous alpha guess " << std::endl;
  64. t1.start();
  65. if ( this->b_usePreviousAlphas )
  66. {
  67. //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
  68. //default in GPLikelihoodApprox for the first time:
  69. // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
  70. double factor ( 1.0 / this->eigenMax[0] );
  71. std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
  72. for ( std::map<int, NICE::Vector>::iterator lastAlphaIt = lastAlphas.begin() ;lastAlphaIt != lastAlphas.end(); lastAlphaIt++ )
  73. {
  74. int oldSize ( lastAlphaIt->second.size() );
  75. lastAlphaIt->second.resize ( oldSize + 1 );
  76. if ( binaryLabelsIt->second[oldSize] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
  77. lastAlphaIt->second[oldSize] = factor;
  78. else
  79. lastAlphaIt->second[oldSize] = -factor; //we follow the initialization as done in previous steps
  80. //lastAlphaIt->second[oldSize] = 0.0; // following the suggestion of Yeh and Darrell
  81. binaryLabelsIt++;
  82. }
  83. //compute unaffected alpha-vectors for the new classes
  84. for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
  85. {
  86. NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
  87. lastAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
  88. }
  89. gplike->setInitialAlphaGuess ( &lastAlphas );
  90. }
  91. else
  92. {
  93. //if we do not use previous alphas, we do not have to set up anything here
  94. }
  95. t1.stop();
  96. if ( this->verboseTime )
  97. std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
  98. std::cerr << "update Eigendecomposition " << std::endl;
  99. t1.start();
  100. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  101. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  102. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  103. t1.stop();
  104. if ( this->verboseTime )
  105. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  106. if ( this->verbose )
  107. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  108. // we can reuse the already given performOptimization-method:
  109. // OPT_GREEDY
  110. // for this strategy we can't reuse any of the previously computed scores
  111. // so come on, let's do the whole thing again...
  112. // OPT_DOWNHILLSIMPLEX
  113. // Here we can benefit from previous results, when we use them as initialization for our optimizer
  114. // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
  115. // as initialization
  116. // OPT_NONE
  117. // nothing to do, obviously
  118. //NOTE we could skip this, if we do not want to change our parameters given new examples
  119. if ( this->verbose )
  120. std::cerr << "perform optimization after increment " << std::endl;
  121. int optimizationMethodTmpCopy;
  122. if ( !performOptimizationAfterIncrement )
  123. {
  124. // if no optimization shall be carried out, we simply set the optimization method to NONE but run the optimization
  125. // call nonetheless, thereby computing alpha vectors, etc. which would be not initialized
  126. optimizationMethodTmpCopy = this->optimizationMethod;
  127. this->optimizationMethod = OPT_NONE;
  128. }
  129. t1.start();
  130. //TODO add option for handing over previous solution!
  131. this->performOptimization ( *gplike, parameterVectorSize);
  132. // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
  133. t1.stop();
  134. if ( this->verboseTime )
  135. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  136. if ( this->verbose )
  137. std::cerr << "Preparing after retraining for classification ..." << std::endl;
  138. t1.start();
  139. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  140. t1.stop();
  141. if ( this->verboseTime)
  142. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  143. if ( !performOptimizationAfterIncrement )
  144. {
  145. this->optimizationMethod = optimizationMethodTmpCopy;
  146. }
  147. //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
  148. // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
  149. // Since we are not aware of any such method, we have to compute them completely new
  150. // :/
  151. t1.start();
  152. this->computeMatricesAndLUTs ( *gplike );
  153. t1.stop();
  154. if ( this->verboseTime )
  155. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  156. t.stop();
  157. NICE::ResourceStatistics rs;
  158. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  159. long maxMemory;
  160. rs.getMaximumMemory ( maxMemory );
  161. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  162. //don't waste memory
  163. delete gplike;
  164. }
  165. void FMKGPHyperparameterOptimization::updateAfterMultipleIncrements (
  166. const std::vector<const NICE::SparseVector*> & x,
  167. const std::set < int > newClasses,
  168. const bool & performOptimizationAfterIncrement )
  169. {
  170. Timer t;
  171. t.start();
  172. if ( fmk == NULL )
  173. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  174. std::map<int, NICE::Vector> binaryLabels;
  175. std::set<int> classesToUse;
  176. this->prepareBinaryLabels ( binaryLabels, labels , classesToUse );
  177. //actually, this is not needed, since we have the global set knownClasses
  178. classesToUse.clear();
  179. std::map<int, NICE::Vector> newBinaryLabels;
  180. if ( newClasses.size() > 0)
  181. {
  182. for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
  183. {
  184. std::map<int, NICE::Vector>::iterator binLabelIt = binaryLabels.find(*newClIt);
  185. newBinaryLabels.insert(*binLabelIt);
  186. }
  187. }
  188. if ( this->verbose )
  189. std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
  190. // ************************************************************
  191. // include the information for classes we know so far
  192. // ************************************************************
  193. if ( this->verbose)
  194. std::cerr << "include the information for classes we know so far " << std::endl;
  195. NICE::Timer t1;
  196. t1.start();
  197. //update the kernel combinations
  198. //TODO verify that this is not needed anymore in any IKMLinearCombination class
  199. //we have to reset the fmk explicitely
  200. ( ( GMHIKernel* ) this->ikmsum->getModel ( this->ikmsum->getNumberOfModels() - 1 ) )->setFastMinKernel ( this->fmk );
  201. t1.stop();
  202. if ( this->verboseTime )
  203. std::cerr << "Time used for setting up the ikm-objects for known classes: " << t1.getLast() << std::endl;
  204. // *********************************************
  205. // work on the new classes
  206. // *********************************************
  207. if ( this->verbose )
  208. std::cerr << "work on the new classes " << std::endl;
  209. double tmpNoise;
  210. (this->ikmsum->getModel( 0 ))->getFirstDiagonalElement(tmpNoise);
  211. // ******************************************************************************************
  212. // now do everything which is independent of the number of new classes
  213. // ******************************************************************************************
  214. if ( this->verbose )
  215. std::cerr << "now do everything which is independent of the number of new classes" << std::endl;
  216. NICE::GPLikelihoodApprox * gplike;
  217. uint parameterVectorSize;
  218. t1.start();
  219. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  220. t1.stop();
  221. if ( this->verboseTime )
  222. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  223. t1.start();
  224. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  225. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  226. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  227. t1.stop();
  228. if ( this->verboseTime )
  229. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  230. t1.start();
  231. if ( this->b_usePreviousAlphas )
  232. {
  233. double factor ( 1.0 / this->eigenMax[0] );
  234. std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
  235. for ( std::map<int, NICE::Vector>::iterator lastAlphaIt = lastAlphas.begin() ;lastAlphaIt != lastAlphas.end(); lastAlphaIt++ )
  236. {
  237. int oldSize ( lastAlphaIt->second.size() );
  238. lastAlphaIt->second.resize ( oldSize + x.size() );
  239. //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
  240. //default in GPLikelihoodApprox for the first time:
  241. // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
  242. for ( uint i = 0; i < x.size(); i++ )
  243. {
  244. if ( binaryLabelsIt->second[oldSize+i] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
  245. lastAlphaIt->second[oldSize+i] = factor;
  246. else
  247. lastAlphaIt->second[oldSize+i] = -factor; //we follow the initialization as done in previous steps
  248. //lastAlphaIt->second[oldSize+i] = 0.0; // following the suggestion of Yeh and Darrell
  249. }
  250. binaryLabelsIt++;
  251. }
  252. //compute unaffected alpha-vectors for the new classes
  253. for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
  254. {
  255. NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
  256. lastAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
  257. }
  258. //TODO check that memory will not be erased when calling delete!
  259. gplike->setInitialAlphaGuess ( &lastAlphas );
  260. }
  261. else
  262. {
  263. }
  264. //if we do not use previous alphas, we do not have to set up anything here
  265. t1.stop();
  266. if ( this->verboseTime )
  267. std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
  268. if ( this->verbose )
  269. std::cerr << "resulting eigenvalues of first class: " << eigenMax[0] << std::endl;
  270. // we can reuse the already given performOptimization-method:
  271. // OPT_GREEDY
  272. // for this strategy we can't reuse any of the previously computed scores
  273. // so come on, let's do the whole thing again...
  274. // OPT_DOWNHILLSIMPLEX
  275. // Here we can benefit from previous results, when we use them as initialization for our optimizer
  276. // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
  277. // as initialization
  278. // OPT_NONE
  279. // nothing to do, obviously
  280. //NOTE we can skip this, if we do not want to change our parameters given new examples
  281. if ( performOptimizationAfterIncrement )
  282. {
  283. t1.start();
  284. //TODO add option for handing over previous solution!
  285. this->performOptimization ( *gplike, parameterVectorSize);
  286. // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
  287. t1.stop();
  288. if ( this->verboseTime )
  289. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  290. t1.start();
  291. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  292. t1.stop();
  293. if ( this->verboseTime)
  294. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  295. }
  296. else
  297. {
  298. //deactivate the optimization method;
  299. int originalOptimizationMethod = optimizationMethod;
  300. this->optimizationMethod = OPT_NONE;
  301. //and deactive the noise-optimization as well
  302. if ( this->optimizeNoise )
  303. this->optimizeNoise = false;
  304. t1.start();
  305. //this is needed to compute the alpha vectors for the standard parameter settings
  306. //TODO add option for handing over previous solution!
  307. this->performOptimization ( *gplike, parameterVectorSize);
  308. // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
  309. t1.stop();
  310. std::cerr << "skip optimization after increment" << std::endl;
  311. if ( this->verboseTime )
  312. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  313. std::cerr << "skip feature transformation" << std::endl;
  314. if ( this->verboseTime )
  315. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  316. //re-activate the optimization method
  317. this->optimizationMethod = originalOptimizationMethod;
  318. }
  319. if ( this->verbose )
  320. std::cerr << "Preparing after retraining for classification ..." << std::endl;
  321. //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
  322. // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
  323. // Since we are not aware of any such method, we have to compute them completely new
  324. // :/
  325. t1.start();
  326. this->computeMatricesAndLUTs ( *gplike );
  327. t1.stop();
  328. if ( this->verboseTime )
  329. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  330. t.stop();
  331. NICE::ResourceStatistics rs;
  332. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  333. long maxMemory;
  334. rs.getMaximumMemory ( maxMemory );
  335. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  336. //don't waste memory
  337. delete gplike;
  338. }
  339. /////////////////////////////////////////////////////
  340. /////////////////////////////////////////////////////
  341. // PUBLIC METHODS
  342. /////////////////////////////////////////////////////
  343. /////////////////////////////////////////////////////
  344. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization()
  345. {
  346. // initialize pointer variables
  347. pf = NULL;
  348. eig = NULL;
  349. linsolver = NULL;
  350. fmk = NULL;
  351. q = NULL;
  352. precomputedTForVarEst = NULL;
  353. ikmsum = NULL;
  354. // initialize boolean flags
  355. verbose = false;
  356. verboseTime = false;
  357. debug = false;
  358. //stupid unneeded default values
  359. binaryLabelPositive = -1;
  360. binaryLabelNegative = -2;
  361. this->b_usePreviousAlphas = false;
  362. }
  363. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const string & _confSection )
  364. {
  365. // initialize pointer variables
  366. pf = NULL;
  367. eig = NULL;
  368. linsolver = NULL;
  369. fmk = NULL;
  370. q = NULL;
  371. precomputedTForVarEst = NULL;
  372. ikmsum = NULL;
  373. //stupid unneeded default values
  374. binaryLabelPositive = -1;
  375. binaryLabelNegative = -2;
  376. knownClasses.clear();
  377. //TODO
  378. if ( _fmk == NULL )
  379. this->initialize ( _conf, _pf ); //then the confSection is also the default value
  380. else
  381. this->initialize ( _conf, _pf, _fmk, _confSection );
  382. }
  383. FMKGPHyperparameterOptimization::~FMKGPHyperparameterOptimization()
  384. {
  385. //pf will delete from outer program
  386. if ( this->eig != NULL )
  387. delete this->eig;
  388. if ( this->linsolver != NULL )
  389. delete this->linsolver;
  390. if ( this->fmk != NULL )
  391. delete this->fmk;
  392. if ( this->q != NULL )
  393. delete this->q;
  394. for ( uint i = 0 ; i < precomputedT.size(); i++ )
  395. delete [] ( precomputedT[i] );
  396. if ( precomputedTForVarEst != NULL )
  397. delete precomputedTForVarEst;
  398. if ( ikmsum != NULL )
  399. delete ikmsum;
  400. }
  401. void FMKGPHyperparameterOptimization::initialize ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const std::string & _confSection )
  402. {
  403. if ( _fmk != NULL )
  404. {
  405. if ( this->fmk != NULL )
  406. {
  407. delete this->fmk;
  408. fmk = NULL;
  409. }
  410. this->fmk = _fmk;
  411. }
  412. this->pf = _pf;
  413. this->verbose = _conf->gB ( _confSection, "verbose", false );
  414. this->verboseTime = _conf->gB ( _confSection, "verboseTime", false );
  415. this->debug = _conf->gB ( _confSection, "debug", false );
  416. if ( verbose )
  417. {
  418. std::cerr << "------------" << std::endl;
  419. std::cerr << "| set-up |" << std::endl;
  420. std::cerr << "------------" << std::endl;
  421. }
  422. this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */, 10 );
  423. // this->eig = new EigValuesTRLAN();
  424. // My time measurements show that both methods use equal time, a comparision
  425. // of their numerical performance has not been done yet
  426. this->parameterUpperBound = _conf->gD ( _confSection, "parameter_upper_bound", 2.5 );
  427. this->parameterLowerBound = _conf->gD ( _confSection, "parameter_lower_bound", 1.0 );
  428. this->parameterStepSize = _conf->gD ( _confSection, "parameter_step_size", 0.1 );
  429. this->verifyApproximation = _conf->gB ( _confSection, "verify_approximation", false );
  430. this->nrOfEigenvaluesToConsider = _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 );
  431. this->nrOfEigenvaluesToConsiderForVarApprox = _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 );
  432. bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
  433. if ( verbose )
  434. {
  435. std::cerr << "_confSection: " << _confSection << std::endl;
  436. std::cerr << "use_quantization: " << useQuantization << std::endl;
  437. }
  438. if ( _conf->gB ( _confSection, "use_quantization", false ) ) {
  439. int numBins = _conf->gI ( _confSection, "num_bins", 100 );
  440. if ( verbose )
  441. std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
  442. this->q = new Quantization ( numBins );
  443. } else {
  444. this->q = NULL;
  445. }
  446. bool ils_verbose = _conf->gB ( _confSection, "ils_verbose", false );
  447. ils_max_iterations = _conf->gI ( _confSection, "ils_max_iterations", 1000 );
  448. if ( verbose )
  449. std::cerr << "FMKGPHyperparameterOptimization: maximum number of iterations is " << ils_max_iterations << std::endl;
  450. double ils_min_delta = _conf->gD ( _confSection, "ils_min_delta", 1e-7 );
  451. double ils_min_residual = _conf->gD ( _confSection, "ils_min_residual", 1e-7/*1e-2 */ );
  452. string ils_method = _conf->gS ( _confSection, "ils_method", "CG" );
  453. if ( ils_method.compare ( "CG" ) == 0 )
  454. {
  455. if ( verbose )
  456. std::cerr << "We use CG with " << ils_max_iterations << " iterations, " << ils_min_delta << " as min delta, and " << ils_min_residual << " as min res " << std::endl;
  457. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  458. if ( verbose )
  459. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients" << std::endl;
  460. }
  461. else if ( ils_method.compare ( "CGL" ) == 0 )
  462. {
  463. this->linsolver = new ILSConjugateGradientsLanczos ( ils_verbose , ils_max_iterations );
  464. if ( verbose )
  465. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients (Lanczos)" << std::endl;
  466. }
  467. else if ( ils_method.compare ( "SYMMLQ" ) == 0 )
  468. {
  469. this->linsolver = new ILSSymmLqLanczos ( ils_verbose , ils_max_iterations );
  470. if ( verbose )
  471. std::cerr << "FMKGPHyperparameterOptimization: using ILS SYMMLQ" << std::endl;
  472. }
  473. else if ( ils_method.compare ( "MINRES" ) == 0 )
  474. {
  475. this->linsolver = new ILSMinResLanczos ( ils_verbose , ils_max_iterations );
  476. if ( verbose )
  477. std::cerr << "FMKGPHyperparameterOptimization: using ILS MINRES" << std::endl;
  478. }
  479. else
  480. {
  481. std::cerr << "FMKGPHyperparameterOptimization: " << _confSection << ":ils_method (" << ils_method << ") does not match any type (CG,CGL,SYMMLQ,MINRES), I will use CG" << std::endl;
  482. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  483. }
  484. string optimizationMethod_s = _conf->gS ( _confSection, "optimization_method", "greedy" );
  485. if ( optimizationMethod_s == "greedy" )
  486. optimizationMethod = OPT_GREEDY;
  487. else if ( optimizationMethod_s == "downhillsimplex" )
  488. optimizationMethod = OPT_DOWNHILLSIMPLEX;
  489. else if ( optimizationMethod_s == "none" )
  490. optimizationMethod = OPT_NONE;
  491. else
  492. fthrow ( Exception, "Optimization method " << optimizationMethod_s << " is not known." );
  493. if ( verbose )
  494. std::cerr << "Using optimization method: " << optimizationMethod_s << std::endl;
  495. downhillSimplexMaxIterations = _conf->gI ( _confSection, "downhillsimplex_max_iterations", 20 );
  496. // do not run longer than a day :)
  497. downhillSimplexTimeLimit = _conf->gD ( _confSection, "downhillsimplex_time_limit", 24 * 60 * 60 );
  498. downhillSimplexParamTol = _conf->gD ( _confSection, "downhillsimplex_delta", 0.01 );
  499. optimizeNoise = _conf->gB ( _confSection, "optimize_noise", false );
  500. if ( verbose )
  501. std::cerr << "Optimize noise: " << ( optimizeNoise ? "on" : "off" ) << std::endl;
  502. this->b_usePreviousAlphas = _conf->gB ( _confSection, "b_usePreviousAlphas", true );
  503. if ( verbose )
  504. {
  505. std::cerr << "------------" << std::endl;
  506. std::cerr << "| start |" << std::endl;
  507. std::cerr << "------------" << std::endl;
  508. }
  509. }
  510. ///////////////////// ///////////////////// /////////////////////
  511. // GET / SET
  512. ///////////////////// ///////////////////// /////////////////////
  513. void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
  514. {
  515. parameterUpperBound = _parameterUpperBound;
  516. }
  517. void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
  518. {
  519. parameterLowerBound = _parameterLowerBound;
  520. }
  521. std::set<int> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
  522. {
  523. return this->knownClasses;
  524. }
  525. ///////////////////// ///////////////////// /////////////////////
  526. // CLASSIFIER STUFF
  527. ///////////////////// ///////////////////// /////////////////////
  528. inline void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize )
  529. {
  530. gplike = new GPLikelihoodApprox ( binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
  531. gplike->setDebug( debug );
  532. gplike->setVerbose( verbose );
  533. parameterVectorSize = ikmsum->getNumParameters();
  534. }
  535. void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & i_noEigenValues )
  536. {
  537. //compute the largest eigenvalue of K + noise
  538. try
  539. {
  540. eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, i_noEigenValues );
  541. }
  542. catch ( char const* exceptionMsg)
  543. {
  544. std::cerr << exceptionMsg << std::endl;
  545. throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
  546. }
  547. //NOTE EigenValue computation extracts EV and EW per default in decreasing order.
  548. }
  549. void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  550. {
  551. if (verbose)
  552. std::cerr << "perform optimization" << std::endl;
  553. if ( optimizationMethod == OPT_GREEDY )
  554. {
  555. if ( verbose )
  556. std::cerr << "OPT_GREEDY!!! " << std::endl;
  557. // simple greedy strategy
  558. if ( ikmsum->getNumParameters() != 1 )
  559. fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
  560. NICE::Vector lB = ikmsum->getParameterLowerBounds();
  561. NICE::Vector uB = ikmsum->getParameterUpperBounds();
  562. if ( verbose )
  563. std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
  564. NICE::Vector tmp = gplike.getBestParameters( );
  565. for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
  566. {
  567. OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
  568. gplike.evaluate ( hyperp );
  569. }
  570. }
  571. else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
  572. {
  573. //standard as before, normal optimization
  574. if ( verbose )
  575. std::cerr << "DOWNHILLSIMPLEX!!! " << std::endl;
  576. // downhill simplex strategy
  577. OPTIMIZATION::DownhillSimplexOptimizer optimizer;
  578. OPTIMIZATION::matrix_type initialParams ( parameterVectorSize, 1 );
  579. NICE::Vector currentParameters;
  580. ikmsum->getParameters ( currentParameters );
  581. for ( uint i = 0 ; i < parameterVectorSize; i++ )
  582. initialParams(i,0) = currentParameters[ i ];
  583. if ( verbose )
  584. std::cerr << "Initial parameters: " << initialParams << std::endl;
  585. //the scales object does not really matter in the actual implementation of Downhill Simplex
  586. //OPTIMIZATION::matrix_type scales ( parameterVectorSize, 1);
  587. //scales.Set(1.0);
  588. OPTIMIZATION::SimpleOptProblem optProblem ( &gplike, initialParams, initialParams /* scales*/ );
  589. // std::cerr << "OPT: " << mypara << " " << nlikelihood << " " << logdet << " " << dataterm << std::endl;
  590. optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
  591. optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
  592. optimizer.setParamTol ( true, downhillSimplexParamTol );
  593. optimizer.optimizeProb ( optProblem );
  594. }
  595. else if ( optimizationMethod == OPT_NONE )
  596. {
  597. if ( verbose )
  598. std::cerr << "NO OPTIMIZATION!!! " << std::endl;
  599. // without optimization
  600. if ( optimizeNoise )
  601. fthrow ( Exception, "Deactivate optimize_noise!" );
  602. if ( verbose )
  603. std::cerr << "Optimization is deactivated!" << std::endl;
  604. double value (1.0);
  605. if ( this->parameterLowerBound == this->parameterUpperBound)
  606. value = this->parameterLowerBound;
  607. pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
  608. pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
  609. // we use the standard value
  610. OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
  611. gplike.setParameterLowerBound ( value );
  612. gplike.setParameterUpperBound ( value );
  613. //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
  614. gplike.computeAlphaDirect( hyperp, eigenMax );
  615. }
  616. if ( verbose )
  617. {
  618. std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
  619. }
  620. }
  621. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  622. {
  623. // transform all features with the currently "optimal" parameter
  624. ikmsum->setParameters ( gplike.getBestParameters() );
  625. }
  626. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
  627. {
  628. std::cerr << "FMKGPHyperparameterOptimization::computeMatricesAndLUTs" << std::endl;
  629. precomputedA.clear();
  630. precomputedB.clear();
  631. std::cerr << "length of best alpha vectors: " << gplike.getBestAlphas().size() << std::endl;
  632. for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
  633. {
  634. PrecomputedType A;
  635. PrecomputedType B;
  636. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  637. A.setIoUntilEndOfFile ( false );
  638. B.setIoUntilEndOfFile ( false );
  639. precomputedA[ i->first ] = A;
  640. precomputedB[ i->first ] = B;
  641. if ( q != NULL )
  642. {
  643. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
  644. //just to be sure that we do not waste space here
  645. if ( precomputedT[ i->first ] != NULL )
  646. delete precomputedT[ i->first ];
  647. precomputedT[ i->first ] = T;
  648. }
  649. //TODO update the variance-related matrices as well here - currently it is done before in the outer method!!!
  650. }
  651. if ( this->precomputedTForVarEst != NULL )
  652. {
  653. this->prepareVarianceApproximationRough();
  654. }
  655. else if ( this->precomputedAForVarEst.size() > 0)
  656. {
  657. this->prepareVarianceApproximationFine();
  658. }
  659. }
  660. #ifdef NICE_USELIB_MATIO
  661. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
  662. {
  663. map<int, int> examples;
  664. Vector y ( yl.size() );
  665. int ind = 0;
  666. for ( uint i = 0 ; i < yl.size(); i++ )
  667. {
  668. if ( positives.find ( i ) != positives.end() ) {
  669. y[ examples.size() ] = 1.0;
  670. examples.insert ( pair<int, int> ( i, ind ) );
  671. ind++;
  672. } else if ( negatives.find ( i ) != negatives.end() ) {
  673. y[ examples.size() ] = -1.0;
  674. examples.insert ( pair<int, int> ( i, ind ) );
  675. ind++;
  676. }
  677. }
  678. y.resize ( examples.size() );
  679. std::cerr << "Examples: " << examples.size() << std::endl;
  680. optimize ( data, y, examples, noise );
  681. }
  682. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
  683. {
  684. Timer t;
  685. t.start();
  686. std::cerr << "Initializing data structure ..." << std::endl;
  687. if ( fmk != NULL ) delete fmk;
  688. fmk = new FastMinKernel ( data, noise, examples );
  689. t.stop();
  690. if (verboseTime)
  691. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  692. optimize ( y );
  693. }
  694. #endif
  695. int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
  696. {
  697. myClasses.clear();
  698. // determine which classes we have in our label vector
  699. // -> MATLAB: myClasses = unique(y);
  700. for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
  701. {
  702. if ( myClasses.find ( *it ) == myClasses.end() )
  703. {
  704. myClasses.insert ( *it );
  705. }
  706. }
  707. //count how many different classes appear in our data
  708. int nrOfClasses = myClasses.size();
  709. binaryLabels.clear();
  710. //compute the corresponding binary label vectors
  711. if ( nrOfClasses > 2 )
  712. {
  713. //resize every labelVector and set all entries to -1.0
  714. for ( set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
  715. {
  716. binaryLabels[ *k ].resize ( y.size() );
  717. binaryLabels[ *k ].set ( -1.0 );
  718. }
  719. // now look on every example and set the entry of its corresponding label vector to 1.0
  720. // proper existance should not be a problem
  721. for ( int i = 0 ; i < ( int ) y.size(); i++ )
  722. binaryLabels[ y[i] ][i] = 1.0;
  723. }
  724. else if ( nrOfClasses == 2 )
  725. {
  726. //binary setting -- prepare two binary label vectors with opposite signs
  727. NICE::Vector yb ( y );
  728. binaryLabelNegative = *(myClasses.begin());
  729. std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
  730. binaryLabelPositive = *classIt;
  731. if ( verbose )
  732. std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
  733. for ( uint i = 0 ; i < yb.size() ; i++ )
  734. yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
  735. binaryLabels[ binaryLabelPositive ] = yb;
  736. //NOTE
  737. //uncomment the following, if you want to perform real binary computations with 2 classes
  738. // //we only need one vector, which already contains +1 and -1, so we need only one computation too
  739. // binaryLabels[ negativeClass ] = yb;
  740. // binaryLabels[ negativeClass ] *= -1.0;
  741. // std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  742. // binaryLabels[ 0 ] = yb;
  743. // binaryLabels[ 0 ] *= -1.0;
  744. //comment the following, if you want to do a real binary computation. It should be senseless, but let's see...
  745. //we do NOT do real binary computation, but an implicite one with only a single object
  746. nrOfClasses--;
  747. std::set<int>::iterator it = myClasses.begin(); it++;
  748. // myClasses.erase(it);
  749. }
  750. else //OCC setting
  751. {
  752. //we set the labels to 1, independent of the previously given class number
  753. //however, the original class numbers are stored and returned in classification
  754. Vector yNew ( y.size(), 1 );
  755. myClasses.clear();
  756. myClasses.insert ( 1 );
  757. //we have to indicate, that we are in an OCC setting
  758. nrOfClasses--;
  759. }
  760. return nrOfClasses;
  761. }
  762. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
  763. {
  764. if ( fmk == NULL )
  765. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  766. this->labels = y;
  767. std::map<int, NICE::Vector> binaryLabels;
  768. prepareBinaryLabels ( binaryLabels, y , knownClasses );
  769. //now call the main function :)
  770. this->optimize(binaryLabels);
  771. }
  772. void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
  773. {
  774. Timer t;
  775. t.start();
  776. //how many different classes do we have right now?
  777. int nrOfClasses = binaryLabels.size();
  778. if (verbose)
  779. {
  780. std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
  781. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  782. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
  783. }
  784. // combine standard model and noise model
  785. Timer t1;
  786. t1.start();
  787. //setup the kernel combination
  788. ikmsum = new IKMLinearCombination ();
  789. if ( verbose )
  790. {
  791. std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  792. }
  793. //First model: noise
  794. ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
  795. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  796. fmk->setNoise ( 0.0 );
  797. //NOTE The GMHIKernel is always the last model which is added (this is necessary for easy store and restore functionality)
  798. ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
  799. t1.stop();
  800. if (verboseTime)
  801. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  802. GPLikelihoodApprox * gplike;
  803. uint parameterVectorSize;
  804. t1.start();
  805. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  806. t1.stop();
  807. if (verboseTime)
  808. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  809. if (verbose)
  810. {
  811. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  812. }
  813. t1.start();
  814. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  815. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  816. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  817. t1.stop();
  818. if (verboseTime)
  819. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  820. if ( verbose )
  821. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  822. t1.start();
  823. this->performOptimization ( *gplike, parameterVectorSize );
  824. t1.stop();
  825. if (verboseTime)
  826. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  827. if ( verbose )
  828. std::cerr << "Preparing classification ..." << std::endl;
  829. t1.start();
  830. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  831. t1.stop();
  832. if (verboseTime)
  833. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  834. t1.start();
  835. this->computeMatricesAndLUTs ( *gplike );
  836. t1.stop();
  837. if (verboseTime)
  838. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  839. t.stop();
  840. ResourceStatistics rs;
  841. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  842. long maxMemory;
  843. rs.getMaximumMemory ( maxMemory );
  844. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  845. //don't waste memory
  846. delete gplike;
  847. }
  848. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  849. {
  850. PrecomputedType AVar;
  851. fmk->hikPrepareKVNApproximation ( AVar );
  852. precomputedAForVarEst = AVar;
  853. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  854. if ( q != NULL )
  855. {
  856. double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
  857. this->precomputedTForVarEst = T;
  858. }
  859. }
  860. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  861. {
  862. if ( this->eigenMax.size() != this->nrOfEigenvaluesToConsiderForVarApprox)
  863. {
  864. std::cerr << "not enough eigenvectors computed for fine approximation of predictive variance. Compute missing ones!" << std::endl;
  865. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  866. }
  867. }
  868. int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
  869. {
  870. // loop through all classes
  871. if ( precomputedA.size() == 0 )
  872. {
  873. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  874. }
  875. uint maxClassNo = 0;
  876. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  877. {
  878. uint classno = i->first;
  879. maxClassNo = std::max ( maxClassNo, classno );
  880. double beta;
  881. if ( q != NULL ) {
  882. map<int, double *>::const_iterator j = precomputedT.find ( classno );
  883. double *T = j->second;
  884. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  885. } else {
  886. const PrecomputedType & A = i->second;
  887. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  888. const PrecomputedType & B = j->second;
  889. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  890. // Giving the transformation pf as an additional
  891. // argument is necessary due to the following reason:
  892. // FeatureMatrixT is sorted according to the original values, therefore,
  893. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  894. // values as inputs. However, for calculation we need the transformed features values.
  895. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  896. }
  897. scores[ classno ] = beta;
  898. }
  899. scores.setDim ( maxClassNo + 1 );
  900. if ( precomputedA.size() > 1 )
  901. { // multi-class classification
  902. return scores.maxElement();
  903. }
  904. else
  905. { // binary setting
  906. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  907. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  908. }
  909. }
  910. int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
  911. {
  912. // loop through all classes
  913. if ( precomputedA.size() == 0 )
  914. {
  915. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  916. }
  917. uint maxClassNo = 0;
  918. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  919. {
  920. uint classno = i->first;
  921. maxClassNo = std::max ( maxClassNo, classno );
  922. double beta;
  923. if ( q != NULL ) {
  924. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  925. double *T = j->second;
  926. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  927. } else {
  928. const PrecomputedType & A = i->second;
  929. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  930. const PrecomputedType & B = j->second;
  931. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  932. // Giving the transformation pf as an additional
  933. // argument is necessary due to the following reason:
  934. // FeatureMatrixT is sorted according to the original values, therefore,
  935. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  936. // values as inputs. However, for calculation we need the transformed features values.
  937. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  938. }
  939. scores[ classno ] = beta;
  940. }
  941. scores.setDim ( maxClassNo + 1 );
  942. if ( precomputedA.size() > 1 )
  943. { // multi-class classification
  944. return scores.maxElement();
  945. }
  946. else
  947. { // binary setting
  948. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  949. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  950. }
  951. }
  952. //////////////////////////////////////////
  953. // variance computation: sparse inputs
  954. //////////////////////////////////////////
  955. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
  956. {
  957. // security check!
  958. if ( pf == NULL )
  959. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  960. // ---------------- compute the first term --------------------
  961. double kSelf ( 0.0 );
  962. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  963. {
  964. kSelf += pf->f ( 0, it->second );
  965. // if weighted dimensions:
  966. //kSelf += pf->f(it->first,it->second);
  967. }
  968. // ---------------- compute the approximation of the second term --------------------
  969. double normKStar;
  970. if ( q != NULL )
  971. {
  972. if ( precomputedTForVarEst == NULL )
  973. {
  974. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  975. }
  976. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  977. }
  978. else
  979. {
  980. if ( precomputedAForVarEst.size () == 0 )
  981. {
  982. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  983. }
  984. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  985. }
  986. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  987. }
  988. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
  989. {
  990. // security check!
  991. if ( eigenMaxVectors.rows() == 0 )
  992. {
  993. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  994. }
  995. // ---------------- compute the first term --------------------
  996. // Timer t;
  997. // t.start();
  998. double kSelf ( 0.0 );
  999. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1000. {
  1001. kSelf += pf->f ( 0, it->second );
  1002. // if weighted dimensions:
  1003. //kSelf += pf->f(it->first,it->second);
  1004. }
  1005. // ---------------- compute the approximation of the second term --------------------
  1006. // t.stop();
  1007. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1008. // t.start();
  1009. NICE::Vector kStar;
  1010. fmk->hikComputeKernelVector ( x, kStar );
  1011. /* t.stop();
  1012. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1013. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1014. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1015. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1016. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1017. //wherefor it takes aeons...
  1018. //so we compute it by ourselves
  1019. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  1020. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  1021. // double kStarI ( kStar[tmpI] );
  1022. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1023. {
  1024. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1025. {
  1026. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1027. }
  1028. }
  1029. double projectionLength ( 0.0 );
  1030. double currentSecondTerm ( 0.0 );
  1031. double sumOfProjectionLengths ( 0.0 );
  1032. int cnt ( 0 );
  1033. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1034. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1035. {
  1036. projectionLength = ( *it );
  1037. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1038. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1039. it++;
  1040. cnt++;
  1041. }
  1042. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1043. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1044. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1045. {
  1046. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1047. }
  1048. predVariance = kSelf - currentSecondTerm;
  1049. }
  1050. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1051. {
  1052. // security check!
  1053. if ( ikmsum->getNumberOfModels() == 0 )
  1054. {
  1055. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1056. }
  1057. Timer t;
  1058. // t.start();
  1059. // ---------------- compute the first term --------------------
  1060. double kSelf ( 0.0 );
  1061. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1062. {
  1063. kSelf += pf->f ( 0, it->second );
  1064. // if weighted dimensions:
  1065. //kSelf += pf->f(it->first,it->second);
  1066. }
  1067. // ---------------- compute the second term --------------------
  1068. // t.stop();
  1069. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  1070. // t.start();
  1071. NICE::Vector kStar;
  1072. fmk->hikComputeKernelVector ( x, kStar );
  1073. // t.stop();
  1074. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  1075. //
  1076. //now run the ILS method
  1077. NICE::Vector diagonalElements;
  1078. ikmsum->getDiagonalElements ( diagonalElements );
  1079. // t.start();
  1080. // init simple jacobi pre-conditioning
  1081. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1082. //perform pre-conditioning
  1083. if ( linsolver_cg != NULL )
  1084. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1085. NICE::Vector beta;
  1086. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1087. * K~ = K + sigma^2 I
  1088. *
  1089. * K~ \approx lambda_max v v^T
  1090. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1091. * => \lambda_max v^T alpha = v^T k_*
  1092. * => alpha = k_* / lambda_max could be a good initial start
  1093. * If we put everything in the first equation this gives us
  1094. * v = k_*
  1095. * This reduces the number of iterations by 5 or 8
  1096. */
  1097. beta = (kStar * (1.0 / eigenMax[0]) );
  1098. /* t.stop();
  1099. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  1100. t.start();*/
  1101. // t.start();
  1102. linsolver->solveLin ( *ikmsum, kStar, beta );
  1103. // t.stop();
  1104. // t.stop();
  1105. // t.stop();
  1106. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  1107. beta *= kStar;
  1108. double currentSecondTerm( beta.Sum() );
  1109. predVariance = kSelf - currentSecondTerm;
  1110. }
  1111. //////////////////////////////////////////
  1112. // variance computation: non-sparse inputs
  1113. //////////////////////////////////////////
  1114. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1115. {
  1116. // security check!
  1117. if ( pf == NULL )
  1118. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1119. // ---------------- compute the first term --------------------
  1120. double kSelf ( 0.0 );
  1121. int dim ( 0 );
  1122. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1123. {
  1124. kSelf += pf->f ( 0, *it );
  1125. // if weighted dimensions:
  1126. //kSelf += pf->f(dim,*it);
  1127. }
  1128. // ---------------- compute the approximation of the second term --------------------
  1129. double normKStar;
  1130. if ( q != NULL )
  1131. {
  1132. if ( precomputedTForVarEst == NULL )
  1133. {
  1134. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1135. }
  1136. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  1137. }
  1138. else
  1139. {
  1140. if ( precomputedAForVarEst.size () == 0 )
  1141. {
  1142. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1143. }
  1144. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  1145. }
  1146. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1147. }
  1148. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
  1149. {
  1150. // security check!
  1151. if ( eigenMaxVectors.rows() == 0 )
  1152. {
  1153. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1154. }
  1155. // ---------------- compute the first term --------------------
  1156. // Timer t;
  1157. // t.start();
  1158. double kSelf ( 0.0 );
  1159. int dim ( 0 );
  1160. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1161. {
  1162. kSelf += pf->f ( 0, *it );
  1163. // if weighted dimensions:
  1164. //kSelf += pf->f(dim,*it);
  1165. }
  1166. // ---------------- compute the approximation of the second term --------------------
  1167. // t.stop();
  1168. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1169. // t.start();
  1170. NICE::Vector kStar;
  1171. fmk->hikComputeKernelVector ( x, kStar );
  1172. /* t.stop();
  1173. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1174. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1175. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1176. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1177. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1178. //wherefor it takes aeons...
  1179. //so we compute it by ourselves
  1180. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  1181. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  1182. // double kStarI ( kStar[tmpI] );
  1183. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1184. {
  1185. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1186. {
  1187. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1188. }
  1189. }
  1190. double projectionLength ( 0.0 );
  1191. double currentSecondTerm ( 0.0 );
  1192. double sumOfProjectionLengths ( 0.0 );
  1193. int cnt ( 0 );
  1194. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1195. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1196. {
  1197. projectionLength = ( *it );
  1198. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1199. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1200. it++;
  1201. cnt++;
  1202. }
  1203. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1204. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1205. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1206. {
  1207. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1208. }
  1209. predVariance = kSelf - currentSecondTerm;
  1210. }
  1211. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & x, double & predVariance ) const
  1212. {
  1213. if ( ikmsum->getNumberOfModels() == 0 )
  1214. {
  1215. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1216. }
  1217. Timer t;
  1218. // t.start();
  1219. // ---------------- compute the first term --------------------
  1220. double kSelf ( 0.0 );
  1221. int dim ( 0 );
  1222. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1223. {
  1224. kSelf += pf->f ( 0, *it );
  1225. // if weighted dimensions:
  1226. //kSelf += pf->f(dim,*it);
  1227. }
  1228. // ---------------- compute the second term --------------------
  1229. // t.stop();
  1230. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  1231. // t.start();
  1232. NICE::Vector kStar;
  1233. fmk->hikComputeKernelVector ( x, kStar );
  1234. // t.stop();
  1235. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  1236. //
  1237. //now run the ILS method
  1238. NICE::Vector diagonalElements;
  1239. ikmsum->getDiagonalElements ( diagonalElements );
  1240. // t.start();
  1241. // init simple jacobi pre-conditioning
  1242. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1243. //perform pre-conditioning
  1244. if ( linsolver_cg != NULL )
  1245. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1246. NICE::Vector beta;
  1247. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1248. * K~ = K + sigma^2 I
  1249. *
  1250. * K~ \approx lambda_max v v^T
  1251. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1252. * => \lambda_max v^T alpha = v^T k_*
  1253. * => alpha = k_* / lambda_max could be a good initial start
  1254. * If we put everything in the first equation this gives us
  1255. * v = k_*
  1256. * This reduces the number of iterations by 5 or 8
  1257. */
  1258. beta = (kStar * (1.0 / eigenMax[0]) );
  1259. /* t.stop();
  1260. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  1261. t.start();*/
  1262. // t.start();
  1263. linsolver->solveLin ( *ikmsum, kStar, beta );
  1264. // t.stop();
  1265. // t.stop();
  1266. // t.stop();
  1267. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  1268. beta *= kStar;
  1269. double currentSecondTerm( beta.Sum() );
  1270. predVariance = kSelf - currentSecondTerm;
  1271. }
  1272. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1273. // interface specific methods for store and restore
  1274. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1275. void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
  1276. {
  1277. bool b_restoreVerbose ( false );
  1278. #ifdef B_RESTOREVERBOSE
  1279. b_restoreVerbose = true;
  1280. #endif
  1281. if ( is.good() )
  1282. {
  1283. if ( b_restoreVerbose )
  1284. std::cerr << " in FMKGP restore" << std::endl;
  1285. std::string tmp;
  1286. is >> tmp; //class name
  1287. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1288. {
  1289. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1290. throw;
  1291. }
  1292. if (fmk != NULL)
  1293. {
  1294. delete fmk;
  1295. fmk = NULL;
  1296. }
  1297. if ( ikmsum != NULL )
  1298. {
  1299. delete ikmsum;
  1300. }
  1301. ikmsum = new IKMLinearCombination ();
  1302. if ( b_restoreVerbose )
  1303. std::cerr << "ikmsum object created" << std::endl;
  1304. is.precision ( numeric_limits<double>::digits10 + 1 );
  1305. bool b_endOfBlock ( false ) ;
  1306. while ( !b_endOfBlock )
  1307. {
  1308. is >> tmp; // start of block
  1309. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1310. {
  1311. b_endOfBlock = true;
  1312. continue;
  1313. }
  1314. tmp = this->removeStartTag ( tmp );
  1315. if ( b_restoreVerbose )
  1316. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1317. if ( tmp.compare("fmk") == 0 )
  1318. {
  1319. fmk = new FastMinKernel;
  1320. fmk->restore( is, format );
  1321. is >> tmp; // end of block
  1322. tmp = this->removeEndTag ( tmp );
  1323. }
  1324. else if ( tmp.compare("precomputedA") == 0 )
  1325. {
  1326. is >> tmp; // size
  1327. int preCompSize ( 0 );
  1328. is >> preCompSize;
  1329. precomputedA.clear();
  1330. if ( b_restoreVerbose )
  1331. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1332. for ( int i = 0; i < preCompSize; i++ )
  1333. {
  1334. int nr;
  1335. is >> nr;
  1336. PrecomputedType pct;
  1337. pct.setIoUntilEndOfFile ( false );
  1338. pct.restore ( is, format );
  1339. precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1340. }
  1341. is >> tmp; // end of block
  1342. tmp = this->removeEndTag ( tmp );
  1343. }
  1344. else if ( tmp.compare("precomputedB") == 0 )
  1345. {
  1346. is >> tmp; // size
  1347. int preCompSize ( 0 );
  1348. is >> preCompSize;
  1349. precomputedB.clear();
  1350. if ( b_restoreVerbose )
  1351. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1352. for ( int i = 0; i < preCompSize; i++ )
  1353. {
  1354. int nr;
  1355. is >> nr;
  1356. PrecomputedType pct;
  1357. pct.setIoUntilEndOfFile ( false );
  1358. pct.restore ( is, format );
  1359. precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1360. }
  1361. is >> tmp; // end of block
  1362. tmp = this->removeEndTag ( tmp );
  1363. }
  1364. else if ( tmp.compare("precomputedT") == 0 )
  1365. {
  1366. is >> tmp; // size
  1367. int precomputedTSize ( 0 );
  1368. is >> precomputedTSize;
  1369. precomputedT.clear();
  1370. if ( b_restoreVerbose )
  1371. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1372. if ( precomputedTSize > 0 )
  1373. {
  1374. if ( b_restoreVerbose )
  1375. std::cerr << " restore precomputedT" << std::endl;
  1376. is >> tmp;
  1377. int sizeOfLUT;
  1378. is >> sizeOfLUT;
  1379. for (int i = 0; i < precomputedTSize; i++)
  1380. {
  1381. is >> tmp;
  1382. int index;
  1383. is >> index;
  1384. double * array = new double [ sizeOfLUT];
  1385. for ( int i = 0; i < sizeOfLUT; i++ )
  1386. {
  1387. is >> array[i];
  1388. }
  1389. precomputedT.insert ( std::pair<int, double*> ( index, array ) );
  1390. }
  1391. }
  1392. else
  1393. {
  1394. if ( b_restoreVerbose )
  1395. std::cerr << " skip restoring precomputedT" << std::endl;
  1396. }
  1397. is >> tmp; // end of block
  1398. tmp = this->removeEndTag ( tmp );
  1399. }
  1400. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1401. {
  1402. int sizeOfAForVarEst;
  1403. is >> sizeOfAForVarEst;
  1404. if ( b_restoreVerbose )
  1405. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1406. if (sizeOfAForVarEst > 0)
  1407. {
  1408. precomputedAForVarEst.clear();
  1409. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1410. precomputedAForVarEst.restore ( is, format );
  1411. }
  1412. is >> tmp; // end of block
  1413. tmp = this->removeEndTag ( tmp );
  1414. }
  1415. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1416. {
  1417. std::string isNull;
  1418. is >> isNull; // NOTNULL or NULL
  1419. if ( b_restoreVerbose )
  1420. std::cerr << "content of isNull: " << isNull << std::endl;
  1421. if (isNull.compare("NOTNULL") == 0)
  1422. {
  1423. if ( b_restoreVerbose )
  1424. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1425. int sizeOfLUT;
  1426. is >> sizeOfLUT;
  1427. precomputedTForVarEst = new double [ sizeOfLUT ];
  1428. for ( int i = 0; i < sizeOfLUT; i++ )
  1429. {
  1430. is >> precomputedTForVarEst[i];
  1431. }
  1432. }
  1433. else
  1434. {
  1435. if ( b_restoreVerbose )
  1436. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1437. if (precomputedTForVarEst != NULL)
  1438. delete precomputedTForVarEst;
  1439. }
  1440. is >> tmp; // end of block
  1441. tmp = this->removeEndTag ( tmp );
  1442. }
  1443. else if ( tmp.compare("eigenMax") == 0 )
  1444. {
  1445. is >> eigenMax;
  1446. is >> tmp; // end of block
  1447. tmp = this->removeEndTag ( tmp );
  1448. }
  1449. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1450. {
  1451. is >> eigenMaxVectors;
  1452. is >> tmp; // end of block
  1453. tmp = this->removeEndTag ( tmp );
  1454. }
  1455. else if ( tmp.compare("ikmsum") == 0 )
  1456. {
  1457. bool b_endOfBlock ( false ) ;
  1458. while ( !b_endOfBlock )
  1459. {
  1460. is >> tmp; // start of block
  1461. if ( this->isEndTag( tmp, "ikmsum" ) )
  1462. {
  1463. b_endOfBlock = true;
  1464. continue;
  1465. }
  1466. tmp = this->removeStartTag ( tmp );
  1467. if ( tmp.compare("IKMNoise") == 0 )
  1468. {
  1469. IKMNoise * ikmnoise = new IKMNoise ();
  1470. ikmnoise->restore ( is, format );
  1471. if ( b_restoreVerbose )
  1472. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1473. ikmsum->addModel ( ikmnoise );
  1474. }
  1475. else
  1476. {
  1477. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1478. throw;
  1479. }
  1480. }
  1481. }
  1482. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1483. {
  1484. is >> binaryLabelPositive;
  1485. is >> tmp; // end of block
  1486. tmp = this->removeEndTag ( tmp );
  1487. }
  1488. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1489. {
  1490. is >> binaryLabelNegative;
  1491. is >> tmp; // end of block
  1492. tmp = this->removeEndTag ( tmp );
  1493. }
  1494. else if ( tmp.compare("labels") == 0 )
  1495. {
  1496. is >> labels;
  1497. is >> tmp; // end of block
  1498. tmp = this->removeEndTag ( tmp );
  1499. }
  1500. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1501. {
  1502. is >> b_usePreviousAlphas;
  1503. is >> tmp; // end of block
  1504. tmp = this->removeEndTag ( tmp );
  1505. }
  1506. else
  1507. {
  1508. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1509. throw;
  1510. }
  1511. }
  1512. //NOTE are there any more models you added? then add them here respectively in the correct order
  1513. //.....
  1514. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1515. if ( b_restoreVerbose )
  1516. std::cerr << " add GMHIKernel" << std::endl;
  1517. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1518. if ( b_restoreVerbose )
  1519. std::cerr << " restore positive and negative label" << std::endl;
  1520. knownClasses.clear();
  1521. if ( b_restoreVerbose )
  1522. std::cerr << " fill known classes object " << std::endl;
  1523. if ( precomputedA.size() == 1)
  1524. {
  1525. knownClasses.insert( binaryLabelPositive );
  1526. knownClasses.insert( binaryLabelNegative );
  1527. if ( b_restoreVerbose )
  1528. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1529. }
  1530. else
  1531. {
  1532. for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
  1533. knownClasses.insert ( itA->first );
  1534. if ( b_restoreVerbose )
  1535. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1536. }
  1537. }
  1538. else
  1539. {
  1540. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1541. throw;
  1542. }
  1543. }
  1544. void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
  1545. {
  1546. if ( os.good() )
  1547. {
  1548. // show starting point
  1549. os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1550. os << this->createStartTag( "fmk" ) << std::endl;
  1551. fmk->store ( os, format );
  1552. os << this->createEndTag( "fmk" ) << std::endl;
  1553. os.precision ( numeric_limits<double>::digits10 + 1 );
  1554. //we only have to store the things we computed, since the remaining settings come with the config file afterwards
  1555. os << this->createStartTag( "precomputedA" ) << std::endl;
  1556. os << "size: " << precomputedA.size() << std::endl;
  1557. std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
  1558. for ( uint i = 0; i < precomputedA.size(); i++ )
  1559. {
  1560. os << preCompIt->first << std::endl;
  1561. ( preCompIt->second ).store ( os, format );
  1562. preCompIt++;
  1563. }
  1564. os << this->createEndTag( "precomputedA" ) << std::endl;
  1565. os << this->createStartTag( "precomputedB" ) << std::endl;
  1566. os << "size: " << precomputedB.size() << std::endl;
  1567. preCompIt = precomputedB.begin();
  1568. for ( uint i = 0; i < precomputedB.size(); i++ )
  1569. {
  1570. os << preCompIt->first << std::endl;
  1571. ( preCompIt->second ).store ( os, format );
  1572. preCompIt++;
  1573. }
  1574. os << this->createEndTag( "precomputedB" ) << std::endl;
  1575. os << this->createStartTag( "precomputedT" ) << std::endl;
  1576. os << "size: " << precomputedT.size() << std::endl;
  1577. if ( precomputedT.size() > 0 )
  1578. {
  1579. int sizeOfLUT ( 0 );
  1580. if ( q != NULL )
  1581. sizeOfLUT = q->size() * this->fmk->get_d();
  1582. os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1583. for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
  1584. {
  1585. os << "index: " << it->first << std::endl;
  1586. for ( int i = 0; i < sizeOfLUT; i++ )
  1587. {
  1588. os << ( it->second ) [i] << " ";
  1589. }
  1590. os << std::endl;
  1591. }
  1592. }
  1593. os << this->createEndTag( "precomputedT" ) << std::endl;
  1594. //now store the things needed for the variance estimation
  1595. os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  1596. os << precomputedAForVarEst.size() << std::endl;
  1597. if (precomputedAForVarEst.size() > 0)
  1598. {
  1599. precomputedAForVarEst.store ( os, format );
  1600. os << std::endl;
  1601. }
  1602. os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  1603. os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  1604. if ( precomputedTForVarEst != NULL )
  1605. {
  1606. os << "NOTNULL" << std::endl;
  1607. int sizeOfLUT ( 0 );
  1608. if ( q != NULL )
  1609. sizeOfLUT = q->size() * this->fmk->get_d();
  1610. os << sizeOfLUT << std::endl;
  1611. for ( int i = 0; i < sizeOfLUT; i++ )
  1612. {
  1613. os << precomputedTForVarEst[i] << " ";
  1614. }
  1615. os << std::endl;
  1616. }
  1617. else
  1618. {
  1619. os << "NULL" << std::endl;
  1620. }
  1621. os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  1622. //store the eigenvalues and eigenvectors
  1623. os << this->createStartTag( "eigenMax" ) << std::endl;
  1624. os << eigenMax << std::endl;
  1625. os << this->createEndTag( "eigenMax" ) << std::endl;
  1626. os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  1627. os << eigenMaxVectors << std::endl;
  1628. os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  1629. os << this->createStartTag( "ikmsum" ) << std::endl;
  1630. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1631. {
  1632. ( ikmsum->getModel ( j ) )->store ( os, format );
  1633. }
  1634. os << this->createEndTag( "ikmsum" ) << std::endl;
  1635. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1636. os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1637. os << binaryLabelPositive << std::endl;
  1638. os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1639. os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1640. os << binaryLabelNegative << std::endl;
  1641. os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1642. os << this->createStartTag( "labels" ) << std::endl;
  1643. os << labels << std::endl;
  1644. os << this->createEndTag( "labels" ) << std::endl;
  1645. os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  1646. os << b_usePreviousAlphas << std::endl;
  1647. os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  1648. // done
  1649. os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1650. }
  1651. else
  1652. {
  1653. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1654. }
  1655. }
  1656. void FMKGPHyperparameterOptimization::clear ( ) {};
  1657. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1658. // interface specific methods for incremental extensions
  1659. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1660. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  1661. const double & label,
  1662. const bool & performOptimizationAfterIncrement
  1663. )
  1664. {
  1665. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  1666. std::set< int > newClasses;
  1667. this->labels.append ( label );
  1668. //have we seen this class already?
  1669. if ( this->knownClasses.find( label ) == this->knownClasses.end() )
  1670. {
  1671. this->knownClasses.insert( label );
  1672. newClasses.insert( label );
  1673. }
  1674. std::cerr << "call addExample of fmk object " << std::endl;
  1675. // add the new example to our data structure
  1676. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  1677. NICE::Timer t;
  1678. t.start();
  1679. this->fmk->addExample ( example, pf );
  1680. t.stop();
  1681. if ( this->verboseTime)
  1682. std::cerr << "Time used for adding the data to the fmk object: " << t.getLast() << std::endl;
  1683. //TODO update the matrix for variance computations as well!!!
  1684. // add examples to all implicite kernel matrices we currently use
  1685. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  1686. std::cerr << "call updateAfterSingleIncrement " << std::endl;
  1687. // update the corresponding matrices A, B and lookup tables T
  1688. // optional: do the optimization again using the previously known solutions as initialization
  1689. this->updateAfterSingleIncrement ( *example, newClasses, performOptimizationAfterIncrement );
  1690. //clean up
  1691. newClasses.clear();
  1692. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  1693. }
  1694. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  1695. const NICE::Vector & newLabels,
  1696. const bool & performOptimizationAfterIncrement
  1697. )
  1698. {
  1699. // // // //TODO check whether this set is actually needed
  1700. // // // std::set< int > newClasses;
  1701. // // //
  1702. // // // if (this->knownClasses.size() == 1) //binary setting
  1703. // // // {
  1704. // // // int oldSize ( this->labels.size() );
  1705. // // // this->labels.resize ( this->labels.size() + newLabels.size() );
  1706. // // // for ( uint i = 0; i < newLabels.size(); i++ )
  1707. // // // {
  1708. // // // this->labels[i+oldSize] = newLabels[i];
  1709. // // // //have we seen this class already?
  1710. // // // if ( (newLabels[i] != this->binaryLabelPositive) && (newLabels[i] != this->binaryLabelNegative) )
  1711. // // // {
  1712. // // // fthrow(Exception, "Binary setting does not allow adding new classes so far");
  1713. // // // // knownClasses.insert( newLabels[i] );
  1714. // // // // newClasses.insert( newLabels[i] );
  1715. // // // }
  1716. // // // }
  1717. // // // }
  1718. // // // else //multi-class setting
  1719. // // // {
  1720. // // // int oldSize ( this->labels.size() );
  1721. // // // this->labels.resize ( this->labels.size() + newLabels.size() );
  1722. // // // for ( uint i = 0; i < newLabels.size(); i++ )
  1723. // // // {
  1724. // // // this->labels[i+oldSize] = newLabels[i];
  1725. // // // //have we seen this class already?
  1726. // // // if (knownClasses.find( newLabels[i] ) == knownClasses.end() )
  1727. // // // {
  1728. // // // knownClasses.insert( newLabels[i] );
  1729. // // // newClasses.insert( newLabels[i] );
  1730. // // // }
  1731. // // // }
  1732. // // // }
  1733. // // //
  1734. // // //
  1735. // // //
  1736. // // // // add the new example to our data structure
  1737. // // // // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  1738. // // // Timer t;
  1739. // // // t.start();
  1740. // // //
  1741. // // // fmk->addMultipleExamples ( newExamples, pf );
  1742. // // // t.stop();
  1743. // // // if (verboseTime)
  1744. // // // std::cerr << "Time used for adding the data to the fmk object: " << t.getLast() << std::endl;
  1745. // // //
  1746. // // // // add examples to all implicite kernel matrices we currently use
  1747. // // // this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  1748. // // //
  1749. // // // Timer tVar;
  1750. // // // tVar.start();
  1751. // // // //do we need to update our matrices?
  1752. // // // if ( precomputedAForVarEst.size() != 0)
  1753. // // // {
  1754. // // // std::cerr << "update the variance matrices " << std::endl;
  1755. // // // //this computes everything from the scratch
  1756. // // // this->prepareVarianceApproximation();
  1757. // // // //this would perform a more sophisticated update
  1758. // // // //unfortunately, there is a bug somewhere
  1759. // // // //TODO fixme!
  1760. // // // // std::cerr << "update the LUTs needed for variance computation" << std::endl;
  1761. // // // // for ( std::vector<const NICE::SparseVector*>::const_iterator exampleIt = newExamples.begin(); exampleIt != newExamples.end(); exampleIt++ )
  1762. // // // // {
  1763. // // // // std::cerr << "new example: " << std::endl;
  1764. // // // // (**exampleIt).store(std::cerr);
  1765. // // // // std::cerr << "now update the LUT for var est" << std::endl;
  1766. // // // // fmk->updatePreparationForKVNApproximation( **exampleIt, precomputedAForVarEst, pf );
  1767. // // // // if ( q != NULL )
  1768. // // // // {
  1769. // // // // fmk->updateLookupTableForKVNApproximation( **exampleIt, precomputedTForVarEst, *q, pf );
  1770. // // // // }
  1771. // // // // }
  1772. // // // // std::cerr << "update of LUTs for variance compuation done" << std::endl;
  1773. // // // }
  1774. // // // tVar.stop();
  1775. // // // if (verboseTime)
  1776. // // // std::cerr << "Time used for computing the Variance Matrix and LUT: " << tVar.getLast() << std::endl;
  1777. // // //
  1778. // // //
  1779. // // //
  1780. // // // // update the corresponding matrices A, B and lookup tables T
  1781. // // // // optional: do the optimization again using the previously known solutions as initialization
  1782. // // // updateAfterMultipleIncrements ( newExamples, newClasses, performOptimizationAfterIncrement );
  1783. // // //
  1784. // // // //clean up
  1785. // // // newClasses.clear();
  1786. }