FMKGPHyperparameterOptimization.cpp 92 KB

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