FMKGPHyperparameterOptimization.cpp 93 KB

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