FMKGPHyperparameterOptimization.cpp 84 KB

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