FMKGPHyperparameterOptimization.cpp 71 KB

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