FMKGPHyperparameterOptimization.cpp 64 KB

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