FMKGPHyperparameterOptimization.cpp 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  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. uint maxClassNo = 0;
  934. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  935. {
  936. uint classno = i->first;
  937. maxClassNo = std::max ( maxClassNo, classno );
  938. double beta;
  939. if ( this->q != NULL ) {
  940. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  941. double *T = j->second;
  942. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  943. } else {
  944. const PrecomputedType & A = i->second;
  945. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  946. const PrecomputedType & B = j->second;
  947. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  948. // Giving the transformation pf as an additional
  949. // argument is necessary due to the following reason:
  950. // FeatureMatrixT is sorted according to the original values, therefore,
  951. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  952. // values as inputs. However, for calculation we need the transformed features values.
  953. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, pf );
  954. }
  955. _scores[ classno ] = beta;
  956. }
  957. _scores.setDim ( maxClassNo + 1 );
  958. if ( this->precomputedA.size() > 1 )
  959. { // multi-class classification
  960. return _scores.maxElement();
  961. }
  962. else if ( this->knownClasses.size() == 2 ) // binary setting
  963. {
  964. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  965. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  966. }
  967. else //OCC or regression setting
  968. {
  969. return 1;
  970. }
  971. }
  972. uint FMKGPHyperparameterOptimization::classify ( const NICE::Vector & _xstar,
  973. NICE::SparseVector & _scores
  974. ) const
  975. {
  976. // loop through all classes
  977. if ( this->precomputedA.size() == 0 )
  978. {
  979. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  980. }
  981. uint maxClassNo = 0;
  982. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  983. {
  984. uint classno = i->first;
  985. maxClassNo = std::max ( maxClassNo, classno );
  986. double beta;
  987. if ( this->q != NULL )
  988. {
  989. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  990. double *T = j->second;
  991. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  992. }
  993. else
  994. {
  995. const PrecomputedType & A = i->second;
  996. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  997. const PrecomputedType & B = j->second;
  998. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  999. // Giving the transformation pf as an additional
  1000. // argument is necessary due to the following reason:
  1001. // FeatureMatrixT is sorted according to the original values, therefore,
  1002. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  1003. // values as inputs. However, for calculation we need the transformed features values.
  1004. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, this->pf );
  1005. }
  1006. _scores[ classno ] = beta;
  1007. }
  1008. _scores.setDim ( maxClassNo + 1 );
  1009. if ( this->precomputedA.size() > 1 )
  1010. { // multi-class classification
  1011. return _scores.maxElement();
  1012. }
  1013. else if ( this->knownClasses.size() == 2 ) // binary setting
  1014. {
  1015. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  1016. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  1017. }
  1018. else //OCC or regression setting
  1019. {
  1020. return 1;
  1021. }
  1022. }
  1023. //////////////////////////////////////////
  1024. // variance computation: sparse inputs
  1025. //////////////////////////////////////////
  1026. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & _x,
  1027. double & _predVariance
  1028. ) const
  1029. {
  1030. // security check!
  1031. if ( this->pf == NULL )
  1032. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1033. // ---------------- compute the first term --------------------
  1034. double kSelf ( 0.0 );
  1035. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1036. {
  1037. kSelf += this->pf->f ( 0, it->second );
  1038. // if weighted dimensions:
  1039. //kSelf += pf->f(it->first,it->second);
  1040. }
  1041. // ---------------- compute the approximation of the second term --------------------
  1042. double normKStar;
  1043. if ( this->q != NULL )
  1044. {
  1045. if ( precomputedTForVarEst == NULL )
  1046. {
  1047. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1048. }
  1049. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, _x, normKStar );
  1050. }
  1051. else
  1052. {
  1053. if ( precomputedAForVarEst.size () == 0 )
  1054. {
  1055. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1056. }
  1057. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, _x, normKStar, pf );
  1058. }
  1059. _predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1060. }
  1061. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & _x,
  1062. double & _predVariance
  1063. ) const
  1064. {
  1065. if ( this->b_debug )
  1066. {
  1067. std::cerr << "FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine" << std::endl;
  1068. }
  1069. // security check!
  1070. if ( this->eigenMaxVectors.rows() == 0 )
  1071. {
  1072. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1073. }
  1074. // ---------------- compute the first term --------------------
  1075. // Timer t;
  1076. // t.start();
  1077. double kSelf ( 0.0 );
  1078. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1079. {
  1080. kSelf += this->pf->f ( 0, it->second );
  1081. // if weighted dimensions:
  1082. //kSelf += pf->f(it->first,it->second);
  1083. }
  1084. if ( this->b_debug )
  1085. {
  1086. std::cerr << "FMKGPHyp::VarApproxFine -- kSelf: " << kSelf << std::endl;
  1087. }
  1088. // ---------------- compute the approximation of the second term --------------------
  1089. // t.stop();
  1090. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1091. // t.start();
  1092. NICE::Vector kStar;
  1093. this->fmk->hikComputeKernelVector ( _x, kStar );
  1094. if ( this->b_debug )
  1095. {
  1096. std::cerr << "FMKGPHyp::VarApproxFine -- kStar: " << kStar << std::endl;
  1097. std::cerr << "nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1098. }
  1099. /* t.stop();
  1100. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1101. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1102. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1103. NICE::Vector multiplicationResults( this->nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1104. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1105. //wherefor it takes aeons...
  1106. //so we compute it by ourselves
  1107. if ( this->b_debug )
  1108. {
  1109. std::cerr << "FMKGPHyp::VarApproxFine -- nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1110. std::cerr << "FMKGPHyp::VarApproxFine -- initial multiplicationResults: " << multiplicationResults << std::endl;
  1111. }
  1112. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  1113. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1114. // double kStarI ( kStar[tmpI] );
  1115. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1116. {
  1117. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1118. {
  1119. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1120. }
  1121. }
  1122. if ( this->b_debug )
  1123. {
  1124. std::cerr << "FMKGPHyp::VarApproxFine -- computed multiplicationResults: " << multiplicationResults << std::endl;
  1125. }
  1126. double projectionLength ( 0.0 );
  1127. double currentSecondTerm ( 0.0 );
  1128. double sumOfProjectionLengths ( 0.0 );
  1129. int cnt ( 0 );
  1130. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1131. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1132. {
  1133. projectionLength = ( *it );
  1134. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1135. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1136. it++;
  1137. cnt++;
  1138. }
  1139. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1140. currentSecondTerm += ( 1.0 / this->eigenMax[this->nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1141. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1142. {
  1143. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1144. }
  1145. _predVariance = kSelf - currentSecondTerm;
  1146. }
  1147. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1148. {
  1149. // security check!
  1150. if ( this->ikmsum->getNumberOfModels() == 0 )
  1151. {
  1152. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1153. }
  1154. Timer t;
  1155. // t.start();
  1156. // ---------------- compute the first term --------------------
  1157. double kSelf ( 0.0 );
  1158. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1159. {
  1160. kSelf += this->pf->f ( 0, it->second );
  1161. // if weighted dimensions:
  1162. //kSelf += pf->f(it->first,it->second);
  1163. }
  1164. // ---------------- compute the second term --------------------
  1165. NICE::Vector kStar;
  1166. fmk->hikComputeKernelVector ( x, kStar );
  1167. //now run the ILS method
  1168. NICE::Vector diagonalElements;
  1169. ikmsum->getDiagonalElements ( diagonalElements );
  1170. // init simple jacobi pre-conditioning
  1171. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1172. //TODO what to do for other solver techniques?
  1173. //perform pre-conditioning
  1174. if ( linsolver_cg != NULL )
  1175. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1176. NICE::Vector beta;
  1177. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1178. * K~ = K + sigma^2 I
  1179. *
  1180. * K~ \approx lambda_max v v^T
  1181. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1182. * => \lambda_max v^T alpha = v^T k_*
  1183. * => alpha = k_* / lambda_max could be a good initial start
  1184. * If we put everything in the first equation this gives us
  1185. * v = k_*
  1186. * This reduces the number of iterations by 5 or 8
  1187. */
  1188. beta = (kStar * (1.0 / eigenMax[0]) );
  1189. linsolver->solveLin ( *ikmsum, kStar, beta );
  1190. beta *= kStar;
  1191. double currentSecondTerm( beta.Sum() );
  1192. predVariance = kSelf - currentSecondTerm;
  1193. }
  1194. //////////////////////////////////////////
  1195. // variance computation: non-sparse inputs
  1196. //////////////////////////////////////////
  1197. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1198. {
  1199. // security check!
  1200. if ( pf == NULL )
  1201. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1202. // ---------------- compute the first term --------------------
  1203. double kSelf ( 0.0 );
  1204. int dim ( 0 );
  1205. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1206. {
  1207. kSelf += pf->f ( 0, *it );
  1208. // if weighted dimensions:
  1209. //kSelf += pf->f(dim,*it);
  1210. }
  1211. // ---------------- compute the approximation of the second term --------------------
  1212. double normKStar;
  1213. if ( this->q != NULL )
  1214. {
  1215. if ( precomputedTForVarEst == NULL )
  1216. {
  1217. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1218. }
  1219. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, x, normKStar );
  1220. }
  1221. else
  1222. {
  1223. if ( precomputedAForVarEst.size () == 0 )
  1224. {
  1225. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1226. }
  1227. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, this->pf );
  1228. }
  1229. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1230. }
  1231. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & _x,
  1232. double & _predVariance
  1233. ) const
  1234. {
  1235. // security check!
  1236. if ( this->eigenMaxVectors.rows() == 0 )
  1237. {
  1238. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1239. }
  1240. // ---------------- compute the first term --------------------
  1241. double kSelf ( 0.0 );
  1242. uint dim ( 0 );
  1243. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1244. {
  1245. kSelf += this->pf->f ( 0, *it );
  1246. // if weighted dimensions:
  1247. //kSelf += pf->f(dim,*it);
  1248. }
  1249. // ---------------- compute the approximation of the second term --------------------
  1250. NICE::Vector kStar;
  1251. this->fmk->hikComputeKernelVector ( _x, kStar );
  1252. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1253. //wherefor it takes aeons...
  1254. //so we compute it by ourselves
  1255. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1256. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1257. NICE::Vector multiplicationResults(this-> nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1258. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1259. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1260. {
  1261. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1262. {
  1263. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1264. }
  1265. }
  1266. double projectionLength ( 0.0 );
  1267. double currentSecondTerm ( 0.0 );
  1268. double sumOfProjectionLengths ( 0.0 );
  1269. int cnt ( 0 );
  1270. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1271. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1272. {
  1273. projectionLength = ( *it );
  1274. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1275. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1276. it++;
  1277. cnt++;
  1278. }
  1279. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1280. currentSecondTerm += ( 1.0 / this->eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1281. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1282. {
  1283. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1284. }
  1285. _predVariance = kSelf - currentSecondTerm;
  1286. }
  1287. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & _x,
  1288. double & _predVariance
  1289. ) const
  1290. {
  1291. if ( this->ikmsum->getNumberOfModels() == 0 )
  1292. {
  1293. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1294. }
  1295. // ---------------- compute the first term --------------------
  1296. double kSelf ( 0.0 );
  1297. uint dim ( 0 );
  1298. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1299. {
  1300. kSelf += this->pf->f ( 0, *it );
  1301. // if weighted dimensions:
  1302. //kSelf += pf->f(dim,*it);
  1303. }
  1304. // ---------------- compute the second term --------------------
  1305. NICE::Vector kStar;
  1306. this->fmk->hikComputeKernelVector ( _x, kStar );
  1307. //now run the ILS method
  1308. NICE::Vector diagonalElements;
  1309. this->ikmsum->getDiagonalElements ( diagonalElements );
  1310. // init simple jacobi pre-conditioning
  1311. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( this->linsolver );
  1312. //perform pre-conditioning
  1313. if ( linsolver_cg != NULL )
  1314. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1315. NICE::Vector beta;
  1316. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1317. * K~ = K + sigma^2 I
  1318. *
  1319. * K~ \approx lambda_max v v^T
  1320. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1321. * => \lambda_max v^T alpha = v^T k_*
  1322. * => alpha = k_* / lambda_max could be a good initial start
  1323. * If we put everything in the first equation this gives us
  1324. * v = k_*
  1325. * This reduces the number of iterations by 5 or 8
  1326. */
  1327. beta = (kStar * (1.0 / this->eigenMax[0]) );
  1328. this->linsolver->solveLin ( *ikmsum, kStar, beta );
  1329. beta *= kStar;
  1330. double currentSecondTerm( beta.Sum() );
  1331. _predVariance = kSelf - currentSecondTerm;
  1332. }
  1333. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1334. // interface specific methods for store and restore
  1335. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1336. void FMKGPHyperparameterOptimization::restore ( std::istream & _is,
  1337. int _format
  1338. )
  1339. {
  1340. bool b_restoreVerbose ( false );
  1341. #ifdef B_RESTOREVERBOSE
  1342. b_restoreVerbose = true;
  1343. #endif
  1344. if ( _is.good() )
  1345. {
  1346. if ( b_restoreVerbose )
  1347. std::cerr << " in FMKGPHyperparameterOptimization restore" << std::endl;
  1348. std::string tmp;
  1349. _is >> tmp; //class name
  1350. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1351. {
  1352. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1353. throw;
  1354. }
  1355. if (fmk != NULL)
  1356. {
  1357. delete fmk;
  1358. fmk = NULL;
  1359. }
  1360. if ( ikmsum != NULL )
  1361. {
  1362. delete ikmsum;
  1363. }
  1364. ikmsum = new IKMLinearCombination ();
  1365. if ( b_restoreVerbose )
  1366. std::cerr << "ikmsum object created" << std::endl;
  1367. _is.precision ( numeric_limits<double>::digits10 + 1 );
  1368. bool b_endOfBlock ( false ) ;
  1369. while ( !b_endOfBlock )
  1370. {
  1371. _is >> tmp; // start of block
  1372. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1373. {
  1374. b_endOfBlock = true;
  1375. continue;
  1376. }
  1377. tmp = this->removeStartTag ( tmp );
  1378. if ( b_restoreVerbose )
  1379. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1380. ///////////////////////////////////
  1381. // output/debug related settings //
  1382. ///////////////////////////////////
  1383. if ( tmp.compare("verbose") == 0 )
  1384. {
  1385. _is >> this->b_verbose;
  1386. _is >> tmp; // end of block
  1387. tmp = this->removeEndTag ( tmp );
  1388. }
  1389. else if ( tmp.compare("verboseTime") == 0 )
  1390. {
  1391. _is >> this->b_verboseTime;
  1392. _is >> tmp; // end of block
  1393. tmp = this->removeEndTag ( tmp );
  1394. }
  1395. else if ( tmp.compare("debug") == 0 )
  1396. {
  1397. _is >> this->b_debug;
  1398. _is >> tmp; // end of block
  1399. tmp = this->removeEndTag ( tmp );
  1400. }
  1401. //////////////////////////////////////
  1402. // classification related variables //
  1403. //////////////////////////////////////
  1404. else if ( tmp.compare("b_performRegression") == 0 )
  1405. {
  1406. _is >> this->b_performRegression;
  1407. _is >> tmp; // end of block
  1408. tmp = this->removeEndTag ( tmp );
  1409. }
  1410. else if ( tmp.compare("fmk") == 0 )
  1411. {
  1412. if ( this->fmk != NULL )
  1413. delete this->fmk;
  1414. this->fmk = new FastMinKernel();
  1415. this->fmk->restore( _is, _format );
  1416. _is >> tmp; // end of block
  1417. tmp = this->removeEndTag ( tmp );
  1418. }
  1419. else if ( tmp.compare("q") == 0 )
  1420. {
  1421. std::string isNull;
  1422. _is >> isNull; // NOTNULL or NULL
  1423. if (isNull.compare("NOTNULL") == 0)
  1424. {
  1425. if ( this->q != NULL )
  1426. delete this->q;
  1427. std::string s_quantType;
  1428. _is >> s_quantType;
  1429. s_quantType = this->removeStartTag ( s_quantType );
  1430. if ( s_quantType == "Quantization1DAequiDist0To1" )
  1431. {
  1432. this->q = new NICE::Quantization1DAequiDist0To1();
  1433. }
  1434. else if ( s_quantType == "Quantization1DAequiDist0ToMax" )
  1435. {
  1436. this->q = new NICE::Quantization1DAequiDist0ToMax ( );
  1437. }
  1438. else if ( s_quantType == "QuantizationNDAequiDist0ToMax" )
  1439. {
  1440. this->q = new NICE::QuantizationNDAequiDist0ToMax ( );
  1441. }
  1442. else
  1443. {
  1444. fthrow(Exception, "Quantization type is unknown " << s_quantType);
  1445. }
  1446. this->q->restore ( _is, _format );
  1447. }
  1448. else
  1449. {
  1450. if ( this->q != NULL )
  1451. delete this->q;
  1452. this->q = NULL;
  1453. }
  1454. _is >> tmp; // end of block
  1455. tmp = this->removeEndTag ( tmp );
  1456. }
  1457. else if ( tmp.compare("parameterUpperBound") == 0 )
  1458. {
  1459. _is >> this->d_parameterUpperBound;
  1460. _is >> tmp; // end of block
  1461. tmp = this->removeEndTag ( tmp );
  1462. }
  1463. else if ( tmp.compare("parameterLowerBound") == 0 )
  1464. {
  1465. _is >> this->d_parameterLowerBound;
  1466. _is >> tmp; // end of block
  1467. tmp = this->removeEndTag ( tmp );
  1468. }
  1469. else if ( tmp.compare("pf") == 0 )
  1470. {
  1471. _is >> tmp; // start of block
  1472. if ( this->isEndTag( tmp, "pf" ) )
  1473. {
  1474. std::cerr << " ParameterizedFunction object can not be restored. Aborting..." << std::endl;
  1475. throw;
  1476. }
  1477. std::string transform ( this->removeStartTag( tmp ) );
  1478. if ( transform == "PFAbsExp" )
  1479. {
  1480. this->pf = new NICE::PFAbsExp ();
  1481. } else if ( transform == "PFExp" ) {
  1482. this->pf = new NICE::PFExp ();
  1483. }
  1484. else if ( transform == "PFIdentity" )
  1485. {
  1486. this->pf = new NICE::PFIdentity( );
  1487. } else {
  1488. fthrow(Exception, "Transformation type is unknown " << transform);
  1489. }
  1490. this->pf->restore( _is, _format);
  1491. _is >> tmp; // end of block
  1492. tmp = this->removeEndTag ( tmp );
  1493. }
  1494. else if ( tmp.compare("precomputedA") == 0 )
  1495. {
  1496. _is >> tmp; // size
  1497. uint preCompSize ( 0 );
  1498. _is >> preCompSize;
  1499. this->precomputedA.clear();
  1500. if ( b_restoreVerbose )
  1501. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1502. for ( int i = 0; i < preCompSize; i++ )
  1503. {
  1504. uint nr;
  1505. _is >> nr;
  1506. PrecomputedType pct;
  1507. pct.setIoUntilEndOfFile ( false );
  1508. pct.restore ( _is, _format );
  1509. this->precomputedA.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1510. }
  1511. _is >> tmp; // end of block
  1512. tmp = this->removeEndTag ( tmp );
  1513. }
  1514. else if ( tmp.compare("precomputedB") == 0 )
  1515. {
  1516. _is >> tmp; // size
  1517. uint preCompSize ( 0 );
  1518. _is >> preCompSize;
  1519. this->precomputedB.clear();
  1520. if ( b_restoreVerbose )
  1521. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1522. for ( int i = 0; i < preCompSize; i++ )
  1523. {
  1524. uint nr;
  1525. _is >> nr;
  1526. PrecomputedType pct;
  1527. pct.setIoUntilEndOfFile ( false );
  1528. pct.restore ( _is, _format );
  1529. this->precomputedB.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1530. }
  1531. _is >> tmp; // end of block
  1532. tmp = this->removeEndTag ( tmp );
  1533. }
  1534. else if ( tmp.compare("precomputedT") == 0 )
  1535. {
  1536. _is >> tmp; // size
  1537. uint precomputedTSize ( 0 );
  1538. _is >> precomputedTSize;
  1539. this->precomputedT.clear();
  1540. if ( b_restoreVerbose )
  1541. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1542. if ( precomputedTSize > 0 )
  1543. {
  1544. if ( b_restoreVerbose )
  1545. std::cerr << " restore precomputedT" << std::endl;
  1546. _is >> tmp;
  1547. int sizeOfLUT;
  1548. _is >> sizeOfLUT;
  1549. for (int i = 0; i < precomputedTSize; i++)
  1550. {
  1551. _is >> tmp;
  1552. uint index;
  1553. _is >> index;
  1554. double * array = new double [ sizeOfLUT];
  1555. for ( int i = 0; i < sizeOfLUT; i++ )
  1556. {
  1557. _is >> array[i];
  1558. }
  1559. this->precomputedT.insert ( std::pair<uint, double*> ( index, array ) );
  1560. }
  1561. }
  1562. else
  1563. {
  1564. if ( b_restoreVerbose )
  1565. std::cerr << " skip restoring precomputedT" << std::endl;
  1566. }
  1567. _is >> tmp; // end of block
  1568. tmp = this->removeEndTag ( tmp );
  1569. }
  1570. else if ( tmp.compare("labels") == 0 )
  1571. {
  1572. _is >> this->labels;
  1573. _is >> tmp; // end of block
  1574. tmp = this->removeEndTag ( tmp );
  1575. }
  1576. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1577. {
  1578. _is >> this->i_binaryLabelPositive;
  1579. _is >> tmp; // end of block
  1580. tmp = this->removeEndTag ( tmp );
  1581. }
  1582. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1583. {
  1584. _is >> this->i_binaryLabelNegative;
  1585. _is >> tmp; // end of block
  1586. tmp = this->removeEndTag ( tmp );
  1587. }
  1588. else if ( tmp.compare("knownClasses") == 0 )
  1589. {
  1590. _is >> tmp; // size
  1591. uint knownClassesSize ( 0 );
  1592. _is >> knownClassesSize;
  1593. this->knownClasses.clear();
  1594. if ( knownClassesSize > 0 )
  1595. {
  1596. for (uint i = 0; i < knownClassesSize; i++)
  1597. {
  1598. uint classNo;
  1599. _is >> classNo;
  1600. this->knownClasses.insert ( classNo );
  1601. }
  1602. }
  1603. else
  1604. {
  1605. //nothing to do
  1606. }
  1607. _is >> tmp; // end of block
  1608. tmp = this->removeEndTag ( tmp );
  1609. }
  1610. else if ( tmp.compare("ikmsum") == 0 )
  1611. {
  1612. bool b_endOfBlock ( false ) ;
  1613. while ( !b_endOfBlock )
  1614. {
  1615. _is >> tmp; // start of block
  1616. if ( this->isEndTag( tmp, "ikmsum" ) )
  1617. {
  1618. b_endOfBlock = true;
  1619. continue;
  1620. }
  1621. tmp = this->removeStartTag ( tmp );
  1622. if ( tmp.compare("IKMNoise") == 0 )
  1623. {
  1624. IKMNoise * ikmnoise = new IKMNoise ();
  1625. ikmnoise->restore ( _is, _format );
  1626. if ( b_restoreVerbose )
  1627. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1628. ikmsum->addModel ( ikmnoise );
  1629. }
  1630. else
  1631. {
  1632. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1633. throw;
  1634. }
  1635. }
  1636. }
  1637. //////////////////////////////////////////////
  1638. // Iterative Linear Solver //
  1639. //////////////////////////////////////////////
  1640. else if ( tmp.compare("linsolver") == 0 )
  1641. {
  1642. //TODO linsolver
  1643. // current solution: hard coded with default values, since LinearSolver does not offer Persistent functionalities
  1644. this->linsolver = new ILSConjugateGradients ( false , 1000, 1e-7, 1e-7 );
  1645. _is >> tmp; // end of block
  1646. tmp = this->removeEndTag ( tmp );
  1647. }
  1648. else if ( tmp.compare("ils_max_iterations") == 0 )
  1649. {
  1650. _is >> ils_max_iterations;
  1651. _is >> tmp; // end of block
  1652. tmp = this->removeEndTag ( tmp );
  1653. }
  1654. /////////////////////////////////////
  1655. // optimization related parameters //
  1656. /////////////////////////////////////
  1657. else if ( tmp.compare("optimizationMethod") == 0 )
  1658. {
  1659. unsigned int ui_optimizationMethod;
  1660. _is >> ui_optimizationMethod;
  1661. optimizationMethod = static_cast<OPTIMIZATIONTECHNIQUE> ( ui_optimizationMethod ) ;
  1662. _is >> tmp; // end of block
  1663. tmp = this->removeEndTag ( tmp );
  1664. }
  1665. else if ( tmp.compare("optimizeNoise") == 0 )
  1666. {
  1667. _is >> optimizeNoise;
  1668. _is >> tmp; // end of block
  1669. tmp = this->removeEndTag ( tmp );
  1670. }
  1671. else if ( tmp.compare("parameterStepSize") == 0 )
  1672. {
  1673. _is >> parameterStepSize;
  1674. _is >> tmp; // end of block
  1675. tmp = this->removeEndTag ( tmp );
  1676. }
  1677. else if ( tmp.compare("downhillSimplexMaxIterations") == 0 )
  1678. {
  1679. _is >> downhillSimplexMaxIterations;
  1680. _is >> tmp; // end of block
  1681. tmp = this->removeEndTag ( tmp );
  1682. }
  1683. else if ( tmp.compare("downhillSimplexTimeLimit") == 0 )
  1684. {
  1685. _is >> downhillSimplexTimeLimit;
  1686. _is >> tmp; // end of block
  1687. tmp = this->removeEndTag ( tmp );
  1688. }
  1689. else if ( tmp.compare("downhillSimplexParamTol") == 0 )
  1690. {
  1691. _is >> downhillSimplexParamTol;
  1692. _is >> tmp; // end of block
  1693. tmp = this->removeEndTag ( tmp );
  1694. }
  1695. //////////////////////////////////////////////
  1696. // likelihood computation related variables //
  1697. //////////////////////////////////////////////
  1698. else if ( tmp.compare("verifyApproximation") == 0 )
  1699. {
  1700. _is >> verifyApproximation;
  1701. _is >> tmp; // end of block
  1702. tmp = this->removeEndTag ( tmp );
  1703. }
  1704. else if ( tmp.compare("eig") == 0 )
  1705. {
  1706. //TODO eig
  1707. // currently hard coded, since EV does not offer Persistent functionalities and
  1708. // in addition, we currently have no other choice for EV then EVArnoldi
  1709. this->eig = new EVArnoldi ( false /*eig_verbose */, 10 );
  1710. _is >> tmp; // end of block
  1711. tmp = this->removeEndTag ( tmp );
  1712. }
  1713. else if ( tmp.compare("nrOfEigenvaluesToConsider") == 0 )
  1714. {
  1715. _is >> nrOfEigenvaluesToConsider;
  1716. _is >> tmp; // end of block
  1717. tmp = this->removeEndTag ( tmp );
  1718. }
  1719. else if ( tmp.compare("eigenMax") == 0 )
  1720. {
  1721. _is >> eigenMax;
  1722. _is >> tmp; // end of block
  1723. tmp = this->removeEndTag ( tmp );
  1724. }
  1725. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1726. {
  1727. _is >> eigenMaxVectors;
  1728. _is >> tmp; // end of block
  1729. tmp = this->removeEndTag ( tmp );
  1730. }
  1731. ////////////////////////////////////////////
  1732. // variance computation related variables //
  1733. ////////////////////////////////////////////
  1734. else if ( tmp.compare("nrOfEigenvaluesToConsiderForVarApprox") == 0 )
  1735. {
  1736. _is >> nrOfEigenvaluesToConsiderForVarApprox;
  1737. _is >> tmp; // end of block
  1738. tmp = this->removeEndTag ( tmp );
  1739. }
  1740. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1741. {
  1742. int sizeOfAForVarEst;
  1743. _is >> sizeOfAForVarEst;
  1744. if ( b_restoreVerbose )
  1745. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1746. if (sizeOfAForVarEst > 0)
  1747. {
  1748. precomputedAForVarEst.clear();
  1749. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1750. precomputedAForVarEst.restore ( _is, _format );
  1751. }
  1752. _is >> tmp; // end of block
  1753. tmp = this->removeEndTag ( tmp );
  1754. }
  1755. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1756. {
  1757. std::string isNull;
  1758. _is >> isNull; // NOTNULL or NULL
  1759. if ( b_restoreVerbose )
  1760. std::cerr << "content of isNull: " << isNull << std::endl;
  1761. if (isNull.compare("NOTNULL") == 0)
  1762. {
  1763. if ( b_restoreVerbose )
  1764. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1765. int sizeOfLUT;
  1766. _is >> sizeOfLUT;
  1767. precomputedTForVarEst = new double [ sizeOfLUT ];
  1768. for ( int i = 0; i < sizeOfLUT; i++ )
  1769. {
  1770. _is >> precomputedTForVarEst[i];
  1771. }
  1772. }
  1773. else
  1774. {
  1775. if ( b_restoreVerbose )
  1776. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1777. if (precomputedTForVarEst != NULL)
  1778. delete precomputedTForVarEst;
  1779. }
  1780. _is >> tmp; // end of block
  1781. tmp = this->removeEndTag ( tmp );
  1782. }
  1783. /////////////////////////////////////////////////////
  1784. // online / incremental learning related variables //
  1785. /////////////////////////////////////////////////////
  1786. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1787. {
  1788. _is >> b_usePreviousAlphas;
  1789. _is >> tmp; // end of block
  1790. tmp = this->removeEndTag ( tmp );
  1791. }
  1792. else if ( tmp.compare("previousAlphas") == 0 )
  1793. {
  1794. _is >> tmp; // size
  1795. uint sizeOfPreviousAlphas ( 0 );
  1796. _is >> sizeOfPreviousAlphas;
  1797. this->previousAlphas.clear();
  1798. if ( b_restoreVerbose )
  1799. std::cerr << "restore previousAlphas with size: " << sizeOfPreviousAlphas << std::endl;
  1800. for ( int i = 0; i < sizeOfPreviousAlphas; i++ )
  1801. {
  1802. uint classNo;
  1803. _is >> classNo;
  1804. NICE::Vector classAlpha;
  1805. _is >> classAlpha;
  1806. this->previousAlphas.insert ( std::pair< uint, NICE::Vector > ( classNo, classAlpha ) );
  1807. }
  1808. _is >> tmp; // end of block
  1809. tmp = this->removeEndTag ( tmp );
  1810. }
  1811. else
  1812. {
  1813. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1814. throw;
  1815. }
  1816. }
  1817. //NOTE are there any more models you added? then add them here respectively in the correct order
  1818. //.....
  1819. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1820. if ( b_restoreVerbose )
  1821. std::cerr << " add GMHIKernel" << std::endl;
  1822. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1823. if ( b_restoreVerbose )
  1824. std::cerr << " restore positive and negative label" << std::endl;
  1825. this->knownClasses.clear();
  1826. if ( b_restoreVerbose )
  1827. std::cerr << " fill known classes object " << std::endl;
  1828. if ( this->precomputedA.size() == 1)
  1829. {
  1830. this->knownClasses.insert( this->i_binaryLabelPositive );
  1831. this->knownClasses.insert( this->i_binaryLabelNegative );
  1832. if ( b_restoreVerbose )
  1833. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1834. }
  1835. else
  1836. {
  1837. for ( std::map<uint, PrecomputedType>::const_iterator itA = this->precomputedA.begin(); itA != this->precomputedA.end(); itA++)
  1838. knownClasses.insert ( itA->first );
  1839. if ( b_restoreVerbose )
  1840. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1841. }
  1842. }
  1843. else
  1844. {
  1845. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1846. throw;
  1847. }
  1848. }
  1849. void FMKGPHyperparameterOptimization::store ( std::ostream & _os,
  1850. int _format
  1851. ) const
  1852. {
  1853. if ( _os.good() )
  1854. {
  1855. // show starting point
  1856. _os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1857. // _os.precision ( numeric_limits<double>::digits10 + 1 );
  1858. ///////////////////////////////////
  1859. // output/debug related settings //
  1860. ///////////////////////////////////
  1861. _os << this->createStartTag( "verbose" ) << std::endl;
  1862. _os << this->b_verbose << std::endl;
  1863. _os << this->createEndTag( "verbose" ) << std::endl;
  1864. _os << this->createStartTag( "verboseTime" ) << std::endl;
  1865. _os << this->b_verboseTime << std::endl;
  1866. _os << this->createEndTag( "verboseTime" ) << std::endl;
  1867. _os << this->createStartTag( "debug" ) << std::endl;
  1868. _os << this->b_debug << std::endl;
  1869. _os << this->createEndTag( "debug" ) << std::endl;
  1870. //////////////////////////////////////
  1871. // classification related variables //
  1872. //////////////////////////////////////
  1873. _os << this->createStartTag( "b_performRegression" ) << std::endl;
  1874. _os << b_performRegression << std::endl;
  1875. _os << this->createEndTag( "b_performRegression" ) << std::endl;
  1876. _os << this->createStartTag( "fmk" ) << std::endl;
  1877. this->fmk->store ( _os, _format );
  1878. _os << this->createEndTag( "fmk" ) << std::endl;
  1879. _os << this->createStartTag( "q" ) << std::endl;
  1880. if ( q != NULL )
  1881. {
  1882. _os << "NOTNULL" << std::endl;
  1883. this->q->store ( _os, _format );
  1884. }
  1885. else
  1886. {
  1887. _os << "NULL" << std::endl;
  1888. }
  1889. _os << this->createEndTag( "q" ) << std::endl;
  1890. _os << this->createStartTag( "parameterUpperBound" ) << std::endl;
  1891. _os << this->d_parameterUpperBound << std::endl;
  1892. _os << this->createEndTag( "parameterUpperBound" ) << std::endl;
  1893. _os << this->createStartTag( "parameterLowerBound" ) << std::endl;
  1894. _os << this->d_parameterLowerBound << std::endl;
  1895. _os << this->createEndTag( "parameterLowerBound" ) << std::endl;
  1896. _os << this->createStartTag( "pf" ) << std::endl;
  1897. this->pf->store(_os, _format);
  1898. _os << this->createEndTag( "pf" ) << std::endl;
  1899. _os << this->createStartTag( "precomputedA" ) << std::endl;
  1900. _os << "size: " << this->precomputedA.size() << std::endl;
  1901. std::map< uint, PrecomputedType >::const_iterator preCompIt = this->precomputedA.begin();
  1902. for ( uint i = 0; i < this->precomputedA.size(); i++ )
  1903. {
  1904. _os << preCompIt->first << std::endl;
  1905. ( preCompIt->second ).store ( _os, _format );
  1906. preCompIt++;
  1907. }
  1908. _os << this->createEndTag( "precomputedA" ) << std::endl;
  1909. _os << this->createStartTag( "precomputedB" ) << std::endl;
  1910. _os << "size: " << this->precomputedB.size() << std::endl;
  1911. preCompIt = this->precomputedB.begin();
  1912. for ( uint i = 0; i < this->precomputedB.size(); i++ )
  1913. {
  1914. _os << preCompIt->first << std::endl;
  1915. ( preCompIt->second ).store ( _os, _format );
  1916. preCompIt++;
  1917. }
  1918. _os << this->createEndTag( "precomputedB" ) << std::endl;
  1919. _os << this->createStartTag( "precomputedT" ) << std::endl;
  1920. _os << "size: " << this->precomputedT.size() << std::endl;
  1921. if ( this->precomputedT.size() > 0 )
  1922. {
  1923. int sizeOfLUT ( 0 );
  1924. if ( q != NULL )
  1925. sizeOfLUT = q->getNumberOfBins() * this->fmk->get_d();
  1926. _os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1927. for ( std::map< uint, double * >::const_iterator it = this->precomputedT.begin(); it != this->precomputedT.end(); it++ )
  1928. {
  1929. _os << "index: " << it->first << std::endl;
  1930. for ( int i = 0; i < sizeOfLUT; i++ )
  1931. {
  1932. _os << ( it->second ) [i] << " ";
  1933. }
  1934. _os << std::endl;
  1935. }
  1936. }
  1937. _os << this->createEndTag( "precomputedT" ) << std::endl;
  1938. _os << this->createStartTag( "labels" ) << std::endl;
  1939. _os << this->labels << std::endl;
  1940. _os << this->createEndTag( "labels" ) << std::endl;
  1941. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1942. _os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1943. _os << this->i_binaryLabelPositive << std::endl;
  1944. _os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1945. _os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1946. _os << this->i_binaryLabelNegative << std::endl;
  1947. _os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1948. _os << this->createStartTag( "knownClasses" ) << std::endl;
  1949. _os << "size: " << this->knownClasses.size() << std::endl;
  1950. for ( std::set< uint >::const_iterator itKnownClasses = this->knownClasses.begin();
  1951. itKnownClasses != this->knownClasses.end();
  1952. itKnownClasses++
  1953. )
  1954. {
  1955. _os << *itKnownClasses << " " << std::endl;
  1956. }
  1957. _os << this->createEndTag( "knownClasses" ) << std::endl;
  1958. _os << this->createStartTag( "ikmsum" ) << std::endl;
  1959. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1960. {
  1961. ( ikmsum->getModel ( j ) )->store ( _os, _format );
  1962. }
  1963. _os << this->createEndTag( "ikmsum" ) << std::endl;
  1964. //////////////////////////////////////////////
  1965. // Iterative Linear Solver //
  1966. //////////////////////////////////////////////
  1967. _os << this->createStartTag( "linsolver" ) << std::endl;
  1968. //TODO linsolver
  1969. _os << this->createEndTag( "linsolver" ) << std::endl;
  1970. _os << this->createStartTag( "ils_max_iterations" ) << std::endl;
  1971. _os << this->ils_max_iterations << std::endl;
  1972. _os << this->createEndTag( "ils_max_iterations" ) << std::endl;
  1973. /////////////////////////////////////
  1974. // optimization related parameters //
  1975. /////////////////////////////////////
  1976. _os << this->createStartTag( "optimizationMethod" ) << std::endl;
  1977. _os << this->optimizationMethod << std::endl;
  1978. _os << this->createEndTag( "optimizationMethod" ) << std::endl;
  1979. _os << this->createStartTag( "optimizeNoise" ) << std::endl;
  1980. _os << this->optimizeNoise << std::endl;
  1981. _os << this->createEndTag( "optimizeNoise" ) << std::endl;
  1982. _os << this->createStartTag( "parameterStepSize" ) << std::endl;
  1983. _os << this->parameterStepSize << std::endl;
  1984. _os << this->createEndTag( "parameterStepSize" ) << std::endl;
  1985. _os << this->createStartTag( "downhillSimplexMaxIterations" ) << std::endl;
  1986. _os << this->downhillSimplexMaxIterations << std::endl;
  1987. _os << this->createEndTag( "downhillSimplexMaxIterations" ) << std::endl;
  1988. _os << this->createStartTag( "downhillSimplexTimeLimit" ) << std::endl;
  1989. _os << this->downhillSimplexTimeLimit << std::endl;
  1990. _os << this->createEndTag( "downhillSimplexTimeLimit" ) << std::endl;
  1991. _os << this->createStartTag( "downhillSimplexParamTol" ) << std::endl;
  1992. _os << this->downhillSimplexParamTol << std::endl;
  1993. _os << this->createEndTag( "downhillSimplexParamTol" ) << std::endl;
  1994. //////////////////////////////////////////////
  1995. // likelihood computation related variables //
  1996. //////////////////////////////////////////////
  1997. _os << this->createStartTag( "verifyApproximation" ) << std::endl;
  1998. _os << this->verifyApproximation << std::endl;
  1999. _os << this->createEndTag( "verifyApproximation" ) << std::endl;
  2000. _os << this->createStartTag( "eig" ) << std::endl;
  2001. //TODO eig
  2002. _os << this->createEndTag( "eig" ) << std::endl;
  2003. _os << this->createStartTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2004. _os << this->nrOfEigenvaluesToConsider << std::endl;
  2005. _os << this->createEndTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2006. _os << this->createStartTag( "eigenMax" ) << std::endl;
  2007. _os << this->eigenMax << std::endl;
  2008. _os << this->createEndTag( "eigenMax" ) << std::endl;
  2009. _os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  2010. _os << this->eigenMaxVectors << std::endl;
  2011. _os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  2012. ////////////////////////////////////////////
  2013. // variance computation related variables //
  2014. ////////////////////////////////////////////
  2015. _os << this->createStartTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2016. _os << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  2017. _os << this->createEndTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2018. _os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  2019. _os << precomputedAForVarEst.size() << std::endl;
  2020. if ( this->precomputedAForVarEst.size() > 0)
  2021. {
  2022. this->precomputedAForVarEst.store ( _os, _format );
  2023. _os << std::endl;
  2024. }
  2025. _os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  2026. _os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  2027. if ( this->precomputedTForVarEst != NULL )
  2028. {
  2029. _os << "NOTNULL" << std::endl;
  2030. int sizeOfLUT ( 0 );
  2031. if ( q != NULL )
  2032. sizeOfLUT = q->getNumberOfBins() * this->fmk->get_d();
  2033. _os << sizeOfLUT << std::endl;
  2034. for ( int i = 0; i < sizeOfLUT; i++ )
  2035. {
  2036. _os << this->precomputedTForVarEst[i] << " ";
  2037. }
  2038. _os << std::endl;
  2039. }
  2040. else
  2041. {
  2042. _os << "NULL" << std::endl;
  2043. }
  2044. _os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  2045. /////////////////////////////////////////////////////
  2046. // online / incremental learning related variables //
  2047. /////////////////////////////////////////////////////
  2048. _os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  2049. _os << this->b_usePreviousAlphas << std::endl;
  2050. _os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  2051. _os << this->createStartTag( "previousAlphas" ) << std::endl;
  2052. _os << "size: " << this->previousAlphas.size() << std::endl;
  2053. std::map< uint, NICE::Vector >::const_iterator prevAlphaIt = this->previousAlphas.begin();
  2054. for ( uint i = 0; i < this->previousAlphas.size(); i++ )
  2055. {
  2056. _os << prevAlphaIt->first << std::endl;
  2057. _os << prevAlphaIt->second << std::endl;
  2058. prevAlphaIt++;
  2059. }
  2060. _os << this->createEndTag( "previousAlphas" ) << std::endl;
  2061. // done
  2062. _os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  2063. }
  2064. else
  2065. {
  2066. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  2067. }
  2068. }
  2069. void FMKGPHyperparameterOptimization::clear ( ) {};
  2070. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2071. // interface specific methods for incremental extensions
  2072. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2073. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  2074. const double & label,
  2075. const bool & performOptimizationAfterIncrement
  2076. )
  2077. {
  2078. if ( this->b_verbose )
  2079. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  2080. NICE::Timer t;
  2081. t.start();
  2082. std::set< uint > newClasses;
  2083. this->labels.append ( label );
  2084. //have we seen this class already?
  2085. if ( !this->b_performRegression && ( this->knownClasses.find( label ) == this->knownClasses.end() ) )
  2086. {
  2087. this->knownClasses.insert( label );
  2088. newClasses.insert( label );
  2089. }
  2090. // If we currently have been in a binary setting, we now have to take care
  2091. // that we also compute an alpha vector for the second class, which previously
  2092. // could be dealt with implicitely.
  2093. // Therefore, we insert its label here...
  2094. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2095. newClasses.insert( this->i_binaryLabelNegative );
  2096. // add the new example to our data structure
  2097. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2098. NICE::Timer tFmk;
  2099. tFmk.start();
  2100. this->fmk->addExample ( example, pf );
  2101. tFmk.stop();
  2102. if ( this->b_verboseTime)
  2103. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2104. // add examples to all implicite kernel matrices we currently use
  2105. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  2106. // update the corresponding matrices A, B and lookup tables T
  2107. // optional: do the optimization again using the previously known solutions as initialization
  2108. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2109. //clean up
  2110. newClasses.clear();
  2111. t.stop();
  2112. NICE::ResourceStatistics rs;
  2113. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2114. long maxMemory;
  2115. rs.getMaximumMemory ( maxMemory );
  2116. if ( this->b_verbose )
  2117. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2118. if ( this->b_verbose )
  2119. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  2120. }
  2121. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  2122. const NICE::Vector & newLabels,
  2123. const bool & performOptimizationAfterIncrement
  2124. )
  2125. {
  2126. if ( this->b_verbose )
  2127. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples --- " << std::endl;
  2128. NICE::Timer t;
  2129. t.start();
  2130. std::set< uint > newClasses;
  2131. this->labels.append ( newLabels );
  2132. //have we seen this class already?
  2133. if ( !this->b_performRegression)
  2134. {
  2135. for ( NICE::Vector::const_iterator vecIt = newLabels.begin();
  2136. vecIt != newLabels.end();
  2137. vecIt++
  2138. )
  2139. {
  2140. if ( this->knownClasses.find( *vecIt ) == this->knownClasses.end() )
  2141. {
  2142. this->knownClasses.insert( *vecIt );
  2143. newClasses.insert( *vecIt );
  2144. }
  2145. }
  2146. // If we currently have been in a OCC setting, and only add a single new class
  2147. // we have to take care that are still efficient, i.e., that we solve for alpha
  2148. // only ones, since scores are symmetric in binary cases
  2149. // Therefore, we remove the label of the secodn class from newClasses, to skip
  2150. // alpha computations for this class lateron...
  2151. //
  2152. // Therefore, we insert its label here...
  2153. if ( (newClasses.size() == 1 ) && ( (this->knownClasses.size() - newClasses.size() ) == 1 ) )
  2154. newClasses.clear();
  2155. // If we currently have been in a binary setting, we now have to take care
  2156. // that we also compute an alpha vector for the second class, which previously
  2157. // could be dealt with implicitely.
  2158. // Therefore, we insert its label here...
  2159. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2160. newClasses.insert( this->i_binaryLabelNegative );
  2161. }
  2162. // in a regression setting, we do not have to remember any "class labels"
  2163. else{}
  2164. // add the new example to our data structure
  2165. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2166. NICE::Timer tFmk;
  2167. tFmk.start();
  2168. this->fmk->addMultipleExamples ( newExamples, pf );
  2169. tFmk.stop();
  2170. if ( this->b_verboseTime)
  2171. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2172. // add examples to all implicite kernel matrices we currently use
  2173. this->ikmsum->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  2174. // update the corresponding matrices A, B and lookup tables T
  2175. // optional: do the optimization again using the previously known solutions as initialization
  2176. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2177. //clean up
  2178. newClasses.clear();
  2179. t.stop();
  2180. NICE::ResourceStatistics rs;
  2181. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2182. long maxMemory;
  2183. rs.getMaximumMemory ( maxMemory );
  2184. if ( this->b_verbose )
  2185. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2186. if ( this->b_verbose )
  2187. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples done --- " << std::endl;
  2188. }