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. int eigValueMaxIterations = _conf->gI ( _confSection, "eig_value_max_iterations", 10 );
  496. this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */,
  497. eigValueMaxIterations /*eigValueMaxIterations*/
  498. );
  499. this->nrOfEigenvaluesToConsider = std::max ( 1, _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 ) );
  500. ////////////////////////////////////////////
  501. // variance computation related variables //
  502. ////////////////////////////////////////////
  503. this->nrOfEigenvaluesToConsiderForVarApprox = std::max ( 1, _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 ) );
  504. /////////////////////////////////////////////////////
  505. // online / incremental learning related variables //
  506. /////////////////////////////////////////////////////
  507. this->b_usePreviousAlphas = _conf->gB ( _confSection, "b_usePreviousAlphas", true );
  508. if ( this->b_verbose )
  509. {
  510. std::cerr << "------------" << std::endl;
  511. std::cerr << "| start |" << std::endl;
  512. std::cerr << "------------" << std::endl;
  513. }
  514. }
  515. ///////////////////// ///////////////////// /////////////////////
  516. // GET / SET
  517. ///////////////////// ///////////////////// /////////////////////
  518. void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
  519. {
  520. this->d_parameterUpperBound = _parameterUpperBound;
  521. }
  522. void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
  523. {
  524. this->d_parameterLowerBound = _parameterLowerBound;
  525. }
  526. std::set<uint> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
  527. {
  528. return this->knownClasses;
  529. }
  530. void FMKGPHyperparameterOptimization::setPerformRegression ( const bool & _performRegression )
  531. {
  532. //TODO check previously whether we already trained
  533. if ( false )
  534. throw NICE::Exception ( "FMPGKHyperparameterOptimization already initialized - switching between classification and regression not allowed!" );
  535. else
  536. this->b_performRegression = _performRegression;
  537. }
  538. void FMKGPHyperparameterOptimization::setFastMinKernel ( FastMinKernel * _fmk )
  539. {
  540. //TODO check previously whether we already trained
  541. if ( _fmk != NULL )
  542. {
  543. if ( this->fmk != NULL )
  544. {
  545. delete this->fmk;
  546. this->fmk = NULL;
  547. }
  548. this->fmk = _fmk;
  549. }
  550. //
  551. if ( this->q != NULL )
  552. {
  553. NICE::Vector _maxValuesPerDimension = this->fmk->featureMatrix().getLargestValuePerDimension();
  554. this->q->computeParametersFromData ( _maxValuesPerDimension );
  555. }
  556. }
  557. void FMKGPHyperparameterOptimization::setNrOfEigenvaluesToConsiderForVarApprox ( const int & _nrOfEigenvaluesToConsiderForVarApprox )
  558. {
  559. //TODO check previously whether we already trained
  560. this->nrOfEigenvaluesToConsiderForVarApprox = _nrOfEigenvaluesToConsiderForVarApprox;
  561. }
  562. ///////////////////// ///////////////////// /////////////////////
  563. // CLASSIFIER STUFF
  564. ///////////////////// ///////////////////// /////////////////////
  565. inline void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & _gplike,
  566. const std::map<uint, NICE::Vector> & _binaryLabels,
  567. uint & _parameterVectorSize )
  568. {
  569. _gplike = new GPLikelihoodApprox ( _binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
  570. _gplike->setDebug( this->b_debug );
  571. _gplike->setVerbose( this->b_verbose );
  572. _parameterVectorSize = this->ikmsum->getNumParameters();
  573. }
  574. void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & _noEigenValues )
  575. {
  576. //compute the largest eigenvalue of K + noise
  577. try
  578. {
  579. this->eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, _noEigenValues );
  580. }
  581. catch ( char const* exceptionMsg)
  582. {
  583. std::cerr << exceptionMsg << std::endl;
  584. throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
  585. }
  586. //NOTE EigenValue computation extracts EV and EW per default in decreasing order.
  587. }
  588. void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & _gplike,
  589. const uint & _parameterVectorSize
  590. )
  591. {
  592. if ( this->b_verbose )
  593. std::cerr << "perform optimization" << std::endl;
  594. if ( optimizationMethod == OPT_GREEDY )
  595. {
  596. if ( this->b_verbose )
  597. std::cerr << "OPT_GREEDY!!! " << std::endl;
  598. // simple greedy strategy
  599. if ( ikmsum->getNumParameters() != 1 )
  600. fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
  601. NICE::Vector lB = ikmsum->getParameterLowerBounds();
  602. NICE::Vector uB = ikmsum->getParameterUpperBounds();
  603. if ( this->b_verbose )
  604. std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
  605. for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
  606. {
  607. OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
  608. _gplike.evaluate ( hyperp );
  609. }
  610. }
  611. else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
  612. {
  613. //standard as before, normal optimization
  614. if ( this->b_verbose )
  615. std::cerr << "DOWNHILLSIMPLEX!!! " << std::endl;
  616. // downhill simplex strategy
  617. OPTIMIZATION::DownhillSimplexOptimizer optimizer;
  618. OPTIMIZATION::matrix_type initialParams ( _parameterVectorSize, 1 );
  619. NICE::Vector currentParameters;
  620. ikmsum->getParameters ( currentParameters );
  621. for ( uint i = 0 ; i < _parameterVectorSize; i++ )
  622. initialParams(i,0) = currentParameters[ i ];
  623. if ( this->b_verbose )
  624. std::cerr << "Initial parameters: " << initialParams << std::endl;
  625. //the scales object does not really matter in the actual implementation of Downhill Simplex
  626. // OPTIMIZATION::matrix_type scales ( _parameterVectorSize, 1);
  627. // scales.set(1.0);
  628. OPTIMIZATION::SimpleOptProblem optProblem ( &_gplike, initialParams, initialParams /* scales */ );
  629. optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
  630. optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
  631. optimizer.setParamTol ( true, downhillSimplexParamTol );
  632. optimizer.optimizeProb ( optProblem );
  633. }
  634. else if ( optimizationMethod == OPT_NONE )
  635. {
  636. if ( this->b_verbose )
  637. std::cerr << "NO OPTIMIZATION!!! " << std::endl;
  638. // without optimization
  639. if ( optimizeNoise )
  640. fthrow ( Exception, "Deactivate optimize_noise!" );
  641. if ( this->b_verbose )
  642. std::cerr << "Optimization is deactivated!" << std::endl;
  643. double value (1.0);
  644. if ( this->d_parameterLowerBound == this->d_parameterUpperBound)
  645. value = this->d_parameterLowerBound;
  646. pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
  647. pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
  648. // we use the standard value
  649. OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
  650. _gplike.setParameterLowerBound ( value );
  651. _gplike.setParameterUpperBound ( value );
  652. //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
  653. _gplike.computeAlphaDirect( hyperp, eigenMax );
  654. }
  655. if ( this->b_verbose )
  656. {
  657. std::cerr << "Optimal hyperparameter was: " << _gplike.getBestParameters() << std::endl;
  658. }
  659. }
  660. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & _gplike,
  661. const uint & parameterVectorSize
  662. )
  663. {
  664. // transform all features with the currently "optimal" parameter
  665. ikmsum->setParameters ( _gplike.getBestParameters() );
  666. }
  667. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & _gplike )
  668. {
  669. this->precomputedA.clear();
  670. this->precomputedB.clear();
  671. for ( std::map<uint, NICE::Vector>::const_iterator i = _gplike.getBestAlphas().begin(); i != _gplike.getBestAlphas().end(); i++ )
  672. {
  673. PrecomputedType A;
  674. PrecomputedType B;
  675. if ( this->b_debug && i->first == 1)
  676. {
  677. std::cerr << "Training for class " << i->first << endl;
  678. std::cerr << " " << i->second << std::endl;
  679. }
  680. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  681. A.setIoUntilEndOfFile ( false );
  682. B.setIoUntilEndOfFile ( false );
  683. this->precomputedA[ i->first ] = A;
  684. this->precomputedB[ i->first ] = B;
  685. if ( this->q != NULL )
  686. {
  687. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, this->q, this->pf );
  688. //just to be sure that we do not waste space here
  689. if ( precomputedT[ i->first ] != NULL )
  690. delete precomputedT[ i->first ];
  691. precomputedT[ i->first ] = T;
  692. // //debug
  693. // double * p_t = T;
  694. // for ( uint i=0; i < this->q->getNumberOfBins(); i++ , p_t++)
  695. // {
  696. // std::cerr << " " << *p_t;
  697. // }
  698. // std::cerr << std::endl;
  699. }
  700. }
  701. if ( this->precomputedTForVarEst != NULL )
  702. {
  703. this->prepareVarianceApproximationRough();
  704. }
  705. else if ( this->nrOfEigenvaluesToConsiderForVarApprox > 0)
  706. {
  707. this->prepareVarianceApproximationFine();
  708. }
  709. // in case that we should want to store the alpha vectors for incremental extensions
  710. if ( this->b_usePreviousAlphas )
  711. this->previousAlphas = _gplike.getBestAlphas();
  712. }
  713. #ifdef NICE_USELIB_MATIO
  714. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & _data,
  715. const NICE::Vector & _yl,
  716. const std::set<uint> & _positives,
  717. const std::set<uint> & _negatives,
  718. double _noise
  719. )
  720. {
  721. std::map<uint, uint> examples;
  722. NICE::Vector y ( _yl.size() );
  723. uint ind = 0;
  724. for ( uint i = 0 ; i < _yl.size(); i++ )
  725. {
  726. if ( _positives.find ( i ) != _positives.end() ) {
  727. y[ examples.size() ] = 1.0;
  728. examples.insert ( pair<uint, uint> ( i, ind ) );
  729. ind++;
  730. } else if ( _negatives.find ( i ) != _negatives.end() ) {
  731. y[ examples.size() ] = -1.0;
  732. examples.insert ( pair<uint, uint> ( i, ind ) );
  733. ind++;
  734. }
  735. }
  736. y.resize ( examples.size() );
  737. std::cerr << "Examples: " << examples.size() << std::endl;
  738. optimize ( _data, y, examples, _noise );
  739. }
  740. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & _data,
  741. const NICE::Vector & _y,
  742. const std::map<uint, uint> & _examples,
  743. double _noise
  744. )
  745. {
  746. NICE::Timer t;
  747. t.start();
  748. std::cerr << "Initializing data structure ..." << std::endl;
  749. if ( fmk != NULL ) delete fmk;
  750. fmk = new FastMinKernel ( _data, _noise, _examples );
  751. t.stop();
  752. if ( this->b_verboseTime )
  753. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  754. optimize ( _y );
  755. }
  756. #endif
  757. uint FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<uint, NICE::Vector> & _binaryLabels,
  758. const NICE::Vector & _y ,
  759. std::set<uint> & _myClasses
  760. )
  761. {
  762. _myClasses.clear();
  763. // determine which classes we have in our label vector
  764. // -> MATLAB: myClasses = unique(y);
  765. for ( NICE::Vector::const_iterator it = _y.begin(); it != _y.end(); it++ )
  766. {
  767. if ( _myClasses.find ( *it ) == _myClasses.end() )
  768. {
  769. _myClasses.insert ( *it );
  770. }
  771. }
  772. //count how many different classes appear in our data
  773. uint nrOfClasses ( _myClasses.size() );
  774. _binaryLabels.clear();
  775. //compute the corresponding binary label vectors
  776. if ( nrOfClasses > 2 )
  777. {
  778. //resize every labelVector and set all entries to -1.0
  779. for ( std::set<uint>::const_iterator k = _myClasses.begin(); k != _myClasses.end(); k++ )
  780. {
  781. _binaryLabels[ *k ].resize ( _y.size() );
  782. _binaryLabels[ *k ].set ( -1.0 );
  783. }
  784. // now look on every example and set the entry of its corresponding label vector to 1.0
  785. // proper existance should not be a problem
  786. for ( uint i = 0 ; i < _y.size(); i++ )
  787. _binaryLabels[ _y[i] ][i] = 1.0;
  788. }
  789. else if ( nrOfClasses == 2 )
  790. {
  791. //binary setting -- prepare a binary label vector
  792. NICE::Vector yb ( _y );
  793. this->i_binaryLabelNegative = *(_myClasses.begin());
  794. std::set<uint>::const_iterator classIt = _myClasses.begin(); classIt++;
  795. this->i_binaryLabelPositive = *classIt;
  796. if ( this->b_verbose )
  797. {
  798. std::cerr << "positiveClass : " << this->i_binaryLabelPositive << " negativeClass: " << this->i_binaryLabelNegative << std::endl;
  799. std::cerr << " all labels: " << _y << std::endl << std::endl;
  800. }
  801. for ( uint i = 0 ; i < yb.size() ; i++ )
  802. yb[i] = ( _y[i] == this->i_binaryLabelNegative ) ? -1.0 : 1.0;
  803. _binaryLabels[ this->i_binaryLabelPositive ] = yb;
  804. //we do NOT do real binary computation, but an implicite one with only a single object
  805. nrOfClasses--;
  806. }
  807. else //OCC setting
  808. {
  809. //we set the labels to 1, independent of the previously given class number
  810. //however, the original class numbers are stored and returned in classification
  811. NICE::Vector yOne ( _y.size(), 1 );
  812. _binaryLabels[ *(_myClasses.begin()) ] = yOne;
  813. //we have to indicate, that we are in an OCC setting
  814. nrOfClasses--;
  815. }
  816. return nrOfClasses;
  817. }
  818. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & _y )
  819. {
  820. if ( this->fmk == NULL )
  821. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  822. this->labels = _y;
  823. std::map< uint, NICE::Vector > binaryLabels;
  824. if ( this->b_performRegression )
  825. {
  826. // for regression, we are not interested in regression scores, rather than in any "label"
  827. uint regressionLabel ( 1 );
  828. binaryLabels.insert ( std::pair< uint, NICE::Vector> ( regressionLabel, _y ) );
  829. this->knownClasses.clear();
  830. this->knownClasses.insert ( regressionLabel );
  831. }
  832. else
  833. {
  834. this->prepareBinaryLabels ( binaryLabels, _y , knownClasses );
  835. }
  836. //now call the main function :)
  837. this->optimize(binaryLabels);
  838. }
  839. void FMKGPHyperparameterOptimization::optimize ( std::map<uint, NICE::Vector> & _binaryLabels )
  840. {
  841. Timer t;
  842. t.start();
  843. //how many different classes do we have right now?
  844. int nrOfClasses = _binaryLabels.size();
  845. if ( this->b_verbose )
  846. {
  847. std::cerr << "Initial noise level: " << this->fmk->getNoise() << std::endl;
  848. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  849. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << this->knownClasses.size() << std::endl;
  850. }
  851. // combine standard model and noise model
  852. Timer t1;
  853. t1.start();
  854. //setup the kernel combination
  855. this->ikmsum = new IKMLinearCombination ();
  856. if ( this->b_verbose )
  857. {
  858. std::cerr << "_binaryLabels.size(): " << _binaryLabels.size() << std::endl;
  859. }
  860. //First model: noise
  861. this->ikmsum->addModel ( new IKMNoise ( this->fmk->get_n(), this->fmk->getNoise(), this->optimizeNoise ) );
  862. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  863. this->fmk->setNoise ( 0.0 );
  864. this->ikmsum->addModel ( new GMHIKernel ( this->fmk, this->pf, NULL /* no quantization */ ) );
  865. t1.stop();
  866. if ( this->b_verboseTime )
  867. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  868. GPLikelihoodApprox * gplike;
  869. uint parameterVectorSize;
  870. t1.start();
  871. this->setupGPLikelihoodApprox ( gplike, _binaryLabels, parameterVectorSize );
  872. t1.stop();
  873. if ( this->b_verboseTime )
  874. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  875. if ( this->b_verbose )
  876. {
  877. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  878. }
  879. t1.start();
  880. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  881. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  882. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  883. t1.stop();
  884. if ( this->b_verboseTime )
  885. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  886. if ( this->b_verbose )
  887. std::cerr << "resulting eigenvalues for first class: " << this->eigenMax[0] << std::endl;
  888. t1.start();
  889. this->performOptimization ( *gplike, parameterVectorSize );
  890. t1.stop();
  891. if ( this->b_verboseTime )
  892. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  893. if ( this->b_verbose )
  894. std::cerr << "Preparing classification ..." << std::endl;
  895. t1.start();
  896. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  897. t1.stop();
  898. if ( this->b_verboseTime )
  899. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  900. t1.start();
  901. this->computeMatricesAndLUTs ( *gplike );
  902. t1.stop();
  903. if ( this->b_verboseTime )
  904. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  905. t.stop();
  906. ResourceStatistics rs;
  907. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  908. long maxMemory;
  909. rs.getMaximumMemory ( maxMemory );
  910. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  911. //don't waste memory
  912. delete gplike;
  913. }
  914. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  915. {
  916. PrecomputedType AVar;
  917. this->fmk->hikPrepareKVNApproximation ( AVar );
  918. this->precomputedAForVarEst = AVar;
  919. this->precomputedAForVarEst.setIoUntilEndOfFile ( false );
  920. if ( this->q != NULL )
  921. {
  922. double *T = this->fmk->hikPrepareLookupTableForKVNApproximation ( this->q, this->pf );
  923. this->precomputedTForVarEst = T;
  924. }
  925. }
  926. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  927. {
  928. if ( this->eigenMax.size() < (uint) this->nrOfEigenvaluesToConsiderForVarApprox )
  929. {
  930. std::cerr << "not enough eigenvectors computed for fine approximation of predictive variance. " <<std::endl;
  931. std::cerr << "Current number of EV: " << this->eigenMax.size() << " but required: " << (uint) this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  932. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  933. }
  934. }
  935. uint FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & _xstar,
  936. NICE::SparseVector & _scores
  937. ) const
  938. {
  939. // loop through all classes
  940. if ( this->precomputedA.size() == 0 )
  941. {
  942. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  943. }
  944. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  945. {
  946. uint classno = i->first;
  947. double beta;
  948. if ( this->q != NULL ) {
  949. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  950. double *T = j->second;
  951. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  952. } else {
  953. const PrecomputedType & A = i->second;
  954. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  955. const PrecomputedType & B = j->second;
  956. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  957. // Giving the transformation pf as an additional
  958. // argument is necessary due to the following reason:
  959. // FeatureMatrixT is sorted according to the original values, therefore,
  960. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  961. // values as inputs. However, for calculation we need the transformed features values.
  962. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, pf );
  963. }
  964. _scores[ classno ] = beta;
  965. }
  966. _scores.setDim ( *(this->knownClasses.rbegin() ) + 1 );
  967. if ( this->precomputedA.size() > 1 )
  968. { // multi-class classification
  969. return _scores.maxElement();
  970. }
  971. else if ( this->knownClasses.size() == 2 ) // binary setting
  972. {
  973. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  974. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  975. }
  976. else //OCC or regression setting
  977. {
  978. return 1;
  979. }
  980. }
  981. uint FMKGPHyperparameterOptimization::classify ( const NICE::Vector & _xstar,
  982. NICE::SparseVector & _scores
  983. ) const
  984. {
  985. // loop through all classes
  986. if ( this->precomputedA.size() == 0 )
  987. {
  988. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  989. }
  990. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  991. {
  992. uint classno = i->first;
  993. double beta;
  994. if ( this->q != NULL )
  995. {
  996. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  997. double *T = j->second;
  998. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  999. }
  1000. else
  1001. {
  1002. const PrecomputedType & A = i->second;
  1003. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  1004. const PrecomputedType & B = j->second;
  1005. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  1006. // Giving the transformation pf as an additional
  1007. // argument is necessary due to the following reason:
  1008. // FeatureMatrixT is sorted according to the original values, therefore,
  1009. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  1010. // values as inputs. However, for calculation we need the transformed features values.
  1011. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, this->pf );
  1012. }
  1013. _scores[ classno ] = beta;
  1014. }
  1015. _scores.setDim ( *(this->knownClasses.rbegin() ) + 1 );
  1016. if ( this->precomputedA.size() > 1 )
  1017. { // multi-class classification
  1018. return _scores.maxElement();
  1019. }
  1020. else if ( this->knownClasses.size() == 2 ) // binary setting
  1021. {
  1022. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  1023. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  1024. }
  1025. else //OCC or regression setting
  1026. {
  1027. return 1;
  1028. }
  1029. }
  1030. //////////////////////////////////////////
  1031. // variance computation: sparse inputs
  1032. //////////////////////////////////////////
  1033. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & _x,
  1034. double & _predVariance
  1035. ) const
  1036. {
  1037. // security check!
  1038. if ( this->pf == NULL )
  1039. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1040. // ---------------- compute the first term --------------------
  1041. double kSelf ( 0.0 );
  1042. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1043. {
  1044. kSelf += this->pf->f ( 0, it->second );
  1045. // if weighted dimensions:
  1046. //kSelf += pf->f(it->first,it->second);
  1047. }
  1048. // ---------------- compute the approximation of the second term --------------------
  1049. double normKStar;
  1050. if ( this->q != NULL )
  1051. {
  1052. if ( precomputedTForVarEst == NULL )
  1053. {
  1054. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1055. }
  1056. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, _x, normKStar );
  1057. }
  1058. else
  1059. {
  1060. if ( precomputedAForVarEst.size () == 0 )
  1061. {
  1062. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1063. }
  1064. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, _x, normKStar, pf );
  1065. }
  1066. _predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1067. }
  1068. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & _x,
  1069. double & _predVariance
  1070. ) const
  1071. {
  1072. if ( this->b_debug )
  1073. {
  1074. std::cerr << "FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine" << std::endl;
  1075. }
  1076. // security check!
  1077. if ( this->eigenMaxVectors.rows() == 0 )
  1078. {
  1079. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1080. }
  1081. // ---------------- compute the first term --------------------
  1082. // Timer t;
  1083. // t.start();
  1084. double kSelf ( 0.0 );
  1085. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1086. {
  1087. kSelf += this->pf->f ( 0, it->second );
  1088. // if weighted dimensions:
  1089. //kSelf += pf->f(it->first,it->second);
  1090. }
  1091. if ( this->b_debug )
  1092. {
  1093. std::cerr << "FMKGPHyp::VarApproxFine -- kSelf: " << kSelf << std::endl;
  1094. }
  1095. // ---------------- compute the approximation of the second term --------------------
  1096. // t.stop();
  1097. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1098. // t.start();
  1099. NICE::Vector kStar;
  1100. this->fmk->hikComputeKernelVector ( _x, kStar );
  1101. if ( this->b_debug )
  1102. {
  1103. std::cerr << "FMKGPHyp::VarApproxFine -- kStar: " << kStar << std::endl;
  1104. std::cerr << "nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1105. }
  1106. /* t.stop();
  1107. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1108. NICE::Vector multiplicationResults( this->nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1109. if ( this->b_debug )
  1110. {
  1111. std::cerr << "FMKGPHyp::VarApproxFine -- nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1112. std::cerr << "FMKGPHyp::VarApproxFine -- initial multiplicationResults: " << multiplicationResults << std::endl;
  1113. }
  1114. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1115. {
  1116. NICE::Vector::iterator multResIt = multiplicationResults.begin();
  1117. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++, multResIt++)
  1118. {
  1119. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++ ,eigenVecIt++)
  1120. {
  1121. (*multResIt) += (*kStarIt) * (*eigenVecIt);
  1122. }
  1123. }
  1124. }
  1125. if ( this->b_debug )
  1126. {
  1127. std::cerr << "FMKGPHyp::VarApproxFine -- computed multiplicationResults: " << multiplicationResults << std::endl;
  1128. }
  1129. double projectionLength ( 0.0 );
  1130. double currentSecondTerm ( 0.0 );
  1131. double sumOfProjectionLengths ( 0.0 );
  1132. int cnt ( 0 );
  1133. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1134. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1135. {
  1136. projectionLength = ( *it );
  1137. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1138. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1139. it++;
  1140. cnt++;
  1141. }
  1142. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1143. currentSecondTerm += ( 1.0 / this->eigenMax[this->nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1144. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1145. {
  1146. std::cerr << "Attention: normKStar: " << normKStar << " - sumOfProjectionLengths: " << sumOfProjectionLengths << " is smaller than zero -- strange!" << std::endl;
  1147. }
  1148. _predVariance = kSelf - currentSecondTerm;
  1149. }
  1150. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1151. {
  1152. // security check!
  1153. if ( this->ikmsum->getNumberOfModels() == 0 )
  1154. {
  1155. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1156. }
  1157. Timer t;
  1158. // t.start();
  1159. // ---------------- compute the first term --------------------
  1160. double kSelf ( 0.0 );
  1161. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1162. {
  1163. kSelf += this->pf->f ( 0, it->second );
  1164. // if weighted dimensions:
  1165. //kSelf += pf->f(it->first,it->second);
  1166. }
  1167. // ---------------- compute the second term --------------------
  1168. NICE::Vector kStar;
  1169. fmk->hikComputeKernelVector ( x, kStar );
  1170. //now run the ILS method
  1171. NICE::Vector diagonalElements;
  1172. ikmsum->getDiagonalElements ( diagonalElements );
  1173. // init simple jacobi pre-conditioning
  1174. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1175. //TODO what to do for other solver techniques?
  1176. //perform pre-conditioning
  1177. if ( linsolver_cg != NULL )
  1178. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1179. NICE::Vector beta;
  1180. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1181. * K~ = K + sigma^2 I
  1182. *
  1183. * K~ \approx lambda_max v v^T
  1184. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1185. * => \lambda_max v^T alpha = v^T k_*
  1186. * => alpha = k_* / lambda_max could be a good initial start
  1187. * If we put everything in the first equation this gives us
  1188. * v = k_*
  1189. * This reduces the number of iterations by 5 or 8
  1190. */
  1191. beta = (kStar * (1.0 / eigenMax[0]) );
  1192. linsolver->solveLin ( *ikmsum, kStar, beta );
  1193. beta *= kStar;
  1194. double currentSecondTerm( beta.Sum() );
  1195. predVariance = kSelf - currentSecondTerm;
  1196. }
  1197. //////////////////////////////////////////
  1198. // variance computation: non-sparse inputs
  1199. //////////////////////////////////////////
  1200. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1201. {
  1202. // security check!
  1203. if ( pf == NULL )
  1204. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1205. // ---------------- compute the first term --------------------
  1206. double kSelf ( 0.0 );
  1207. int dim ( 0 );
  1208. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1209. {
  1210. kSelf += pf->f ( 0, *it );
  1211. // if weighted dimensions:
  1212. //kSelf += pf->f(dim,*it);
  1213. }
  1214. // ---------------- compute the approximation of the second term --------------------
  1215. double normKStar;
  1216. if ( this->q != NULL )
  1217. {
  1218. if ( precomputedTForVarEst == NULL )
  1219. {
  1220. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1221. }
  1222. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, x, normKStar );
  1223. }
  1224. else
  1225. {
  1226. if ( precomputedAForVarEst.size () == 0 )
  1227. {
  1228. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1229. }
  1230. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, this->pf );
  1231. }
  1232. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1233. }
  1234. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & _x,
  1235. double & _predVariance
  1236. ) const
  1237. {
  1238. // security check!
  1239. if ( this->eigenMaxVectors.rows() == 0 )
  1240. {
  1241. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1242. }
  1243. // ---------------- compute the first term --------------------
  1244. double kSelf ( 0.0 );
  1245. uint dim ( 0 );
  1246. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1247. {
  1248. kSelf += this->pf->f ( 0, *it );
  1249. // if weighted dimensions:
  1250. //kSelf += pf->f(dim,*it);
  1251. }
  1252. // ---------------- compute the approximation of the second term --------------------
  1253. NICE::Vector kStar;
  1254. this->fmk->hikComputeKernelVector ( _x, kStar );
  1255. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1256. //wherefor it takes aeons...
  1257. //so we compute it by ourselves
  1258. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1259. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1260. NICE::Vector multiplicationResults(this-> nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1261. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1262. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1263. {
  1264. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1265. {
  1266. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1267. }
  1268. }
  1269. double projectionLength ( 0.0 );
  1270. double currentSecondTerm ( 0.0 );
  1271. double sumOfProjectionLengths ( 0.0 );
  1272. int cnt ( 0 );
  1273. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1274. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1275. {
  1276. projectionLength = ( *it );
  1277. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1278. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1279. it++;
  1280. cnt++;
  1281. }
  1282. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1283. currentSecondTerm += ( 1.0 / this->eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1284. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1285. {
  1286. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1287. }
  1288. _predVariance = kSelf - currentSecondTerm;
  1289. }
  1290. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & _x,
  1291. double & _predVariance
  1292. ) const
  1293. {
  1294. if ( this->ikmsum->getNumberOfModels() == 0 )
  1295. {
  1296. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1297. }
  1298. // ---------------- compute the first term --------------------
  1299. double kSelf ( 0.0 );
  1300. uint dim ( 0 );
  1301. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1302. {
  1303. kSelf += this->pf->f ( 0, *it );
  1304. // if weighted dimensions:
  1305. //kSelf += pf->f(dim,*it);
  1306. }
  1307. // ---------------- compute the second term --------------------
  1308. NICE::Vector kStar;
  1309. this->fmk->hikComputeKernelVector ( _x, kStar );
  1310. //now run the ILS method
  1311. NICE::Vector diagonalElements;
  1312. this->ikmsum->getDiagonalElements ( diagonalElements );
  1313. // init simple jacobi pre-conditioning
  1314. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( this->linsolver );
  1315. //perform pre-conditioning
  1316. if ( linsolver_cg != NULL )
  1317. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1318. NICE::Vector beta;
  1319. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1320. * K~ = K + sigma^2 I
  1321. *
  1322. * K~ \approx lambda_max v v^T
  1323. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1324. * => \lambda_max v^T alpha = v^T k_*
  1325. * => alpha = k_* / lambda_max could be a good initial start
  1326. * If we put everything in the first equation this gives us
  1327. * v = k_*
  1328. * This reduces the number of iterations by 5 or 8
  1329. */
  1330. beta = (kStar * (1.0 / this->eigenMax[0]) );
  1331. this->linsolver->solveLin ( *ikmsum, kStar, beta );
  1332. beta *= kStar;
  1333. double currentSecondTerm( beta.Sum() );
  1334. _predVariance = kSelf - currentSecondTerm;
  1335. }
  1336. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1337. // interface specific methods for store and restore
  1338. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1339. void FMKGPHyperparameterOptimization::restore ( std::istream & _is,
  1340. int _format
  1341. )
  1342. {
  1343. bool b_restoreVerbose ( false );
  1344. #ifdef B_RESTOREVERBOSE
  1345. b_restoreVerbose = true;
  1346. #endif
  1347. if ( _is.good() )
  1348. {
  1349. if ( b_restoreVerbose )
  1350. std::cerr << " in FMKGPHyperparameterOptimization restore" << std::endl;
  1351. std::string tmp;
  1352. _is >> tmp; //class name
  1353. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1354. {
  1355. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1356. throw;
  1357. }
  1358. if (fmk != NULL)
  1359. {
  1360. delete fmk;
  1361. fmk = NULL;
  1362. }
  1363. if ( ikmsum != NULL )
  1364. {
  1365. delete ikmsum;
  1366. }
  1367. ikmsum = new IKMLinearCombination ();
  1368. if ( b_restoreVerbose )
  1369. std::cerr << "ikmsum object created" << std::endl;
  1370. _is.precision ( numeric_limits<double>::digits10 + 1 );
  1371. bool b_endOfBlock ( false ) ;
  1372. while ( !b_endOfBlock )
  1373. {
  1374. _is >> tmp; // start of block
  1375. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1376. {
  1377. b_endOfBlock = true;
  1378. continue;
  1379. }
  1380. tmp = this->removeStartTag ( tmp );
  1381. if ( b_restoreVerbose )
  1382. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1383. ///////////////////////////////////
  1384. // output/debug related settings //
  1385. ///////////////////////////////////
  1386. if ( tmp.compare("verbose") == 0 )
  1387. {
  1388. _is >> this->b_verbose;
  1389. _is >> tmp; // end of block
  1390. tmp = this->removeEndTag ( tmp );
  1391. }
  1392. else if ( tmp.compare("verboseTime") == 0 )
  1393. {
  1394. _is >> this->b_verboseTime;
  1395. _is >> tmp; // end of block
  1396. tmp = this->removeEndTag ( tmp );
  1397. }
  1398. else if ( tmp.compare("debug") == 0 )
  1399. {
  1400. _is >> this->b_debug;
  1401. _is >> tmp; // end of block
  1402. tmp = this->removeEndTag ( tmp );
  1403. }
  1404. //////////////////////////////////////
  1405. // classification related variables //
  1406. //////////////////////////////////////
  1407. else if ( tmp.compare("b_performRegression") == 0 )
  1408. {
  1409. _is >> this->b_performRegression;
  1410. _is >> tmp; // end of block
  1411. tmp = this->removeEndTag ( tmp );
  1412. }
  1413. else if ( tmp.compare("fmk") == 0 )
  1414. {
  1415. if ( this->fmk != NULL )
  1416. delete this->fmk;
  1417. this->fmk = new FastMinKernel();
  1418. this->fmk->restore( _is, _format );
  1419. _is >> tmp; // end of block
  1420. tmp = this->removeEndTag ( tmp );
  1421. }
  1422. else if ( tmp.compare("q") == 0 )
  1423. {
  1424. std::string isNull;
  1425. _is >> isNull; // NOTNULL or NULL
  1426. if (isNull.compare("NOTNULL") == 0)
  1427. {
  1428. if ( this->q != NULL )
  1429. delete this->q;
  1430. std::string s_quantType;
  1431. _is >> s_quantType;
  1432. s_quantType = this->removeStartTag ( s_quantType );
  1433. if ( s_quantType == "Quantization1DAequiDist0To1" )
  1434. {
  1435. this->q = new NICE::Quantization1DAequiDist0To1();
  1436. }
  1437. else if ( s_quantType == "Quantization1DAequiDist0ToMax" )
  1438. {
  1439. this->q = new NICE::Quantization1DAequiDist0ToMax ( );
  1440. }
  1441. else if ( s_quantType == "QuantizationNDAequiDist0ToMax" )
  1442. {
  1443. this->q = new NICE::QuantizationNDAequiDist0ToMax ( );
  1444. }
  1445. else
  1446. {
  1447. fthrow(Exception, "Quantization type is unknown " << s_quantType);
  1448. }
  1449. this->q->restore ( _is, _format );
  1450. }
  1451. else
  1452. {
  1453. if ( this->q != NULL )
  1454. delete this->q;
  1455. this->q = NULL;
  1456. }
  1457. _is >> tmp; // end of block
  1458. tmp = this->removeEndTag ( tmp );
  1459. }
  1460. else if ( tmp.compare("parameterUpperBound") == 0 )
  1461. {
  1462. _is >> this->d_parameterUpperBound;
  1463. _is >> tmp; // end of block
  1464. tmp = this->removeEndTag ( tmp );
  1465. }
  1466. else if ( tmp.compare("parameterLowerBound") == 0 )
  1467. {
  1468. _is >> this->d_parameterLowerBound;
  1469. _is >> tmp; // end of block
  1470. tmp = this->removeEndTag ( tmp );
  1471. }
  1472. else if ( tmp.compare("pf") == 0 )
  1473. {
  1474. _is >> tmp; // start of block
  1475. if ( this->isEndTag( tmp, "pf" ) )
  1476. {
  1477. std::cerr << " ParameterizedFunction object can not be restored. Aborting..." << std::endl;
  1478. throw;
  1479. }
  1480. std::string transform ( this->removeStartTag( tmp ) );
  1481. if ( transform == "PFAbsExp" )
  1482. {
  1483. this->pf = new NICE::PFAbsExp ();
  1484. } else if ( transform == "PFExp" ) {
  1485. this->pf = new NICE::PFExp ();
  1486. }
  1487. else if ( transform == "PFIdentity" )
  1488. {
  1489. this->pf = new NICE::PFIdentity( );
  1490. } else {
  1491. fthrow(Exception, "Transformation type is unknown " << transform);
  1492. }
  1493. this->pf->restore( _is, _format);
  1494. _is >> tmp; // end of block
  1495. tmp = this->removeEndTag ( tmp );
  1496. }
  1497. else if ( tmp.compare("precomputedA") == 0 )
  1498. {
  1499. _is >> tmp; // size
  1500. uint preCompSize ( 0 );
  1501. _is >> preCompSize;
  1502. this->precomputedA.clear();
  1503. if ( b_restoreVerbose )
  1504. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1505. for ( int i = 0; i < preCompSize; i++ )
  1506. {
  1507. uint nr;
  1508. _is >> nr;
  1509. PrecomputedType pct;
  1510. pct.setIoUntilEndOfFile ( false );
  1511. pct.restore ( _is, _format );
  1512. this->precomputedA.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1513. }
  1514. _is >> tmp; // end of block
  1515. tmp = this->removeEndTag ( tmp );
  1516. }
  1517. else if ( tmp.compare("precomputedB") == 0 )
  1518. {
  1519. _is >> tmp; // size
  1520. uint preCompSize ( 0 );
  1521. _is >> preCompSize;
  1522. this->precomputedB.clear();
  1523. if ( b_restoreVerbose )
  1524. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1525. for ( int i = 0; i < preCompSize; i++ )
  1526. {
  1527. uint nr;
  1528. _is >> nr;
  1529. PrecomputedType pct;
  1530. pct.setIoUntilEndOfFile ( false );
  1531. pct.restore ( _is, _format );
  1532. this->precomputedB.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1533. }
  1534. _is >> tmp; // end of block
  1535. tmp = this->removeEndTag ( tmp );
  1536. }
  1537. else if ( tmp.compare("precomputedT") == 0 )
  1538. {
  1539. _is >> tmp; // size
  1540. uint precomputedTSize ( 0 );
  1541. _is >> precomputedTSize;
  1542. this->precomputedT.clear();
  1543. if ( b_restoreVerbose )
  1544. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1545. if ( precomputedTSize > 0 )
  1546. {
  1547. if ( b_restoreVerbose )
  1548. std::cerr << " restore precomputedT" << std::endl;
  1549. _is >> tmp;
  1550. int sizeOfLUT;
  1551. _is >> sizeOfLUT;
  1552. for (int i = 0; i < precomputedTSize; i++)
  1553. {
  1554. _is >> tmp;
  1555. uint index;
  1556. _is >> index;
  1557. double * array = new double [ sizeOfLUT];
  1558. for ( int i = 0; i < sizeOfLUT; i++ )
  1559. {
  1560. _is >> array[i];
  1561. }
  1562. this->precomputedT.insert ( std::pair<uint, double*> ( index, array ) );
  1563. }
  1564. }
  1565. else
  1566. {
  1567. if ( b_restoreVerbose )
  1568. std::cerr << " skip restoring precomputedT" << std::endl;
  1569. }
  1570. _is >> tmp; // end of block
  1571. tmp = this->removeEndTag ( tmp );
  1572. }
  1573. else if ( tmp.compare("labels") == 0 )
  1574. {
  1575. _is >> this->labels;
  1576. _is >> tmp; // end of block
  1577. tmp = this->removeEndTag ( tmp );
  1578. }
  1579. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1580. {
  1581. _is >> this->i_binaryLabelPositive;
  1582. _is >> tmp; // end of block
  1583. tmp = this->removeEndTag ( tmp );
  1584. }
  1585. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1586. {
  1587. _is >> this->i_binaryLabelNegative;
  1588. _is >> tmp; // end of block
  1589. tmp = this->removeEndTag ( tmp );
  1590. }
  1591. else if ( tmp.compare("knownClasses") == 0 )
  1592. {
  1593. _is >> tmp; // size
  1594. uint knownClassesSize ( 0 );
  1595. _is >> knownClassesSize;
  1596. this->knownClasses.clear();
  1597. if ( knownClassesSize > 0 )
  1598. {
  1599. for (uint i = 0; i < knownClassesSize; i++)
  1600. {
  1601. uint classNo;
  1602. _is >> classNo;
  1603. this->knownClasses.insert ( classNo );
  1604. }
  1605. }
  1606. else
  1607. {
  1608. //nothing to do
  1609. }
  1610. _is >> tmp; // end of block
  1611. tmp = this->removeEndTag ( tmp );
  1612. }
  1613. else if ( tmp.compare("ikmsum") == 0 )
  1614. {
  1615. bool b_endOfBlock ( false ) ;
  1616. while ( !b_endOfBlock )
  1617. {
  1618. _is >> tmp; // start of block
  1619. if ( this->isEndTag( tmp, "ikmsum" ) )
  1620. {
  1621. b_endOfBlock = true;
  1622. continue;
  1623. }
  1624. tmp = this->removeStartTag ( tmp );
  1625. if ( tmp.compare("IKMNoise") == 0 )
  1626. {
  1627. IKMNoise * ikmnoise = new IKMNoise ();
  1628. ikmnoise->restore ( _is, _format );
  1629. if ( b_restoreVerbose )
  1630. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1631. ikmsum->addModel ( ikmnoise );
  1632. }
  1633. else
  1634. {
  1635. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1636. throw;
  1637. }
  1638. }
  1639. }
  1640. //////////////////////////////////////////////
  1641. // Iterative Linear Solver //
  1642. //////////////////////////////////////////////
  1643. else if ( tmp.compare("linsolver") == 0 )
  1644. {
  1645. //TODO linsolver
  1646. // current solution: hard coded with default values, since LinearSolver does not offer Persistent functionalities
  1647. this->linsolver = new ILSConjugateGradients ( false , 1000, 1e-7, 1e-7 );
  1648. _is >> tmp; // end of block
  1649. tmp = this->removeEndTag ( tmp );
  1650. }
  1651. else if ( tmp.compare("ils_max_iterations") == 0 )
  1652. {
  1653. _is >> ils_max_iterations;
  1654. _is >> tmp; // end of block
  1655. tmp = this->removeEndTag ( tmp );
  1656. }
  1657. /////////////////////////////////////
  1658. // optimization related parameters //
  1659. /////////////////////////////////////
  1660. else if ( tmp.compare("optimizationMethod") == 0 )
  1661. {
  1662. unsigned int ui_optimizationMethod;
  1663. _is >> ui_optimizationMethod;
  1664. optimizationMethod = static_cast<OPTIMIZATIONTECHNIQUE> ( ui_optimizationMethod ) ;
  1665. _is >> tmp; // end of block
  1666. tmp = this->removeEndTag ( tmp );
  1667. }
  1668. else if ( tmp.compare("optimizeNoise") == 0 )
  1669. {
  1670. _is >> optimizeNoise;
  1671. _is >> tmp; // end of block
  1672. tmp = this->removeEndTag ( tmp );
  1673. }
  1674. else if ( tmp.compare("parameterStepSize") == 0 )
  1675. {
  1676. _is >> parameterStepSize;
  1677. _is >> tmp; // end of block
  1678. tmp = this->removeEndTag ( tmp );
  1679. }
  1680. else if ( tmp.compare("downhillSimplexMaxIterations") == 0 )
  1681. {
  1682. _is >> downhillSimplexMaxIterations;
  1683. _is >> tmp; // end of block
  1684. tmp = this->removeEndTag ( tmp );
  1685. }
  1686. else if ( tmp.compare("downhillSimplexTimeLimit") == 0 )
  1687. {
  1688. _is >> downhillSimplexTimeLimit;
  1689. _is >> tmp; // end of block
  1690. tmp = this->removeEndTag ( tmp );
  1691. }
  1692. else if ( tmp.compare("downhillSimplexParamTol") == 0 )
  1693. {
  1694. _is >> downhillSimplexParamTol;
  1695. _is >> tmp; // end of block
  1696. tmp = this->removeEndTag ( tmp );
  1697. }
  1698. //////////////////////////////////////////////
  1699. // likelihood computation related variables //
  1700. //////////////////////////////////////////////
  1701. else if ( tmp.compare("verifyApproximation") == 0 )
  1702. {
  1703. _is >> verifyApproximation;
  1704. _is >> tmp; // end of block
  1705. tmp = this->removeEndTag ( tmp );
  1706. }
  1707. else if ( tmp.compare("eig") == 0 )
  1708. {
  1709. //TODO eig
  1710. // currently hard coded, since EV does not offer Persistent functionalities and
  1711. // in addition, we currently have no other choice for EV then EVArnoldi
  1712. this->eig = new EVArnoldi ( false /*eig_verbose */, 10 /*_maxiterations*/ );
  1713. _is >> tmp; // end of block
  1714. tmp = this->removeEndTag ( tmp );
  1715. }
  1716. else if ( tmp.compare("nrOfEigenvaluesToConsider") == 0 )
  1717. {
  1718. _is >> nrOfEigenvaluesToConsider;
  1719. _is >> tmp; // end of block
  1720. tmp = this->removeEndTag ( tmp );
  1721. }
  1722. else if ( tmp.compare("eigenMax") == 0 )
  1723. {
  1724. _is >> eigenMax;
  1725. _is >> tmp; // end of block
  1726. tmp = this->removeEndTag ( tmp );
  1727. }
  1728. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1729. {
  1730. _is >> eigenMaxVectors;
  1731. _is >> tmp; // end of block
  1732. tmp = this->removeEndTag ( tmp );
  1733. }
  1734. ////////////////////////////////////////////
  1735. // variance computation related variables //
  1736. ////////////////////////////////////////////
  1737. else if ( tmp.compare("nrOfEigenvaluesToConsiderForVarApprox") == 0 )
  1738. {
  1739. _is >> nrOfEigenvaluesToConsiderForVarApprox;
  1740. _is >> tmp; // end of block
  1741. tmp = this->removeEndTag ( tmp );
  1742. }
  1743. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1744. {
  1745. int sizeOfAForVarEst;
  1746. _is >> sizeOfAForVarEst;
  1747. if ( b_restoreVerbose )
  1748. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1749. if (sizeOfAForVarEst > 0)
  1750. {
  1751. precomputedAForVarEst.clear();
  1752. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1753. precomputedAForVarEst.restore ( _is, _format );
  1754. }
  1755. _is >> tmp; // end of block
  1756. tmp = this->removeEndTag ( tmp );
  1757. }
  1758. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1759. {
  1760. std::string isNull;
  1761. _is >> isNull; // NOTNULL or NULL
  1762. if ( b_restoreVerbose )
  1763. std::cerr << "content of isNull: " << isNull << std::endl;
  1764. if (isNull.compare("NOTNULL") == 0)
  1765. {
  1766. if ( b_restoreVerbose )
  1767. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1768. int sizeOfLUT;
  1769. _is >> sizeOfLUT;
  1770. precomputedTForVarEst = new double [ sizeOfLUT ];
  1771. for ( int i = 0; i < sizeOfLUT; i++ )
  1772. {
  1773. _is >> precomputedTForVarEst[i];
  1774. }
  1775. }
  1776. else
  1777. {
  1778. if ( b_restoreVerbose )
  1779. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1780. if (precomputedTForVarEst != NULL)
  1781. delete precomputedTForVarEst;
  1782. }
  1783. _is >> tmp; // end of block
  1784. tmp = this->removeEndTag ( tmp );
  1785. }
  1786. /////////////////////////////////////////////////////
  1787. // online / incremental learning related variables //
  1788. /////////////////////////////////////////////////////
  1789. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1790. {
  1791. _is >> b_usePreviousAlphas;
  1792. _is >> tmp; // end of block
  1793. tmp = this->removeEndTag ( tmp );
  1794. }
  1795. else if ( tmp.compare("previousAlphas") == 0 )
  1796. {
  1797. _is >> tmp; // size
  1798. uint sizeOfPreviousAlphas ( 0 );
  1799. _is >> sizeOfPreviousAlphas;
  1800. this->previousAlphas.clear();
  1801. if ( b_restoreVerbose )
  1802. std::cerr << "restore previousAlphas with size: " << sizeOfPreviousAlphas << std::endl;
  1803. for ( int i = 0; i < sizeOfPreviousAlphas; i++ )
  1804. {
  1805. uint classNo;
  1806. _is >> classNo;
  1807. NICE::Vector classAlpha;
  1808. _is >> classAlpha;
  1809. this->previousAlphas.insert ( std::pair< uint, NICE::Vector > ( classNo, classAlpha ) );
  1810. }
  1811. _is >> tmp; // end of block
  1812. tmp = this->removeEndTag ( tmp );
  1813. }
  1814. else
  1815. {
  1816. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1817. throw;
  1818. }
  1819. }
  1820. //NOTE are there any more models you added? then add them here respectively in the correct order
  1821. //.....
  1822. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1823. if ( b_restoreVerbose )
  1824. std::cerr << " add GMHIKernel" << std::endl;
  1825. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1826. if ( b_restoreVerbose )
  1827. std::cerr << " restore positive and negative label" << std::endl;
  1828. this->knownClasses.clear();
  1829. if ( b_restoreVerbose )
  1830. std::cerr << " fill known classes object " << std::endl;
  1831. if ( this->precomputedA.size() == 1)
  1832. {
  1833. this->knownClasses.insert( this->i_binaryLabelPositive );
  1834. this->knownClasses.insert( this->i_binaryLabelNegative );
  1835. if ( b_restoreVerbose )
  1836. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1837. }
  1838. else
  1839. {
  1840. for ( std::map<uint, PrecomputedType>::const_iterator itA = this->precomputedA.begin(); itA != this->precomputedA.end(); itA++)
  1841. knownClasses.insert ( itA->first );
  1842. if ( b_restoreVerbose )
  1843. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1844. }
  1845. }
  1846. else
  1847. {
  1848. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1849. throw;
  1850. }
  1851. }
  1852. void FMKGPHyperparameterOptimization::store ( std::ostream & _os,
  1853. int _format
  1854. ) const
  1855. {
  1856. if ( _os.good() )
  1857. {
  1858. // show starting point
  1859. _os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1860. // _os.precision ( numeric_limits<double>::digits10 + 1 );
  1861. ///////////////////////////////////
  1862. // output/debug related settings //
  1863. ///////////////////////////////////
  1864. _os << this->createStartTag( "verbose" ) << std::endl;
  1865. _os << this->b_verbose << std::endl;
  1866. _os << this->createEndTag( "verbose" ) << std::endl;
  1867. _os << this->createStartTag( "verboseTime" ) << std::endl;
  1868. _os << this->b_verboseTime << std::endl;
  1869. _os << this->createEndTag( "verboseTime" ) << std::endl;
  1870. _os << this->createStartTag( "debug" ) << std::endl;
  1871. _os << this->b_debug << std::endl;
  1872. _os << this->createEndTag( "debug" ) << std::endl;
  1873. //////////////////////////////////////
  1874. // classification related variables //
  1875. //////////////////////////////////////
  1876. _os << this->createStartTag( "b_performRegression" ) << std::endl;
  1877. _os << b_performRegression << std::endl;
  1878. _os << this->createEndTag( "b_performRegression" ) << std::endl;
  1879. _os << this->createStartTag( "fmk" ) << std::endl;
  1880. this->fmk->store ( _os, _format );
  1881. _os << this->createEndTag( "fmk" ) << std::endl;
  1882. _os << this->createStartTag( "q" ) << std::endl;
  1883. if ( q != NULL )
  1884. {
  1885. _os << "NOTNULL" << std::endl;
  1886. this->q->store ( _os, _format );
  1887. }
  1888. else
  1889. {
  1890. _os << "NULL" << std::endl;
  1891. }
  1892. _os << this->createEndTag( "q" ) << std::endl;
  1893. _os << this->createStartTag( "parameterUpperBound" ) << std::endl;
  1894. _os << this->d_parameterUpperBound << std::endl;
  1895. _os << this->createEndTag( "parameterUpperBound" ) << std::endl;
  1896. _os << this->createStartTag( "parameterLowerBound" ) << std::endl;
  1897. _os << this->d_parameterLowerBound << std::endl;
  1898. _os << this->createEndTag( "parameterLowerBound" ) << std::endl;
  1899. _os << this->createStartTag( "pf" ) << std::endl;
  1900. this->pf->store(_os, _format);
  1901. _os << this->createEndTag( "pf" ) << std::endl;
  1902. _os << this->createStartTag( "precomputedA" ) << std::endl;
  1903. _os << "size: " << this->precomputedA.size() << std::endl;
  1904. std::map< uint, PrecomputedType >::const_iterator preCompIt = this->precomputedA.begin();
  1905. for ( uint i = 0; i < this->precomputedA.size(); i++ )
  1906. {
  1907. _os << preCompIt->first << std::endl;
  1908. ( preCompIt->second ).store ( _os, _format );
  1909. preCompIt++;
  1910. }
  1911. _os << this->createEndTag( "precomputedA" ) << std::endl;
  1912. _os << this->createStartTag( "precomputedB" ) << std::endl;
  1913. _os << "size: " << this->precomputedB.size() << std::endl;
  1914. preCompIt = this->precomputedB.begin();
  1915. for ( uint i = 0; i < this->precomputedB.size(); i++ )
  1916. {
  1917. _os << preCompIt->first << std::endl;
  1918. ( preCompIt->second ).store ( _os, _format );
  1919. preCompIt++;
  1920. }
  1921. _os << this->createEndTag( "precomputedB" ) << std::endl;
  1922. _os << this->createStartTag( "precomputedT" ) << std::endl;
  1923. _os << "size: " << this->precomputedT.size() << std::endl;
  1924. if ( this->precomputedT.size() > 0 )
  1925. {
  1926. int sizeOfLUT ( 0 );
  1927. if ( q != NULL )
  1928. sizeOfLUT = q->getNumberOfBins() * this->fmk->get_d();
  1929. _os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1930. for ( std::map< uint, double * >::const_iterator it = this->precomputedT.begin(); it != this->precomputedT.end(); it++ )
  1931. {
  1932. _os << "index: " << it->first << std::endl;
  1933. for ( int i = 0; i < sizeOfLUT; i++ )
  1934. {
  1935. _os << ( it->second ) [i] << " ";
  1936. }
  1937. _os << std::endl;
  1938. }
  1939. }
  1940. _os << this->createEndTag( "precomputedT" ) << std::endl;
  1941. _os << this->createStartTag( "labels" ) << std::endl;
  1942. _os << this->labels << std::endl;
  1943. _os << this->createEndTag( "labels" ) << std::endl;
  1944. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1945. _os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1946. _os << this->i_binaryLabelPositive << std::endl;
  1947. _os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1948. _os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1949. _os << this->i_binaryLabelNegative << std::endl;
  1950. _os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1951. _os << this->createStartTag( "knownClasses" ) << std::endl;
  1952. _os << "size: " << this->knownClasses.size() << std::endl;
  1953. for ( std::set< uint >::const_iterator itKnownClasses = this->knownClasses.begin();
  1954. itKnownClasses != this->knownClasses.end();
  1955. itKnownClasses++
  1956. )
  1957. {
  1958. _os << *itKnownClasses << " " << std::endl;
  1959. }
  1960. _os << this->createEndTag( "knownClasses" ) << std::endl;
  1961. _os << this->createStartTag( "ikmsum" ) << std::endl;
  1962. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1963. {
  1964. ( ikmsum->getModel ( j ) )->store ( _os, _format );
  1965. }
  1966. _os << this->createEndTag( "ikmsum" ) << std::endl;
  1967. //////////////////////////////////////////////
  1968. // Iterative Linear Solver //
  1969. //////////////////////////////////////////////
  1970. _os << this->createStartTag( "linsolver" ) << std::endl;
  1971. //TODO linsolver
  1972. _os << this->createEndTag( "linsolver" ) << std::endl;
  1973. _os << this->createStartTag( "ils_max_iterations" ) << std::endl;
  1974. _os << this->ils_max_iterations << std::endl;
  1975. _os << this->createEndTag( "ils_max_iterations" ) << std::endl;
  1976. /////////////////////////////////////
  1977. // optimization related parameters //
  1978. /////////////////////////////////////
  1979. _os << this->createStartTag( "optimizationMethod" ) << std::endl;
  1980. _os << this->optimizationMethod << std::endl;
  1981. _os << this->createEndTag( "optimizationMethod" ) << std::endl;
  1982. _os << this->createStartTag( "optimizeNoise" ) << std::endl;
  1983. _os << this->optimizeNoise << std::endl;
  1984. _os << this->createEndTag( "optimizeNoise" ) << std::endl;
  1985. _os << this->createStartTag( "parameterStepSize" ) << std::endl;
  1986. _os << this->parameterStepSize << std::endl;
  1987. _os << this->createEndTag( "parameterStepSize" ) << std::endl;
  1988. _os << this->createStartTag( "downhillSimplexMaxIterations" ) << std::endl;
  1989. _os << this->downhillSimplexMaxIterations << std::endl;
  1990. _os << this->createEndTag( "downhillSimplexMaxIterations" ) << std::endl;
  1991. _os << this->createStartTag( "downhillSimplexTimeLimit" ) << std::endl;
  1992. _os << this->downhillSimplexTimeLimit << std::endl;
  1993. _os << this->createEndTag( "downhillSimplexTimeLimit" ) << std::endl;
  1994. _os << this->createStartTag( "downhillSimplexParamTol" ) << std::endl;
  1995. _os << this->downhillSimplexParamTol << std::endl;
  1996. _os << this->createEndTag( "downhillSimplexParamTol" ) << std::endl;
  1997. //////////////////////////////////////////////
  1998. // likelihood computation related variables //
  1999. //////////////////////////////////////////////
  2000. _os << this->createStartTag( "verifyApproximation" ) << std::endl;
  2001. _os << this->verifyApproximation << std::endl;
  2002. _os << this->createEndTag( "verifyApproximation" ) << std::endl;
  2003. _os << this->createStartTag( "eig" ) << std::endl;
  2004. //TODO eig
  2005. _os << this->createEndTag( "eig" ) << std::endl;
  2006. _os << this->createStartTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2007. _os << this->nrOfEigenvaluesToConsider << std::endl;
  2008. _os << this->createEndTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2009. _os << this->createStartTag( "eigenMax" ) << std::endl;
  2010. _os << this->eigenMax << std::endl;
  2011. _os << this->createEndTag( "eigenMax" ) << std::endl;
  2012. _os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  2013. _os << this->eigenMaxVectors << std::endl;
  2014. _os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  2015. ////////////////////////////////////////////
  2016. // variance computation related variables //
  2017. ////////////////////////////////////////////
  2018. _os << this->createStartTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2019. _os << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  2020. _os << this->createEndTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2021. _os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  2022. _os << precomputedAForVarEst.size() << std::endl;
  2023. if ( this->precomputedAForVarEst.size() > 0)
  2024. {
  2025. this->precomputedAForVarEst.store ( _os, _format );
  2026. _os << std::endl;
  2027. }
  2028. _os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  2029. _os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  2030. if ( this->precomputedTForVarEst != NULL )
  2031. {
  2032. _os << "NOTNULL" << std::endl;
  2033. int sizeOfLUT ( 0 );
  2034. if ( q != NULL )
  2035. sizeOfLUT = q->getNumberOfBins() * this->fmk->get_d();
  2036. _os << sizeOfLUT << std::endl;
  2037. for ( int i = 0; i < sizeOfLUT; i++ )
  2038. {
  2039. _os << this->precomputedTForVarEst[i] << " ";
  2040. }
  2041. _os << std::endl;
  2042. }
  2043. else
  2044. {
  2045. _os << "NULL" << std::endl;
  2046. }
  2047. _os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  2048. /////////////////////////////////////////////////////
  2049. // online / incremental learning related variables //
  2050. /////////////////////////////////////////////////////
  2051. _os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  2052. _os << this->b_usePreviousAlphas << std::endl;
  2053. _os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  2054. _os << this->createStartTag( "previousAlphas" ) << std::endl;
  2055. _os << "size: " << this->previousAlphas.size() << std::endl;
  2056. std::map< uint, NICE::Vector >::const_iterator prevAlphaIt = this->previousAlphas.begin();
  2057. for ( uint i = 0; i < this->previousAlphas.size(); i++ )
  2058. {
  2059. _os << prevAlphaIt->first << std::endl;
  2060. _os << prevAlphaIt->second << std::endl;
  2061. prevAlphaIt++;
  2062. }
  2063. _os << this->createEndTag( "previousAlphas" ) << std::endl;
  2064. // done
  2065. _os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  2066. }
  2067. else
  2068. {
  2069. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  2070. }
  2071. }
  2072. void FMKGPHyperparameterOptimization::clear ( ) {};
  2073. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2074. // interface specific methods for incremental extensions
  2075. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2076. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  2077. const double & label,
  2078. const bool & performOptimizationAfterIncrement
  2079. )
  2080. {
  2081. if ( this->b_verbose )
  2082. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  2083. NICE::Timer t;
  2084. t.start();
  2085. std::set< uint > newClasses;
  2086. this->labels.append ( label );
  2087. //have we seen this class already?
  2088. if ( !this->b_performRegression && ( this->knownClasses.find( label ) == this->knownClasses.end() ) )
  2089. {
  2090. this->knownClasses.insert( label );
  2091. newClasses.insert( label );
  2092. }
  2093. // If we currently have been in a binary setting, we now have to take care
  2094. // that we also compute an alpha vector for the second class, which previously
  2095. // could be dealt with implicitely.
  2096. // Therefore, we insert its label here...
  2097. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2098. newClasses.insert( this->i_binaryLabelNegative );
  2099. // add the new example to our data structure
  2100. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2101. NICE::Timer tFmk;
  2102. tFmk.start();
  2103. this->fmk->addExample ( example, pf );
  2104. tFmk.stop();
  2105. if ( this->b_verboseTime)
  2106. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2107. // add examples to all implicite kernel matrices we currently use
  2108. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  2109. // update the corresponding matrices A, B and lookup tables T
  2110. // optional: do the optimization again using the previously known solutions as initialization
  2111. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2112. //clean up
  2113. newClasses.clear();
  2114. t.stop();
  2115. NICE::ResourceStatistics rs;
  2116. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2117. long maxMemory;
  2118. rs.getMaximumMemory ( maxMemory );
  2119. if ( this->b_verbose )
  2120. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2121. if ( this->b_verbose )
  2122. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  2123. }
  2124. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  2125. const NICE::Vector & newLabels,
  2126. const bool & performOptimizationAfterIncrement
  2127. )
  2128. {
  2129. if ( this->b_verbose )
  2130. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples --- " << std::endl;
  2131. NICE::Timer t;
  2132. t.start();
  2133. std::set< uint > newClasses;
  2134. this->labels.append ( newLabels );
  2135. //have we seen this class already?
  2136. if ( !this->b_performRegression)
  2137. {
  2138. for ( NICE::Vector::const_iterator vecIt = newLabels.begin();
  2139. vecIt != newLabels.end();
  2140. vecIt++
  2141. )
  2142. {
  2143. if ( this->knownClasses.find( *vecIt ) == this->knownClasses.end() )
  2144. {
  2145. this->knownClasses.insert( *vecIt );
  2146. newClasses.insert( *vecIt );
  2147. }
  2148. }
  2149. // If we currently have been in a OCC setting, and only add a single new class
  2150. // we have to take care that are still efficient, i.e., that we solve for alpha
  2151. // only ones, since scores are symmetric in binary cases
  2152. // Therefore, we remove the label of the secodn class from newClasses, to skip
  2153. // alpha computations for this class lateron...
  2154. //
  2155. // Therefore, we insert its label here...
  2156. if ( (newClasses.size() == 1 ) && ( (this->knownClasses.size() - newClasses.size() ) == 1 ) )
  2157. newClasses.clear();
  2158. // If we currently have been in a binary setting, we now have to take care
  2159. // that we also compute an alpha vector for the second class, which previously
  2160. // could be dealt with implicitely.
  2161. // Therefore, we insert its label here...
  2162. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2163. newClasses.insert( this->i_binaryLabelNegative );
  2164. }
  2165. // in a regression setting, we do not have to remember any "class labels"
  2166. else{}
  2167. // add the new example to our data structure
  2168. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2169. NICE::Timer tFmk;
  2170. tFmk.start();
  2171. this->fmk->addMultipleExamples ( newExamples, pf );
  2172. tFmk.stop();
  2173. if ( this->b_verboseTime)
  2174. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2175. // add examples to all implicite kernel matrices we currently use
  2176. this->ikmsum->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  2177. // update the corresponding matrices A, B and lookup tables T
  2178. // optional: do the optimization again using the previously known solutions as initialization
  2179. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2180. //clean up
  2181. newClasses.clear();
  2182. t.stop();
  2183. NICE::ResourceStatistics rs;
  2184. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2185. long maxMemory;
  2186. rs.getMaximumMemory ( maxMemory );
  2187. if ( this->b_verbose )
  2188. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2189. if ( this->b_verbose )
  2190. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples done --- " << std::endl;
  2191. }