FMKGPHyperparameterOptimization.cpp 92 KB

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