FMKGPHyperparameterOptimization.cpp 72 KB

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