FMKGPHyperparameterOptimization.cpp 69 KB

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