FMKGPHyperparameterOptimization.cpp 68 KB

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