FMKGPHyperparameterOptimization.cpp 92 KB

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