FMKGPHyperparameterOptimization.cpp 66 KB

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