FMKGPHyperparameterOptimization.cpp 86 KB

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