FMKGPHyperparameterOptimization.cpp 64 KB

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