FMKGPHyperparameterOptimization.cpp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459
  1. /**
  2. * @file FMKGPHyperparameterOptimization.cpp
  3. * @brief Heart of the framework to set up everything, perform optimization, classification, and variance prediction (Implementation)
  4. * @author Erik Rodner, Alexander Freytag
  5. * @date 01/02/2012
  6. */
  7. // STL includes
  8. #include <iostream>
  9. #include <map>
  10. // NICE-core includes
  11. #include <core/algebra/ILSConjugateGradients.h>
  12. #include <core/algebra/ILSConjugateGradientsLanczos.h>
  13. #include <core/algebra/ILSSymmLqLanczos.h>
  14. #include <core/algebra/ILSMinResLanczos.h>
  15. #include <core/algebra/ILSPlainGradient.h>
  16. #include <core/algebra/EigValuesTRLAN.h>
  17. #include <core/algebra/CholeskyRobust.h>
  18. //
  19. #include <core/basics/Timer.h>
  20. #include <core/basics/ResourceStatistics.h>
  21. #include <core/basics/Exception.h>
  22. //
  23. #include <core/vector/Algorithms.h>
  24. #include <core/vector/Eigen.h>
  25. //
  26. #include <core/optimization/blackbox/DownhillSimplexOptimizer.h>
  27. // gp-hik-core includes
  28. #include "gp-hik-core/FMKGPHyperparameterOptimization.h"
  29. #include "gp-hik-core/FastMinKernel.h"
  30. #include "gp-hik-core/GMHIKernel.h"
  31. #include "gp-hik-core/IKMNoise.h"
  32. //
  33. #include "gp-hik-core/parameterizedFunctions/PFAbsExp.h"
  34. #include "gp-hik-core/parameterizedFunctions/PFExp.h"
  35. #include "gp-hik-core/parameterizedFunctions/PFMKL.h"
  36. using namespace NICE;
  37. using namespace std;
  38. /////////////////////////////////////////////////////
  39. /////////////////////////////////////////////////////
  40. // PROTECTED METHODS
  41. /////////////////////////////////////////////////////
  42. /////////////////////////////////////////////////////
  43. void FMKGPHyperparameterOptimization::updateAfterIncrement (
  44. const std::set < int > newClasses,
  45. const bool & performOptimizationAfterIncrement )
  46. {
  47. if ( this->fmk == NULL )
  48. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  49. std::map<int, NICE::Vector> binaryLabels;
  50. std::set<int> classesToUse;
  51. //TODO this could be made faster when storing the previous binary label vectors...
  52. if ( this->b_performRegression )
  53. {
  54. // for regression, we are not interested in regression scores, rather than in any "label"
  55. int regressionLabel ( 1 );
  56. binaryLabels.insert ( std::pair< int, NICE::Vector> ( regressionLabel, this->labels ) );
  57. }
  58. else
  59. this->prepareBinaryLabels ( binaryLabels, this->labels , classesToUse );
  60. if ( this->verbose )
  61. std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
  62. NICE::Timer t1;
  63. NICE::GPLikelihoodApprox * gplike;
  64. uint parameterVectorSize;
  65. t1.start();
  66. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  67. t1.stop();
  68. if ( this->verboseTime )
  69. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  70. t1.start();
  71. if ( this->b_usePreviousAlphas && ( this->previousAlphas.size() > 0) )
  72. {
  73. //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
  74. //default in GPLikelihoodApprox for the first time:
  75. // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
  76. double factor ( 1.0 / this->eigenMax[0] );
  77. std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
  78. for ( std::map<int, NICE::Vector>::iterator prevAlphaIt = this->previousAlphas.begin();
  79. prevAlphaIt != this->previousAlphas.end();
  80. prevAlphaIt++
  81. )
  82. {
  83. int oldSize ( prevAlphaIt->second.size() );
  84. prevAlphaIt->second.resize ( oldSize + 1 );
  85. if ( binaryLabelsIt->second[oldSize] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
  86. prevAlphaIt->second[oldSize] = factor;
  87. else
  88. prevAlphaIt->second[oldSize] = -factor; //we follow the initialization as done in previous steps
  89. //prevAlphaIt->second[oldSize] = 0.0; // following the suggestion of Yeh and Darrell
  90. binaryLabelsIt++;
  91. }
  92. //compute unaffected alpha-vectors for the new classes
  93. for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
  94. {
  95. NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
  96. previousAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
  97. }
  98. gplike->setInitialAlphaGuess ( &previousAlphas );
  99. }
  100. else
  101. {
  102. //if we do not use previous alphas, we do not have to set up anything here
  103. gplike->setInitialAlphaGuess ( NULL );
  104. }
  105. t1.stop();
  106. if ( this->verboseTime )
  107. std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
  108. if ( this->verbose )
  109. std::cerr << "update Eigendecomposition " << std::endl;
  110. t1.start();
  111. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  112. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  113. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  114. t1.stop();
  115. if ( this->verboseTime )
  116. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  117. ////////////////////// //////////////////////
  118. // RE-RUN THE OPTIMIZATION, IF DESIRED //
  119. ////////////////////// //////////////////////
  120. if ( this->verbose )
  121. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  122. // we can reuse the already given performOptimization-method:
  123. // OPT_GREEDY
  124. // for this strategy we can't reuse any of the previously computed scores
  125. // so come on, let's do the whole thing again...
  126. // OPT_DOWNHILLSIMPLEX
  127. // Here we can benefit from previous results, when we use them as initialization for our optimizer
  128. // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
  129. // as initialization
  130. // OPT_NONE
  131. // nothing to do, obviously
  132. if ( this->verbose )
  133. std::cerr << "perform optimization after increment " << std::endl;
  134. OPTIMIZATIONTECHNIQUE optimizationMethodTmpCopy;
  135. if ( !performOptimizationAfterIncrement )
  136. {
  137. // if no optimization shall be carried out, we simply set the optimization method to NONE but run the optimization
  138. // call nonetheless, thereby computing alpha vectors, etc. which would be not initialized
  139. optimizationMethodTmpCopy = this->optimizationMethod;
  140. this->optimizationMethod = OPT_NONE;
  141. }
  142. t1.start();
  143. this->performOptimization ( *gplike, parameterVectorSize);
  144. t1.stop();
  145. if ( this->verboseTime )
  146. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  147. if ( this->verbose )
  148. std::cerr << "Preparing after retraining for classification ..." << std::endl;
  149. t1.start();
  150. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  151. t1.stop();
  152. if ( this->verboseTime)
  153. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  154. if ( !performOptimizationAfterIncrement )
  155. {
  156. this->optimizationMethod = optimizationMethodTmpCopy;
  157. }
  158. //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
  159. // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
  160. // Since we are not aware of any such method, we have to compute them completely new
  161. // :/
  162. t1.start();
  163. this->computeMatricesAndLUTs ( *gplike );
  164. t1.stop();
  165. if ( this->verboseTime )
  166. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  167. //don't waste memory
  168. delete gplike;
  169. }
  170. /////////////////////////////////////////////////////
  171. /////////////////////////////////////////////////////
  172. // PUBLIC METHODS
  173. /////////////////////////////////////////////////////
  174. /////////////////////////////////////////////////////
  175. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization( )
  176. {
  177. // initialize pointer variables
  178. this->pf = NULL;
  179. this->eig = NULL;
  180. this->linsolver = NULL;
  181. this->fmk = NULL;
  182. this->q = NULL;
  183. this->precomputedTForVarEst = NULL;
  184. this->ikmsum = NULL;
  185. // initialize boolean flags
  186. this->verbose = false;
  187. this->verboseTime = false;
  188. this->debug = false;
  189. //stupid unneeded default values
  190. this->binaryLabelPositive = -1;
  191. this->binaryLabelNegative = -2;
  192. this->knownClasses.clear();
  193. this->b_usePreviousAlphas = false;
  194. this->b_performRegression = false;
  195. }
  196. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization( const bool & b_performRegression )
  197. {
  198. ///////////
  199. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  200. ///////////
  201. // initialize pointer variables
  202. this->pf = NULL;
  203. this->eig = NULL;
  204. this->linsolver = NULL;
  205. this->fmk = NULL;
  206. this->q = NULL;
  207. this->precomputedTForVarEst = NULL;
  208. this->ikmsum = NULL;
  209. // initialize boolean flags
  210. this->verbose = false;
  211. this->verboseTime = false;
  212. this->debug = false;
  213. //stupid unneeded default values
  214. this->binaryLabelPositive = -1;
  215. this->binaryLabelNegative = -2;
  216. this->knownClasses.clear();
  217. this->b_usePreviousAlphas = false;
  218. this->b_performRegression = false;
  219. ///////////
  220. // here comes the new code part different from the empty constructor
  221. ///////////
  222. this->b_performRegression = b_performRegression;
  223. }
  224. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, const string & _confSection )
  225. {
  226. ///////////
  227. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  228. ///////////
  229. // initialize pointer variables
  230. this->pf = NULL;
  231. this->eig = NULL;
  232. this->linsolver = NULL;
  233. this->fmk = NULL;
  234. this->q = NULL;
  235. this->precomputedTForVarEst = NULL;
  236. this->ikmsum = NULL;
  237. // initialize boolean flags
  238. this->verbose = false;
  239. this->verboseTime = false;
  240. this->debug = false;
  241. //stupid unneeded default values
  242. this->binaryLabelPositive = -1;
  243. this->binaryLabelNegative = -2;
  244. this->knownClasses.clear();
  245. this->b_usePreviousAlphas = false;
  246. this->b_performRegression = false;
  247. ///////////
  248. // here comes the new code part different from the empty constructor
  249. ///////////
  250. this->initFromConfig ( _conf, _confSection );
  251. }
  252. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, FastMinKernel *_fmk, const string & _confSection )
  253. {
  254. ///////////
  255. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  256. ///////////
  257. // initialize pointer variables
  258. this->pf = NULL;
  259. this->eig = NULL;
  260. this->linsolver = NULL;
  261. this->fmk = NULL;
  262. this->q = NULL;
  263. this->precomputedTForVarEst = NULL;
  264. this->ikmsum = NULL;
  265. // initialize boolean flags
  266. this->verbose = false;
  267. this->verboseTime = false;
  268. this->debug = false;
  269. //stupid unneeded default values
  270. this->binaryLabelPositive = -1;
  271. this->binaryLabelNegative = -2;
  272. this->knownClasses.clear();
  273. this->b_usePreviousAlphas = false;
  274. this->b_performRegression = false;
  275. ///////////
  276. // here comes the new code part different from the empty constructor
  277. ///////////
  278. this->initFromConfig ( _conf, _confSection );
  279. this->setFastMinKernel( _fmk );
  280. }
  281. FMKGPHyperparameterOptimization::~FMKGPHyperparameterOptimization()
  282. {
  283. //////////////////////////////////////
  284. // classification related variables //
  285. //////////////////////////////////////
  286. if ( this->fmk != NULL )
  287. delete this->fmk;
  288. if ( this->q != NULL )
  289. delete this->q;
  290. if ( this->pf != NULL )
  291. delete this->pf;
  292. for ( uint i = 0 ; i < this->precomputedT.size(); i++ )
  293. delete [] ( this->precomputedT[i] );
  294. if ( this->ikmsum != NULL )
  295. delete this->ikmsum;
  296. //////////////////////////////////////////////
  297. // Iterative Linear Solver //
  298. //////////////////////////////////////////////
  299. if ( this->linsolver != NULL )
  300. delete this->linsolver;
  301. //////////////////////////////////////////////
  302. // likelihood computation related variables //
  303. //////////////////////////////////////////////
  304. if ( this->eig != NULL )
  305. delete this->eig;
  306. ////////////////////////////////////////////
  307. // variance computation related variables //
  308. ////////////////////////////////////////////
  309. if ( this->precomputedTForVarEst != NULL )
  310. delete this->precomputedTForVarEst;
  311. }
  312. void FMKGPHyperparameterOptimization::initFromConfig ( const Config *_conf, const std::string & _confSection )
  313. {
  314. ///////////////////////////////////
  315. // output/debug related settings //
  316. ///////////////////////////////////
  317. this->verbose = _conf->gB ( _confSection, "verbose", false );
  318. this->verboseTime = _conf->gB ( _confSection, "verboseTime", false );
  319. this->debug = _conf->gB ( _confSection, "debug", false );
  320. if ( verbose )
  321. {
  322. std::cerr << "------------" << std::endl;
  323. std::cerr << "| set-up |" << std::endl;
  324. std::cerr << "------------" << std::endl;
  325. }
  326. //////////////////////////////////////
  327. // classification related variables //
  328. //////////////////////////////////////
  329. this->b_performRegression = _conf->gB ( _confSection, "b_performRegression", false );
  330. bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
  331. if ( verbose )
  332. {
  333. std::cerr << "_confSection: " << _confSection << std::endl;
  334. std::cerr << "use_quantization: " << useQuantization << std::endl;
  335. }
  336. if ( _conf->gB ( _confSection, "use_quantization", false ) )
  337. {
  338. int numBins = _conf->gI ( _confSection, "num_bins", 100 );
  339. if ( verbose )
  340. std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
  341. this->q = new Quantization ( numBins );
  342. }
  343. else
  344. {
  345. this->q = NULL;
  346. }
  347. this->parameterUpperBound = _conf->gD ( _confSection, "parameter_upper_bound", 2.5 );
  348. this->parameterLowerBound = _conf->gD ( _confSection, "parameter_lower_bound", 1.0 );
  349. std::string transform = _conf->gS( _confSection, "transform", "absexp" );
  350. if ( transform == "absexp" )
  351. {
  352. this->pf = new NICE::PFAbsExp( 1.0, parameterLowerBound, parameterUpperBound );
  353. }
  354. else if ( transform == "exp" )
  355. {
  356. this->pf = new NICE::PFExp( 1.0, parameterLowerBound, parameterUpperBound );
  357. }
  358. else if ( transform == "MKL" )
  359. {
  360. //TODO generic, please :) load from a separate file or something like this!
  361. std::set<int> steps; steps.insert(4000); steps.insert(6000); //specific for VISAPP
  362. this->pf = new NICE::PFMKL( steps, parameterLowerBound, parameterUpperBound );
  363. }
  364. else
  365. {
  366. fthrow(Exception, "Transformation type is unknown " << transform);
  367. }
  368. //////////////////////////////////////////////
  369. // Iterative Linear Solver //
  370. //////////////////////////////////////////////
  371. bool ils_verbose = _conf->gB ( _confSection, "ils_verbose", false );
  372. ils_max_iterations = _conf->gI ( _confSection, "ils_max_iterations", 1000 );
  373. if ( verbose )
  374. std::cerr << "FMKGPHyperparameterOptimization: maximum number of iterations is " << ils_max_iterations << std::endl;
  375. double ils_min_delta = _conf->gD ( _confSection, "ils_min_delta", 1e-7 );
  376. double ils_min_residual = _conf->gD ( _confSection, "ils_min_residual", 1e-7/*1e-2 */ );
  377. string ils_method = _conf->gS ( _confSection, "ils_method", "CG" );
  378. if ( ils_method.compare ( "CG" ) == 0 )
  379. {
  380. if ( verbose )
  381. 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;
  382. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  383. if ( verbose )
  384. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients" << std::endl;
  385. }
  386. else if ( ils_method.compare ( "CGL" ) == 0 )
  387. {
  388. this->linsolver = new ILSConjugateGradientsLanczos ( ils_verbose , ils_max_iterations );
  389. if ( verbose )
  390. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients (Lanczos)" << std::endl;
  391. }
  392. else if ( ils_method.compare ( "SYMMLQ" ) == 0 )
  393. {
  394. this->linsolver = new ILSSymmLqLanczos ( ils_verbose , ils_max_iterations );
  395. if ( verbose )
  396. std::cerr << "FMKGPHyperparameterOptimization: using ILS SYMMLQ" << std::endl;
  397. }
  398. else if ( ils_method.compare ( "MINRES" ) == 0 )
  399. {
  400. this->linsolver = new ILSMinResLanczos ( ils_verbose , ils_max_iterations );
  401. if ( verbose )
  402. std::cerr << "FMKGPHyperparameterOptimization: using ILS MINRES" << std::endl;
  403. }
  404. else
  405. {
  406. std::cerr << "FMKGPHyperparameterOptimization: " << _confSection << ":ils_method (" << ils_method << ") does not match any type (CG,CGL,SYMMLQ,MINRES), I will use CG" << std::endl;
  407. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  408. }
  409. /////////////////////////////////////
  410. // optimization related parameters //
  411. /////////////////////////////////////
  412. std::string optimizationMethod_s = _conf->gS ( _confSection, "optimization_method", "greedy" );
  413. if ( optimizationMethod_s == "greedy" )
  414. optimizationMethod = OPT_GREEDY;
  415. else if ( optimizationMethod_s == "downhillsimplex" )
  416. optimizationMethod = OPT_DOWNHILLSIMPLEX;
  417. else if ( optimizationMethod_s == "none" )
  418. optimizationMethod = OPT_NONE;
  419. else
  420. fthrow ( Exception, "Optimization method " << optimizationMethod_s << " is not known." );
  421. if ( verbose )
  422. std::cerr << "Using optimization method: " << optimizationMethod_s << std::endl;
  423. this->parameterStepSize = _conf->gD ( _confSection, "parameter_step_size", 0.1 );
  424. optimizeNoise = _conf->gB ( _confSection, "optimize_noise", false );
  425. if ( verbose )
  426. std::cerr << "Optimize noise: " << ( optimizeNoise ? "on" : "off" ) << std::endl;
  427. downhillSimplexMaxIterations = _conf->gI ( _confSection, "downhillsimplex_max_iterations", 20 );
  428. // do not run longer than a day :)
  429. downhillSimplexTimeLimit = _conf->gD ( _confSection, "downhillsimplex_time_limit", 24 * 60 * 60 );
  430. downhillSimplexParamTol = _conf->gD ( _confSection, "downhillsimplex_delta", 0.01 );
  431. //////////////////////////////////////////////
  432. // likelihood computation related variables //
  433. //////////////////////////////////////////////
  434. this->verifyApproximation = _conf->gB ( _confSection, "verify_approximation", false );
  435. // this->eig = new EigValuesTRLAN();
  436. // My time measurements show that both methods use equal time, a comparision
  437. // of their numerical performance has not been done yet
  438. this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */, 10 );
  439. this->nrOfEigenvaluesToConsider = _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 );
  440. ////////////////////////////////////////////
  441. // variance computation related variables //
  442. ////////////////////////////////////////////
  443. this->nrOfEigenvaluesToConsiderForVarApprox = _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 );
  444. /////////////////////////////////////////////////////
  445. // online / incremental learning related variables //
  446. /////////////////////////////////////////////////////
  447. this->b_usePreviousAlphas = _conf->gB ( _confSection, "b_usePreviousAlphas", true );
  448. if ( verbose )
  449. {
  450. std::cerr << "------------" << std::endl;
  451. std::cerr << "| start |" << std::endl;
  452. std::cerr << "------------" << std::endl;
  453. }
  454. }
  455. ///////////////////// ///////////////////// /////////////////////
  456. // GET / SET
  457. ///////////////////// ///////////////////// /////////////////////
  458. void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
  459. {
  460. parameterUpperBound = _parameterUpperBound;
  461. }
  462. void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
  463. {
  464. parameterLowerBound = _parameterLowerBound;
  465. }
  466. std::set<int> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
  467. {
  468. return this->knownClasses;
  469. }
  470. void FMKGPHyperparameterOptimization::setPerformRegression ( const bool & b_performRegression )
  471. {
  472. //TODO check previously whether we already trained
  473. if ( false )
  474. throw NICE::Exception ( "FMPGKHyperparameterOptimization already initialized - switching between classification and regression not allowed!" );
  475. else
  476. this->b_performRegression = b_performRegression;
  477. }
  478. void FMKGPHyperparameterOptimization::setFastMinKernel ( FastMinKernel * _fmk )
  479. {
  480. //TODO check previously whether we already trained
  481. if ( _fmk != NULL )
  482. {
  483. if ( this->fmk != NULL )
  484. {
  485. delete this->fmk;
  486. this->fmk = NULL;
  487. }
  488. this->fmk = _fmk;
  489. }
  490. }
  491. void FMKGPHyperparameterOptimization::setNrOfEigenvaluesToConsiderForVarApprox ( const int & i_nrOfEigenvaluesToConsiderForVarApprox )
  492. {
  493. //TODO check previously whether we already trained
  494. this->nrOfEigenvaluesToConsiderForVarApprox = i_nrOfEigenvaluesToConsiderForVarApprox;
  495. }
  496. ///////////////////// ///////////////////// /////////////////////
  497. // CLASSIFIER STUFF
  498. ///////////////////// ///////////////////// /////////////////////
  499. inline void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize )
  500. {
  501. gplike = new GPLikelihoodApprox ( binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
  502. gplike->setDebug( debug );
  503. gplike->setVerbose( verbose );
  504. parameterVectorSize = ikmsum->getNumParameters();
  505. }
  506. void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & i_noEigenValues )
  507. {
  508. //compute the largest eigenvalue of K + noise
  509. try
  510. {
  511. eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, i_noEigenValues );
  512. }
  513. catch ( char const* exceptionMsg)
  514. {
  515. std::cerr << exceptionMsg << std::endl;
  516. throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
  517. }
  518. //NOTE EigenValue computation extracts EV and EW per default in decreasing order.
  519. }
  520. void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  521. {
  522. if (verbose)
  523. std::cerr << "perform optimization" << std::endl;
  524. if ( optimizationMethod == OPT_GREEDY )
  525. {
  526. if ( verbose )
  527. std::cerr << "OPT_GREEDY!!! " << std::endl;
  528. // simple greedy strategy
  529. if ( ikmsum->getNumParameters() != 1 )
  530. fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
  531. NICE::Vector lB = ikmsum->getParameterLowerBounds();
  532. NICE::Vector uB = ikmsum->getParameterUpperBounds();
  533. if ( verbose )
  534. std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
  535. for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
  536. {
  537. OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
  538. gplike.evaluate ( hyperp );
  539. }
  540. }
  541. else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
  542. {
  543. //standard as before, normal optimization
  544. if ( verbose )
  545. std::cerr << "DOWNHILLSIMPLEX!!! " << std::endl;
  546. // downhill simplex strategy
  547. OPTIMIZATION::DownhillSimplexOptimizer optimizer;
  548. OPTIMIZATION::matrix_type initialParams ( parameterVectorSize, 1 );
  549. NICE::Vector currentParameters;
  550. ikmsum->getParameters ( currentParameters );
  551. for ( uint i = 0 ; i < parameterVectorSize; i++ )
  552. initialParams(i,0) = currentParameters[ i ];
  553. if ( verbose )
  554. std::cerr << "Initial parameters: " << initialParams << std::endl;
  555. //the scales object does not really matter in the actual implementation of Downhill Simplex
  556. // OPTIMIZATION::matrix_type scales ( parameterVectorSize, 1);
  557. // scales.set(1.0);
  558. OPTIMIZATION::SimpleOptProblem optProblem ( &gplike, initialParams, initialParams /* scales */ );
  559. optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
  560. optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
  561. optimizer.setParamTol ( true, downhillSimplexParamTol );
  562. optimizer.optimizeProb ( optProblem );
  563. }
  564. else if ( optimizationMethod == OPT_NONE )
  565. {
  566. if ( verbose )
  567. std::cerr << "NO OPTIMIZATION!!! " << std::endl;
  568. // without optimization
  569. if ( optimizeNoise )
  570. fthrow ( Exception, "Deactivate optimize_noise!" );
  571. if ( verbose )
  572. std::cerr << "Optimization is deactivated!" << std::endl;
  573. double value (1.0);
  574. if ( this->parameterLowerBound == this->parameterUpperBound)
  575. value = this->parameterLowerBound;
  576. pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
  577. pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
  578. // we use the standard value
  579. OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
  580. gplike.setParameterLowerBound ( value );
  581. gplike.setParameterUpperBound ( value );
  582. //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
  583. gplike.computeAlphaDirect( hyperp, eigenMax );
  584. }
  585. if ( verbose )
  586. {
  587. std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
  588. }
  589. }
  590. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  591. {
  592. // transform all features with the currently "optimal" parameter
  593. ikmsum->setParameters ( gplike.getBestParameters() );
  594. }
  595. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
  596. {
  597. precomputedA.clear();
  598. precomputedB.clear();
  599. for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
  600. {
  601. PrecomputedType A;
  602. PrecomputedType B;
  603. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  604. A.setIoUntilEndOfFile ( false );
  605. B.setIoUntilEndOfFile ( false );
  606. precomputedA[ i->first ] = A;
  607. precomputedB[ i->first ] = B;
  608. if ( q != NULL )
  609. {
  610. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
  611. //just to be sure that we do not waste space here
  612. if ( precomputedT[ i->first ] != NULL )
  613. delete precomputedT[ i->first ];
  614. precomputedT[ i->first ] = T;
  615. }
  616. }
  617. if ( this->precomputedTForVarEst != NULL )
  618. {
  619. this->prepareVarianceApproximationRough();
  620. }
  621. else if ( this->nrOfEigenvaluesToConsiderForVarApprox > 0)
  622. {
  623. this->prepareVarianceApproximationFine();
  624. }
  625. // in case that we should want to store the alpha vectors for incremental extensions
  626. if ( this->b_usePreviousAlphas )
  627. this->previousAlphas = gplike.getBestAlphas();
  628. }
  629. #ifdef NICE_USELIB_MATIO
  630. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
  631. {
  632. std::map<int, int> examples;
  633. NICE::Vector y ( yl.size() );
  634. int ind = 0;
  635. for ( uint i = 0 ; i < yl.size(); i++ )
  636. {
  637. if ( positives.find ( i ) != positives.end() ) {
  638. y[ examples.size() ] = 1.0;
  639. examples.insert ( pair<int, int> ( i, ind ) );
  640. ind++;
  641. } else if ( negatives.find ( i ) != negatives.end() ) {
  642. y[ examples.size() ] = -1.0;
  643. examples.insert ( pair<int, int> ( i, ind ) );
  644. ind++;
  645. }
  646. }
  647. y.resize ( examples.size() );
  648. std::cerr << "Examples: " << examples.size() << std::endl;
  649. optimize ( data, y, examples, noise );
  650. }
  651. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
  652. {
  653. NICE::Timer t;
  654. t.start();
  655. std::cerr << "Initializing data structure ..." << std::endl;
  656. if ( fmk != NULL ) delete fmk;
  657. fmk = new FastMinKernel ( data, noise, examples );
  658. t.stop();
  659. if (verboseTime)
  660. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  661. optimize ( y );
  662. }
  663. #endif
  664. int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
  665. {
  666. myClasses.clear();
  667. // determine which classes we have in our label vector
  668. // -> MATLAB: myClasses = unique(y);
  669. for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
  670. {
  671. if ( myClasses.find ( *it ) == myClasses.end() )
  672. {
  673. myClasses.insert ( *it );
  674. }
  675. }
  676. //count how many different classes appear in our data
  677. int nrOfClasses = myClasses.size();
  678. binaryLabels.clear();
  679. //compute the corresponding binary label vectors
  680. if ( nrOfClasses > 2 )
  681. {
  682. //resize every labelVector and set all entries to -1.0
  683. for ( set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
  684. {
  685. binaryLabels[ *k ].resize ( y.size() );
  686. binaryLabels[ *k ].set ( -1.0 );
  687. }
  688. // now look on every example and set the entry of its corresponding label vector to 1.0
  689. // proper existance should not be a problem
  690. for ( int i = 0 ; i < ( int ) y.size(); i++ )
  691. binaryLabels[ y[i] ][i] = 1.0;
  692. }
  693. else if ( nrOfClasses == 2 )
  694. {
  695. //binary setting -- prepare two binary label vectors with opposite signs
  696. NICE::Vector yb ( y );
  697. binaryLabelNegative = *(myClasses.begin());
  698. std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
  699. binaryLabelPositive = *classIt;
  700. if ( verbose )
  701. std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
  702. for ( uint i = 0 ; i < yb.size() ; i++ )
  703. yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
  704. binaryLabels[ binaryLabelPositive ] = yb;
  705. //we do NOT do real binary computation, but an implicite one with only a single object
  706. nrOfClasses--;
  707. }
  708. else //OCC setting
  709. {
  710. //we set the labels to 1, independent of the previously given class number
  711. //however, the original class numbers are stored and returned in classification
  712. NICE::Vector yOne ( y.size(), 1 );
  713. binaryLabels[ *(myClasses.begin()) ] = yOne;
  714. //we have to indicate, that we are in an OCC setting
  715. nrOfClasses--;
  716. }
  717. return nrOfClasses;
  718. }
  719. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
  720. {
  721. if ( fmk == NULL )
  722. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  723. this->labels = y;
  724. std::map<int, NICE::Vector> binaryLabels;
  725. if ( this->b_performRegression )
  726. {
  727. // for regression, we are not interested in regression scores, rather than in any "label"
  728. int regressionLabel ( 1 );
  729. binaryLabels.insert ( std::pair< int, NICE::Vector> ( regressionLabel, y ) );
  730. this->knownClasses.clear();
  731. this->knownClasses.insert ( regressionLabel );
  732. }
  733. else
  734. {
  735. this->prepareBinaryLabels ( binaryLabels, y , knownClasses );
  736. }
  737. //now call the main function :)
  738. this->optimize(binaryLabels);
  739. }
  740. void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
  741. {
  742. Timer t;
  743. t.start();
  744. //how many different classes do we have right now?
  745. int nrOfClasses = binaryLabels.size();
  746. if (verbose)
  747. {
  748. std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
  749. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  750. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
  751. }
  752. // combine standard model and noise model
  753. Timer t1;
  754. t1.start();
  755. //setup the kernel combination
  756. ikmsum = new IKMLinearCombination ();
  757. if ( verbose )
  758. {
  759. std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  760. }
  761. //First model: noise
  762. ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
  763. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  764. fmk->setNoise ( 0.0 );
  765. ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
  766. t1.stop();
  767. if (verboseTime)
  768. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  769. GPLikelihoodApprox * gplike;
  770. uint parameterVectorSize;
  771. t1.start();
  772. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  773. t1.stop();
  774. if (verboseTime)
  775. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  776. if (verbose)
  777. {
  778. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  779. }
  780. t1.start();
  781. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  782. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  783. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  784. t1.stop();
  785. if (verboseTime)
  786. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  787. if ( verbose )
  788. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  789. t1.start();
  790. this->performOptimization ( *gplike, parameterVectorSize );
  791. t1.stop();
  792. if (verboseTime)
  793. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  794. if ( verbose )
  795. std::cerr << "Preparing classification ..." << std::endl;
  796. t1.start();
  797. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  798. t1.stop();
  799. if (verboseTime)
  800. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  801. t1.start();
  802. this->computeMatricesAndLUTs ( *gplike );
  803. t1.stop();
  804. if (verboseTime)
  805. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  806. t.stop();
  807. ResourceStatistics rs;
  808. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  809. long maxMemory;
  810. rs.getMaximumMemory ( maxMemory );
  811. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  812. //don't waste memory
  813. delete gplike;
  814. }
  815. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  816. {
  817. PrecomputedType AVar;
  818. fmk->hikPrepareKVNApproximation ( AVar );
  819. precomputedAForVarEst = AVar;
  820. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  821. if ( q != NULL )
  822. {
  823. double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
  824. this->precomputedTForVarEst = T;
  825. }
  826. }
  827. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  828. {
  829. if ( this->eigenMax.size() < (uint) this->nrOfEigenvaluesToConsiderForVarApprox )
  830. {
  831. std::cerr << "not enough eigenvectors computed for fine approximation of predictive variance. " <<std::endl;
  832. std::cerr << "Current number of EV: " << this->eigenMax.size() << " but required: " << (uint) this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  833. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  834. }
  835. }
  836. int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
  837. {
  838. // loop through all classes
  839. if ( precomputedA.size() == 0 )
  840. {
  841. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  842. }
  843. uint maxClassNo = 0;
  844. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  845. {
  846. uint classno = i->first;
  847. maxClassNo = std::max ( maxClassNo, classno );
  848. double beta;
  849. if ( q != NULL ) {
  850. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  851. double *T = j->second;
  852. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  853. } else {
  854. const PrecomputedType & A = i->second;
  855. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  856. const PrecomputedType & B = j->second;
  857. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  858. // Giving the transformation pf as an additional
  859. // argument is necessary due to the following reason:
  860. // FeatureMatrixT is sorted according to the original values, therefore,
  861. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  862. // values as inputs. However, for calculation we need the transformed features values.
  863. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  864. }
  865. scores[ classno ] = beta;
  866. }
  867. scores.setDim ( maxClassNo + 1 );
  868. if ( precomputedA.size() > 1 )
  869. { // multi-class classification
  870. return scores.maxElement();
  871. }
  872. else if ( this->knownClasses.size() == 2 ) // binary setting
  873. {
  874. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  875. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  876. }
  877. else //OCC or regression setting
  878. {
  879. return 1;
  880. }
  881. }
  882. int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
  883. {
  884. // loop through all classes
  885. if ( precomputedA.size() == 0 )
  886. {
  887. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  888. }
  889. uint maxClassNo = 0;
  890. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  891. {
  892. uint classno = i->first;
  893. maxClassNo = std::max ( maxClassNo, classno );
  894. double beta;
  895. if ( q != NULL ) {
  896. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  897. double *T = j->second;
  898. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  899. } else {
  900. const PrecomputedType & A = i->second;
  901. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  902. const PrecomputedType & B = j->second;
  903. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  904. // Giving the transformation pf as an additional
  905. // argument is necessary due to the following reason:
  906. // FeatureMatrixT is sorted according to the original values, therefore,
  907. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  908. // values as inputs. However, for calculation we need the transformed features values.
  909. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  910. }
  911. scores[ classno ] = beta;
  912. }
  913. scores.setDim ( maxClassNo + 1 );
  914. if ( precomputedA.size() > 1 )
  915. { // multi-class classification
  916. return scores.maxElement();
  917. }
  918. else if ( this->knownClasses.size() == 2 ) // binary setting
  919. {
  920. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  921. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  922. }
  923. else //OCC or regression setting
  924. {
  925. return 1;
  926. }
  927. }
  928. //////////////////////////////////////////
  929. // variance computation: sparse inputs
  930. //////////////////////////////////////////
  931. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
  932. {
  933. // security check!
  934. if ( pf == NULL )
  935. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  936. // ---------------- compute the first term --------------------
  937. double kSelf ( 0.0 );
  938. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  939. {
  940. kSelf += pf->f ( 0, it->second );
  941. // if weighted dimensions:
  942. //kSelf += pf->f(it->first,it->second);
  943. }
  944. // ---------------- compute the approximation of the second term --------------------
  945. double normKStar;
  946. if ( q != NULL )
  947. {
  948. if ( precomputedTForVarEst == NULL )
  949. {
  950. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  951. }
  952. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  953. }
  954. else
  955. {
  956. if ( precomputedAForVarEst.size () == 0 )
  957. {
  958. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  959. }
  960. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  961. }
  962. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  963. }
  964. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
  965. {
  966. // security check!
  967. if ( eigenMaxVectors.rows() == 0 )
  968. {
  969. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  970. }
  971. // ---------------- compute the first term --------------------
  972. // Timer t;
  973. // t.start();
  974. double kSelf ( 0.0 );
  975. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  976. {
  977. kSelf += pf->f ( 0, it->second );
  978. // if weighted dimensions:
  979. //kSelf += pf->f(it->first,it->second);
  980. }
  981. // ---------------- compute the approximation of the second term --------------------
  982. // t.stop();
  983. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  984. // t.start();
  985. NICE::Vector kStar;
  986. fmk->hikComputeKernelVector ( x, kStar );
  987. /* t.stop();
  988. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  989. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  990. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  991. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  992. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  993. //wherefor it takes aeons...
  994. //so we compute it by ourselves
  995. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  996. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  997. // double kStarI ( kStar[tmpI] );
  998. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  999. {
  1000. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1001. {
  1002. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1003. }
  1004. }
  1005. double projectionLength ( 0.0 );
  1006. double currentSecondTerm ( 0.0 );
  1007. double sumOfProjectionLengths ( 0.0 );
  1008. int cnt ( 0 );
  1009. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1010. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1011. {
  1012. projectionLength = ( *it );
  1013. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1014. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1015. it++;
  1016. cnt++;
  1017. }
  1018. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1019. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1020. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1021. {
  1022. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1023. }
  1024. predVariance = kSelf - currentSecondTerm;
  1025. }
  1026. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1027. {
  1028. // security check!
  1029. if ( ikmsum->getNumberOfModels() == 0 )
  1030. {
  1031. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1032. }
  1033. Timer t;
  1034. // t.start();
  1035. // ---------------- compute the first term --------------------
  1036. double kSelf ( 0.0 );
  1037. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1038. {
  1039. kSelf += pf->f ( 0, it->second );
  1040. // if weighted dimensions:
  1041. //kSelf += pf->f(it->first,it->second);
  1042. }
  1043. // ---------------- compute the second term --------------------
  1044. NICE::Vector kStar;
  1045. fmk->hikComputeKernelVector ( x, kStar );
  1046. //now run the ILS method
  1047. NICE::Vector diagonalElements;
  1048. ikmsum->getDiagonalElements ( diagonalElements );
  1049. // init simple jacobi pre-conditioning
  1050. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1051. //TODO what to do for other solver techniques?
  1052. //perform pre-conditioning
  1053. if ( linsolver_cg != NULL )
  1054. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1055. NICE::Vector beta;
  1056. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1057. * K~ = K + sigma^2 I
  1058. *
  1059. * K~ \approx lambda_max v v^T
  1060. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1061. * => \lambda_max v^T alpha = v^T k_*
  1062. * => alpha = k_* / lambda_max could be a good initial start
  1063. * If we put everything in the first equation this gives us
  1064. * v = k_*
  1065. * This reduces the number of iterations by 5 or 8
  1066. */
  1067. beta = (kStar * (1.0 / eigenMax[0]) );
  1068. linsolver->solveLin ( *ikmsum, kStar, beta );
  1069. beta *= kStar;
  1070. double currentSecondTerm( beta.Sum() );
  1071. predVariance = kSelf - currentSecondTerm;
  1072. }
  1073. //////////////////////////////////////////
  1074. // variance computation: non-sparse inputs
  1075. //////////////////////////////////////////
  1076. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1077. {
  1078. // security check!
  1079. if ( pf == NULL )
  1080. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1081. // ---------------- compute the first term --------------------
  1082. double kSelf ( 0.0 );
  1083. int dim ( 0 );
  1084. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1085. {
  1086. kSelf += pf->f ( 0, *it );
  1087. // if weighted dimensions:
  1088. //kSelf += pf->f(dim,*it);
  1089. }
  1090. // ---------------- compute the approximation of the second term --------------------
  1091. double normKStar;
  1092. if ( q != NULL )
  1093. {
  1094. if ( precomputedTForVarEst == NULL )
  1095. {
  1096. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1097. }
  1098. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  1099. }
  1100. else
  1101. {
  1102. if ( precomputedAForVarEst.size () == 0 )
  1103. {
  1104. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1105. }
  1106. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  1107. }
  1108. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1109. }
  1110. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
  1111. {
  1112. // security check!
  1113. if ( eigenMaxVectors.rows() == 0 )
  1114. {
  1115. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1116. }
  1117. // ---------------- compute the first term --------------------
  1118. double kSelf ( 0.0 );
  1119. int dim ( 0 );
  1120. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1121. {
  1122. kSelf += pf->f ( 0, *it );
  1123. // if weighted dimensions:
  1124. //kSelf += pf->f(dim,*it);
  1125. }
  1126. // ---------------- compute the approximation of the second term --------------------
  1127. NICE::Vector kStar;
  1128. fmk->hikComputeKernelVector ( x, kStar );
  1129. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1130. //wherefor it takes aeons...
  1131. //so we compute it by ourselves
  1132. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1133. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1134. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1135. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  1136. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1137. {
  1138. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1139. {
  1140. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1141. }
  1142. }
  1143. double projectionLength ( 0.0 );
  1144. double currentSecondTerm ( 0.0 );
  1145. double sumOfProjectionLengths ( 0.0 );
  1146. int cnt ( 0 );
  1147. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1148. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1149. {
  1150. projectionLength = ( *it );
  1151. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1152. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1153. it++;
  1154. cnt++;
  1155. }
  1156. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1157. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1158. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1159. {
  1160. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1161. }
  1162. predVariance = kSelf - currentSecondTerm;
  1163. }
  1164. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & x, double & predVariance ) const
  1165. {
  1166. if ( ikmsum->getNumberOfModels() == 0 )
  1167. {
  1168. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1169. }
  1170. // ---------------- compute the first term --------------------
  1171. double kSelf ( 0.0 );
  1172. int dim ( 0 );
  1173. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1174. {
  1175. kSelf += pf->f ( 0, *it );
  1176. // if weighted dimensions:
  1177. //kSelf += pf->f(dim,*it);
  1178. }
  1179. // ---------------- compute the second term --------------------
  1180. NICE::Vector kStar;
  1181. fmk->hikComputeKernelVector ( x, kStar );
  1182. //now run the ILS method
  1183. NICE::Vector diagonalElements;
  1184. ikmsum->getDiagonalElements ( diagonalElements );
  1185. // init simple jacobi pre-conditioning
  1186. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1187. //perform pre-conditioning
  1188. if ( linsolver_cg != NULL )
  1189. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1190. NICE::Vector beta;
  1191. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1192. * K~ = K + sigma^2 I
  1193. *
  1194. * K~ \approx lambda_max v v^T
  1195. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1196. * => \lambda_max v^T alpha = v^T k_*
  1197. * => alpha = k_* / lambda_max could be a good initial start
  1198. * If we put everything in the first equation this gives us
  1199. * v = k_*
  1200. * This reduces the number of iterations by 5 or 8
  1201. */
  1202. beta = (kStar * (1.0 / eigenMax[0]) );
  1203. linsolver->solveLin ( *ikmsum, kStar, beta );
  1204. beta *= kStar;
  1205. double currentSecondTerm( beta.Sum() );
  1206. predVariance = kSelf - currentSecondTerm;
  1207. }
  1208. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1209. // interface specific methods for store and restore
  1210. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1211. void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
  1212. {
  1213. bool b_restoreVerbose ( false );
  1214. #ifdef B_RESTOREVERBOSE
  1215. b_restoreVerbose = true;
  1216. #endif
  1217. if ( is.good() )
  1218. {
  1219. if ( b_restoreVerbose )
  1220. std::cerr << " in FMKGP restore" << std::endl;
  1221. std::string tmp;
  1222. is >> tmp; //class name
  1223. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1224. {
  1225. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1226. throw;
  1227. }
  1228. if (fmk != NULL)
  1229. {
  1230. delete fmk;
  1231. fmk = NULL;
  1232. }
  1233. if ( ikmsum != NULL )
  1234. {
  1235. delete ikmsum;
  1236. }
  1237. ikmsum = new IKMLinearCombination ();
  1238. if ( b_restoreVerbose )
  1239. std::cerr << "ikmsum object created" << std::endl;
  1240. is.precision ( numeric_limits<double>::digits10 + 1 );
  1241. bool b_endOfBlock ( false ) ;
  1242. while ( !b_endOfBlock )
  1243. {
  1244. is >> tmp; // start of block
  1245. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1246. {
  1247. b_endOfBlock = true;
  1248. continue;
  1249. }
  1250. tmp = this->removeStartTag ( tmp );
  1251. if ( b_restoreVerbose )
  1252. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1253. ///////////////////////////////////
  1254. // output/debug related settings //
  1255. ///////////////////////////////////
  1256. if ( tmp.compare("verbose") == 0 )
  1257. {
  1258. is >> verbose;
  1259. is >> tmp; // end of block
  1260. tmp = this->removeEndTag ( tmp );
  1261. }
  1262. else if ( tmp.compare("verboseTime") == 0 )
  1263. {
  1264. is >> verboseTime;
  1265. is >> tmp; // end of block
  1266. tmp = this->removeEndTag ( tmp );
  1267. }
  1268. else if ( tmp.compare("debug") == 0 )
  1269. {
  1270. is >> debug;
  1271. is >> tmp; // end of block
  1272. tmp = this->removeEndTag ( tmp );
  1273. }
  1274. //////////////////////////////////////
  1275. // classification related variables //
  1276. //////////////////////////////////////
  1277. else if ( tmp.compare("b_performRegression") == 0 )
  1278. {
  1279. is >> b_performRegression;
  1280. is >> tmp; // end of block
  1281. tmp = this->removeEndTag ( tmp );
  1282. }
  1283. else if ( tmp.compare("fmk") == 0 )
  1284. {
  1285. if ( fmk != NULL )
  1286. delete fmk;
  1287. fmk = new FastMinKernel();
  1288. fmk->restore( is, format );
  1289. is >> tmp; // end of block
  1290. tmp = this->removeEndTag ( tmp );
  1291. }
  1292. else if ( tmp.compare("q") == 0 )
  1293. {
  1294. std::string isNull;
  1295. is >> isNull; // NOTNULL or NULL
  1296. if (isNull.compare("NOTNULL") == 0)
  1297. {
  1298. if ( q != NULL )
  1299. delete q;
  1300. q = new Quantization();
  1301. q->restore ( is, format );
  1302. }
  1303. else
  1304. {
  1305. if ( q != NULL )
  1306. delete q;
  1307. q = NULL;
  1308. }
  1309. is >> tmp; // end of block
  1310. tmp = this->removeEndTag ( tmp );
  1311. }
  1312. else if ( tmp.compare("parameterUpperBound") == 0 )
  1313. {
  1314. is >> parameterUpperBound;
  1315. is >> tmp; // end of block
  1316. tmp = this->removeEndTag ( tmp );
  1317. }
  1318. else if ( tmp.compare("parameterLowerBound") == 0 )
  1319. {
  1320. is >> parameterLowerBound;
  1321. is >> tmp; // end of block
  1322. tmp = this->removeEndTag ( tmp );
  1323. }
  1324. else if ( tmp.compare("pf") == 0 )
  1325. {
  1326. is >> tmp; // start of block
  1327. if ( this->isEndTag( tmp, "pf" ) )
  1328. {
  1329. std::cerr << " ParameterizedFunction object can not be restored. Aborting..." << std::endl;
  1330. throw;
  1331. }
  1332. std::string transform = this->removeStartTag ( tmp );
  1333. if ( transform == "PFAbsExp" )
  1334. {
  1335. this->pf = new PFAbsExp ();
  1336. } else if ( transform == "PFExp" ) {
  1337. this->pf = new PFExp ();
  1338. } else {
  1339. fthrow(Exception, "Transformation type is unknown " << transform);
  1340. }
  1341. pf->restore(is, format);
  1342. is >> tmp; // end of block
  1343. tmp = this->removeEndTag ( tmp );
  1344. }
  1345. else if ( tmp.compare("precomputedA") == 0 )
  1346. {
  1347. is >> tmp; // size
  1348. int preCompSize ( 0 );
  1349. is >> preCompSize;
  1350. precomputedA.clear();
  1351. if ( b_restoreVerbose )
  1352. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1353. for ( int i = 0; i < preCompSize; i++ )
  1354. {
  1355. int nr;
  1356. is >> nr;
  1357. PrecomputedType pct;
  1358. pct.setIoUntilEndOfFile ( false );
  1359. pct.restore ( is, format );
  1360. precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1361. }
  1362. is >> tmp; // end of block
  1363. tmp = this->removeEndTag ( tmp );
  1364. }
  1365. else if ( tmp.compare("precomputedB") == 0 )
  1366. {
  1367. is >> tmp; // size
  1368. int preCompSize ( 0 );
  1369. is >> preCompSize;
  1370. precomputedB.clear();
  1371. if ( b_restoreVerbose )
  1372. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1373. for ( int i = 0; i < preCompSize; i++ )
  1374. {
  1375. int nr;
  1376. is >> nr;
  1377. PrecomputedType pct;
  1378. pct.setIoUntilEndOfFile ( false );
  1379. pct.restore ( is, format );
  1380. precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1381. }
  1382. is >> tmp; // end of block
  1383. tmp = this->removeEndTag ( tmp );
  1384. }
  1385. else if ( tmp.compare("precomputedT") == 0 )
  1386. {
  1387. is >> tmp; // size
  1388. int precomputedTSize ( 0 );
  1389. is >> precomputedTSize;
  1390. precomputedT.clear();
  1391. if ( b_restoreVerbose )
  1392. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1393. if ( precomputedTSize > 0 )
  1394. {
  1395. if ( b_restoreVerbose )
  1396. std::cerr << " restore precomputedT" << std::endl;
  1397. is >> tmp;
  1398. int sizeOfLUT;
  1399. is >> sizeOfLUT;
  1400. for (int i = 0; i < precomputedTSize; i++)
  1401. {
  1402. is >> tmp;
  1403. int index;
  1404. is >> index;
  1405. double * array = new double [ sizeOfLUT];
  1406. for ( int i = 0; i < sizeOfLUT; i++ )
  1407. {
  1408. is >> array[i];
  1409. }
  1410. precomputedT.insert ( std::pair<int, double*> ( index, array ) );
  1411. }
  1412. }
  1413. else
  1414. {
  1415. if ( b_restoreVerbose )
  1416. std::cerr << " skip restoring precomputedT" << std::endl;
  1417. }
  1418. is >> tmp; // end of block
  1419. tmp = this->removeEndTag ( tmp );
  1420. }
  1421. else if ( tmp.compare("labels") == 0 )
  1422. {
  1423. is >> labels;
  1424. is >> tmp; // end of block
  1425. tmp = this->removeEndTag ( tmp );
  1426. }
  1427. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1428. {
  1429. is >> binaryLabelPositive;
  1430. is >> tmp; // end of block
  1431. tmp = this->removeEndTag ( tmp );
  1432. }
  1433. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1434. {
  1435. is >> binaryLabelNegative;
  1436. is >> tmp; // end of block
  1437. tmp = this->removeEndTag ( tmp );
  1438. }
  1439. else if ( tmp.compare("knownClasses") == 0 )
  1440. {
  1441. is >> tmp; // size
  1442. int knownClassesSize ( 0 );
  1443. is >> knownClassesSize;
  1444. knownClasses.clear();
  1445. if ( knownClassesSize > 0 )
  1446. {
  1447. for (int i = 0; i < knownClassesSize; i++)
  1448. {
  1449. int classNo;
  1450. is >> classNo;
  1451. knownClasses.insert ( classNo );
  1452. }
  1453. }
  1454. else
  1455. {
  1456. //nothing to do
  1457. }
  1458. is >> tmp; // end of block
  1459. tmp = this->removeEndTag ( tmp );
  1460. }
  1461. else if ( tmp.compare("ikmsum") == 0 )
  1462. {
  1463. bool b_endOfBlock ( false ) ;
  1464. while ( !b_endOfBlock )
  1465. {
  1466. is >> tmp; // start of block
  1467. if ( this->isEndTag( tmp, "ikmsum" ) )
  1468. {
  1469. b_endOfBlock = true;
  1470. continue;
  1471. }
  1472. tmp = this->removeStartTag ( tmp );
  1473. if ( tmp.compare("IKMNoise") == 0 )
  1474. {
  1475. IKMNoise * ikmnoise = new IKMNoise ();
  1476. ikmnoise->restore ( is, format );
  1477. if ( b_restoreVerbose )
  1478. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1479. ikmsum->addModel ( ikmnoise );
  1480. }
  1481. else
  1482. {
  1483. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1484. throw;
  1485. }
  1486. }
  1487. }
  1488. //////////////////////////////////////////////
  1489. // Iterative Linear Solver //
  1490. //////////////////////////////////////////////
  1491. else if ( tmp.compare("linsolver") == 0 )
  1492. {
  1493. //TODO linsolver
  1494. // current solution: hard coded with default values, since LinearSolver does not offer Persistent functionalities
  1495. this->linsolver = new ILSConjugateGradients ( false , 1000, 1e-7, 1e-7 );
  1496. is >> tmp; // end of block
  1497. tmp = this->removeEndTag ( tmp );
  1498. }
  1499. else if ( tmp.compare("ils_max_iterations") == 0 )
  1500. {
  1501. is >> ils_max_iterations;
  1502. is >> tmp; // end of block
  1503. tmp = this->removeEndTag ( tmp );
  1504. }
  1505. /////////////////////////////////////
  1506. // optimization related parameters //
  1507. /////////////////////////////////////
  1508. else if ( tmp.compare("optimizationMethod") == 0 )
  1509. {
  1510. unsigned int ui_optimizationMethod;
  1511. is >> ui_optimizationMethod;
  1512. optimizationMethod = static_cast<OPTIMIZATIONTECHNIQUE> ( ui_optimizationMethod ) ;
  1513. is >> tmp; // end of block
  1514. tmp = this->removeEndTag ( tmp );
  1515. }
  1516. else if ( tmp.compare("optimizeNoise") == 0 )
  1517. {
  1518. is >> optimizeNoise;
  1519. is >> tmp; // end of block
  1520. tmp = this->removeEndTag ( tmp );
  1521. }
  1522. else if ( tmp.compare("parameterStepSize") == 0 )
  1523. {
  1524. is >> parameterStepSize;
  1525. is >> tmp; // end of block
  1526. tmp = this->removeEndTag ( tmp );
  1527. }
  1528. else if ( tmp.compare("downhillSimplexMaxIterations") == 0 )
  1529. {
  1530. is >> downhillSimplexMaxIterations;
  1531. is >> tmp; // end of block
  1532. tmp = this->removeEndTag ( tmp );
  1533. }
  1534. else if ( tmp.compare("downhillSimplexTimeLimit") == 0 )
  1535. {
  1536. is >> downhillSimplexTimeLimit;
  1537. is >> tmp; // end of block
  1538. tmp = this->removeEndTag ( tmp );
  1539. }
  1540. else if ( tmp.compare("downhillSimplexParamTol") == 0 )
  1541. {
  1542. is >> downhillSimplexParamTol;
  1543. is >> tmp; // end of block
  1544. tmp = this->removeEndTag ( tmp );
  1545. }
  1546. //////////////////////////////////////////////
  1547. // likelihood computation related variables //
  1548. //////////////////////////////////////////////
  1549. else if ( tmp.compare("verifyApproximation") == 0 )
  1550. {
  1551. is >> verifyApproximation;
  1552. is >> tmp; // end of block
  1553. tmp = this->removeEndTag ( tmp );
  1554. }
  1555. else if ( tmp.compare("eig") == 0 )
  1556. {
  1557. //TODO eig
  1558. // currently hard coded, since EV does not offer Persistent functionalities and
  1559. // in addition, we currently have no other choice for EV then EVArnoldi
  1560. this->eig = new EVArnoldi ( false /*eig_verbose */, 10 );
  1561. is >> tmp; // end of block
  1562. tmp = this->removeEndTag ( tmp );
  1563. }
  1564. else if ( tmp.compare("nrOfEigenvaluesToConsider") == 0 )
  1565. {
  1566. is >> nrOfEigenvaluesToConsider;
  1567. is >> tmp; // end of block
  1568. tmp = this->removeEndTag ( tmp );
  1569. }
  1570. else if ( tmp.compare("eigenMax") == 0 )
  1571. {
  1572. is >> eigenMax;
  1573. is >> tmp; // end of block
  1574. tmp = this->removeEndTag ( tmp );
  1575. }
  1576. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1577. {
  1578. is >> eigenMaxVectors;
  1579. is >> tmp; // end of block
  1580. tmp = this->removeEndTag ( tmp );
  1581. }
  1582. ////////////////////////////////////////////
  1583. // variance computation related variables //
  1584. ////////////////////////////////////////////
  1585. else if ( tmp.compare("nrOfEigenvaluesToConsiderForVarApprox") == 0 )
  1586. {
  1587. is >> nrOfEigenvaluesToConsiderForVarApprox;
  1588. is >> tmp; // end of block
  1589. tmp = this->removeEndTag ( tmp );
  1590. }
  1591. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1592. {
  1593. int sizeOfAForVarEst;
  1594. is >> sizeOfAForVarEst;
  1595. if ( b_restoreVerbose )
  1596. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1597. if (sizeOfAForVarEst > 0)
  1598. {
  1599. precomputedAForVarEst.clear();
  1600. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1601. precomputedAForVarEst.restore ( is, format );
  1602. }
  1603. is >> tmp; // end of block
  1604. tmp = this->removeEndTag ( tmp );
  1605. }
  1606. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1607. {
  1608. std::string isNull;
  1609. is >> isNull; // NOTNULL or NULL
  1610. if ( b_restoreVerbose )
  1611. std::cerr << "content of isNull: " << isNull << std::endl;
  1612. if (isNull.compare("NOTNULL") == 0)
  1613. {
  1614. if ( b_restoreVerbose )
  1615. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1616. int sizeOfLUT;
  1617. is >> sizeOfLUT;
  1618. precomputedTForVarEst = new double [ sizeOfLUT ];
  1619. for ( int i = 0; i < sizeOfLUT; i++ )
  1620. {
  1621. is >> precomputedTForVarEst[i];
  1622. }
  1623. }
  1624. else
  1625. {
  1626. if ( b_restoreVerbose )
  1627. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1628. if (precomputedTForVarEst != NULL)
  1629. delete precomputedTForVarEst;
  1630. }
  1631. is >> tmp; // end of block
  1632. tmp = this->removeEndTag ( tmp );
  1633. }
  1634. /////////////////////////////////////////////////////
  1635. // online / incremental learning related variables //
  1636. /////////////////////////////////////////////////////
  1637. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1638. {
  1639. is >> b_usePreviousAlphas;
  1640. is >> tmp; // end of block
  1641. tmp = this->removeEndTag ( tmp );
  1642. }
  1643. else if ( tmp.compare("previousAlphas") == 0 )
  1644. {
  1645. is >> tmp; // size
  1646. int sizeOfPreviousAlphas ( 0 );
  1647. is >> sizeOfPreviousAlphas;
  1648. previousAlphas.clear();
  1649. if ( b_restoreVerbose )
  1650. std::cerr << "restore previousAlphas with size: " << sizeOfPreviousAlphas << std::endl;
  1651. for ( int i = 0; i < sizeOfPreviousAlphas; i++ )
  1652. {
  1653. int classNo;
  1654. is >> classNo;
  1655. NICE::Vector classAlpha;
  1656. is >> classAlpha;
  1657. previousAlphas.insert ( std::pair< int, NICE::Vector > ( classNo, classAlpha ) );
  1658. }
  1659. is >> tmp; // end of block
  1660. tmp = this->removeEndTag ( tmp );
  1661. }
  1662. else
  1663. {
  1664. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1665. throw;
  1666. }
  1667. }
  1668. //NOTE are there any more models you added? then add them here respectively in the correct order
  1669. //.....
  1670. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1671. if ( b_restoreVerbose )
  1672. std::cerr << " add GMHIKernel" << std::endl;
  1673. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1674. if ( b_restoreVerbose )
  1675. std::cerr << " restore positive and negative label" << std::endl;
  1676. knownClasses.clear();
  1677. if ( b_restoreVerbose )
  1678. std::cerr << " fill known classes object " << std::endl;
  1679. if ( precomputedA.size() == 1)
  1680. {
  1681. knownClasses.insert( binaryLabelPositive );
  1682. knownClasses.insert( binaryLabelNegative );
  1683. if ( b_restoreVerbose )
  1684. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1685. }
  1686. else
  1687. {
  1688. for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
  1689. knownClasses.insert ( itA->first );
  1690. if ( b_restoreVerbose )
  1691. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1692. }
  1693. }
  1694. else
  1695. {
  1696. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1697. throw;
  1698. }
  1699. }
  1700. void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
  1701. {
  1702. if ( os.good() )
  1703. {
  1704. // show starting point
  1705. os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1706. // os.precision ( numeric_limits<double>::digits10 + 1 );
  1707. ///////////////////////////////////
  1708. // output/debug related settings //
  1709. ///////////////////////////////////
  1710. os << this->createStartTag( "verbose" ) << std::endl;
  1711. os << verbose << std::endl;
  1712. os << this->createEndTag( "verbose" ) << std::endl;
  1713. os << this->createStartTag( "verboseTime" ) << std::endl;
  1714. os << verboseTime << std::endl;
  1715. os << this->createEndTag( "verboseTime" ) << std::endl;
  1716. os << this->createStartTag( "debug" ) << std::endl;
  1717. os << debug << std::endl;
  1718. os << this->createEndTag( "debug" ) << std::endl;
  1719. //////////////////////////////////////
  1720. // classification related variables //
  1721. //////////////////////////////////////
  1722. os << this->createStartTag( "b_performRegression" ) << std::endl;
  1723. os << b_performRegression << std::endl;
  1724. os << this->createEndTag( "b_performRegression" ) << std::endl;
  1725. os << this->createStartTag( "fmk" ) << std::endl;
  1726. fmk->store ( os, format );
  1727. os << this->createEndTag( "fmk" ) << std::endl;
  1728. os << this->createStartTag( "q" ) << std::endl;
  1729. if ( q != NULL )
  1730. {
  1731. os << "NOTNULL" << std::endl;
  1732. q->store ( os, format );
  1733. }
  1734. else
  1735. {
  1736. os << "NULL" << std::endl;
  1737. }
  1738. os << this->createEndTag( "q" ) << std::endl;
  1739. os << this->createStartTag( "parameterUpperBound" ) << std::endl;
  1740. os << parameterUpperBound << std::endl;
  1741. os << this->createEndTag( "parameterUpperBound" ) << std::endl;
  1742. os << this->createStartTag( "parameterLowerBound" ) << std::endl;
  1743. os << parameterLowerBound << std::endl;
  1744. os << this->createEndTag( "parameterLowerBound" ) << std::endl;
  1745. os << this->createStartTag( "pf" ) << std::endl;
  1746. pf->store(os, format);
  1747. os << this->createEndTag( "pf" ) << std::endl;
  1748. os << this->createStartTag( "precomputedA" ) << std::endl;
  1749. os << "size: " << precomputedA.size() << std::endl;
  1750. std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
  1751. for ( uint i = 0; i < precomputedA.size(); i++ )
  1752. {
  1753. os << preCompIt->first << std::endl;
  1754. ( preCompIt->second ).store ( os, format );
  1755. preCompIt++;
  1756. }
  1757. os << this->createEndTag( "precomputedA" ) << std::endl;
  1758. os << this->createStartTag( "precomputedB" ) << std::endl;
  1759. os << "size: " << precomputedB.size() << std::endl;
  1760. preCompIt = precomputedB.begin();
  1761. for ( uint i = 0; i < precomputedB.size(); i++ )
  1762. {
  1763. os << preCompIt->first << std::endl;
  1764. ( preCompIt->second ).store ( os, format );
  1765. preCompIt++;
  1766. }
  1767. os << this->createEndTag( "precomputedB" ) << std::endl;
  1768. os << this->createStartTag( "precomputedT" ) << std::endl;
  1769. os << "size: " << precomputedT.size() << std::endl;
  1770. if ( precomputedT.size() > 0 )
  1771. {
  1772. int sizeOfLUT ( 0 );
  1773. if ( q != NULL )
  1774. sizeOfLUT = q->size() * this->fmk->get_d();
  1775. os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1776. for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
  1777. {
  1778. os << "index: " << it->first << std::endl;
  1779. for ( int i = 0; i < sizeOfLUT; i++ )
  1780. {
  1781. os << ( it->second ) [i] << " ";
  1782. }
  1783. os << std::endl;
  1784. }
  1785. }
  1786. os << this->createEndTag( "precomputedT" ) << std::endl;
  1787. os << this->createStartTag( "labels" ) << std::endl;
  1788. os << labels << std::endl;
  1789. os << this->createEndTag( "labels" ) << std::endl;
  1790. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1791. os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1792. os << binaryLabelPositive << std::endl;
  1793. os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1794. os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1795. os << binaryLabelNegative << std::endl;
  1796. os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1797. os << this->createStartTag( "knownClasses" ) << std::endl;
  1798. os << "size: " << knownClasses.size() << std::endl;
  1799. for ( std::set< int >::const_iterator itKnownClasses = knownClasses.begin();
  1800. itKnownClasses != knownClasses.end();
  1801. itKnownClasses++
  1802. )
  1803. {
  1804. os << *itKnownClasses << " " << std::endl;
  1805. }
  1806. os << this->createEndTag( "knownClasses" ) << std::endl;
  1807. os << this->createStartTag( "ikmsum" ) << std::endl;
  1808. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1809. {
  1810. ( ikmsum->getModel ( j ) )->store ( os, format );
  1811. }
  1812. os << this->createEndTag( "ikmsum" ) << std::endl;
  1813. //////////////////////////////////////////////
  1814. // Iterative Linear Solver //
  1815. //////////////////////////////////////////////
  1816. os << this->createStartTag( "linsolver" ) << std::endl;
  1817. //TODO linsolver
  1818. os << this->createEndTag( "linsolver" ) << std::endl;
  1819. os << this->createStartTag( "ils_max_iterations" ) << std::endl;
  1820. os << ils_max_iterations << std::endl;
  1821. os << this->createEndTag( "ils_max_iterations" ) << std::endl;
  1822. /////////////////////////////////////
  1823. // optimization related parameters //
  1824. /////////////////////////////////////
  1825. os << this->createStartTag( "optimizationMethod" ) << std::endl;
  1826. os << optimizationMethod << std::endl;
  1827. os << this->createEndTag( "optimizationMethod" ) << std::endl;
  1828. os << this->createStartTag( "optimizeNoise" ) << std::endl;
  1829. os << optimizeNoise << std::endl;
  1830. os << this->createEndTag( "optimizeNoise" ) << std::endl;
  1831. os << this->createStartTag( "parameterStepSize" ) << std::endl;
  1832. os << parameterStepSize << std::endl;
  1833. os << this->createEndTag( "parameterStepSize" ) << std::endl;
  1834. os << this->createStartTag( "downhillSimplexMaxIterations" ) << std::endl;
  1835. os << downhillSimplexMaxIterations << std::endl;
  1836. os << this->createEndTag( "downhillSimplexMaxIterations" ) << std::endl;
  1837. os << this->createStartTag( "downhillSimplexTimeLimit" ) << std::endl;
  1838. os << downhillSimplexTimeLimit << std::endl;
  1839. os << this->createEndTag( "downhillSimplexTimeLimit" ) << std::endl;
  1840. os << this->createStartTag( "downhillSimplexParamTol" ) << std::endl;
  1841. os << downhillSimplexParamTol << std::endl;
  1842. os << this->createEndTag( "downhillSimplexParamTol" ) << std::endl;
  1843. //////////////////////////////////////////////
  1844. // likelihood computation related variables //
  1845. //////////////////////////////////////////////
  1846. os << this->createStartTag( "verifyApproximation" ) << std::endl;
  1847. os << verifyApproximation << std::endl;
  1848. os << this->createEndTag( "verifyApproximation" ) << std::endl;
  1849. os << this->createStartTag( "eig" ) << std::endl;
  1850. //TODO eig
  1851. os << this->createEndTag( "eig" ) << std::endl;
  1852. os << this->createStartTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  1853. os << nrOfEigenvaluesToConsider << std::endl;
  1854. os << this->createEndTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  1855. os << this->createStartTag( "eigenMax" ) << std::endl;
  1856. os << eigenMax << std::endl;
  1857. os << this->createEndTag( "eigenMax" ) << std::endl;
  1858. os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  1859. os << eigenMaxVectors << std::endl;
  1860. os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  1861. ////////////////////////////////////////////
  1862. // variance computation related variables //
  1863. ////////////////////////////////////////////
  1864. os << this->createStartTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  1865. os << nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1866. os << this->createEndTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  1867. os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  1868. os << precomputedAForVarEst.size() << std::endl;
  1869. if (precomputedAForVarEst.size() > 0)
  1870. {
  1871. precomputedAForVarEst.store ( os, format );
  1872. os << std::endl;
  1873. }
  1874. os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  1875. os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  1876. if ( precomputedTForVarEst != NULL )
  1877. {
  1878. os << "NOTNULL" << std::endl;
  1879. int sizeOfLUT ( 0 );
  1880. if ( q != NULL )
  1881. sizeOfLUT = q->size() * this->fmk->get_d();
  1882. os << sizeOfLUT << std::endl;
  1883. for ( int i = 0; i < sizeOfLUT; i++ )
  1884. {
  1885. os << precomputedTForVarEst[i] << " ";
  1886. }
  1887. os << std::endl;
  1888. }
  1889. else
  1890. {
  1891. os << "NULL" << std::endl;
  1892. }
  1893. os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  1894. /////////////////////////////////////////////////////
  1895. // online / incremental learning related variables //
  1896. /////////////////////////////////////////////////////
  1897. os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  1898. os << b_usePreviousAlphas << std::endl;
  1899. os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  1900. os << this->createStartTag( "previousAlphas" ) << std::endl;
  1901. os << "size: " << previousAlphas.size() << std::endl;
  1902. std::map< int, NICE::Vector >::const_iterator prevAlphaIt = previousAlphas.begin();
  1903. for ( uint i = 0; i < previousAlphas.size(); i++ )
  1904. {
  1905. os << prevAlphaIt->first << std::endl;
  1906. os << prevAlphaIt->second << std::endl;
  1907. prevAlphaIt++;
  1908. }
  1909. os << this->createEndTag( "previousAlphas" ) << std::endl;
  1910. // done
  1911. os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1912. }
  1913. else
  1914. {
  1915. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1916. }
  1917. }
  1918. void FMKGPHyperparameterOptimization::clear ( ) {};
  1919. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1920. // interface specific methods for incremental extensions
  1921. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1922. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  1923. const double & label,
  1924. const bool & performOptimizationAfterIncrement
  1925. )
  1926. {
  1927. if ( this->verbose )
  1928. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  1929. NICE::Timer t;
  1930. t.start();
  1931. std::set< int > newClasses;
  1932. this->labels.append ( label );
  1933. //have we seen this class already?
  1934. if ( !this->b_performRegression && ( this->knownClasses.find( label ) == this->knownClasses.end() ) )
  1935. {
  1936. this->knownClasses.insert( label );
  1937. newClasses.insert( label );
  1938. }
  1939. // add the new example to our data structure
  1940. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  1941. NICE::Timer tFmk;
  1942. tFmk.start();
  1943. this->fmk->addExample ( example, pf );
  1944. tFmk.stop();
  1945. if ( this->verboseTime)
  1946. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  1947. // add examples to all implicite kernel matrices we currently use
  1948. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  1949. // update the corresponding matrices A, B and lookup tables T
  1950. // optional: do the optimization again using the previously known solutions as initialization
  1951. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  1952. //clean up
  1953. newClasses.clear();
  1954. t.stop();
  1955. NICE::ResourceStatistics rs;
  1956. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  1957. long maxMemory;
  1958. rs.getMaximumMemory ( maxMemory );
  1959. if ( this->verbose )
  1960. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  1961. if ( this->verbose )
  1962. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  1963. }
  1964. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  1965. const NICE::Vector & newLabels,
  1966. const bool & performOptimizationAfterIncrement
  1967. )
  1968. {
  1969. if ( this->verbose )
  1970. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples --- " << std::endl;
  1971. NICE::Timer t;
  1972. t.start();
  1973. std::set< int > newClasses;
  1974. this->labels.append ( newLabels );
  1975. //have we seen this class already?
  1976. if ( !this->b_performRegression)
  1977. {
  1978. for ( NICE::Vector::const_iterator vecIt = newLabels.begin();
  1979. vecIt != newLabels.end(); vecIt++
  1980. )
  1981. {
  1982. if ( this->knownClasses.find( *vecIt ) == this->knownClasses.end() )
  1983. {
  1984. this->knownClasses.insert( *vecIt );
  1985. newClasses.insert( *vecIt );
  1986. }
  1987. }
  1988. }
  1989. // in a regression setting, we do not have to remember any "class labels"
  1990. else{}
  1991. // add the new example to our data structure
  1992. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  1993. NICE::Timer tFmk;
  1994. tFmk.start();
  1995. this->fmk->addMultipleExamples ( newExamples, pf );
  1996. tFmk.stop();
  1997. if ( this->verboseTime)
  1998. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  1999. // add examples to all implicite kernel matrices we currently use
  2000. this->ikmsum->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  2001. // update the corresponding matrices A, B and lookup tables T
  2002. // optional: do the optimization again using the previously known solutions as initialization
  2003. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2004. //clean up
  2005. newClasses.clear();
  2006. t.stop();
  2007. NICE::ResourceStatistics rs;
  2008. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2009. long maxMemory;
  2010. rs.getMaximumMemory ( maxMemory );
  2011. if ( this->verbose )
  2012. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2013. if ( this->verbose )
  2014. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples done --- " << std::endl;
  2015. }