FMKGPHyperparameterOptimization.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization()
  35. {
  36. // initialize pointer variables
  37. pf = NULL;
  38. eig = NULL;
  39. linsolver = NULL;
  40. fmk = NULL;
  41. q = NULL;
  42. precomputedTForVarEst = NULL;
  43. ikmsum = NULL;
  44. // initialize boolean flags
  45. verbose = false;
  46. verboseTime = false;
  47. debug = false;
  48. //stupid unneeded default values
  49. binaryLabelPositive = -1;
  50. binaryLabelNegative = -2;
  51. }
  52. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const string & _confSection )
  53. {
  54. // initialize pointer variables
  55. pf = NULL;
  56. eig = NULL;
  57. linsolver = NULL;
  58. fmk = NULL;
  59. q = NULL;
  60. precomputedTForVarEst = NULL;
  61. ikmsum = NULL;
  62. //stupid unneeded default values
  63. binaryLabelPositive = -1;
  64. binaryLabelNegative = -2;
  65. knownClasses.clear();
  66. //TODO
  67. if ( _fmk == NULL )
  68. this->initialize ( _conf, _pf ); //then the confSection is also the default value
  69. else
  70. this->initialize ( _conf, _pf, _fmk, _confSection );
  71. }
  72. FMKGPHyperparameterOptimization::~FMKGPHyperparameterOptimization()
  73. {
  74. //pf will delete from outer program
  75. if ( this->eig != NULL )
  76. delete this->eig;
  77. if ( this->linsolver != NULL )
  78. delete this->linsolver;
  79. if ( this->fmk != NULL )
  80. delete this->fmk;
  81. if ( this->q != NULL )
  82. delete this->q;
  83. for ( uint i = 0 ; i < precomputedT.size(); i++ )
  84. delete [] ( precomputedT[i] );
  85. if ( precomputedTForVarEst != NULL )
  86. delete precomputedTForVarEst;
  87. if ( ikmsum != NULL )
  88. delete ikmsum;
  89. }
  90. void FMKGPHyperparameterOptimization::initialize ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const std::string & _confSection )
  91. {
  92. if ( _fmk != NULL )
  93. {
  94. if ( this->fmk != NULL )
  95. {
  96. delete this->fmk;
  97. fmk = NULL;
  98. }
  99. this->fmk = _fmk;
  100. }
  101. this->pf = _pf;
  102. this->verbose = _conf->gB ( _confSection, "verbose", false );
  103. this->verboseTime = _conf->gB ( _confSection, "verboseTime", false );
  104. this->debug = _conf->gB ( _confSection, "debug", false );
  105. if ( verbose )
  106. {
  107. std::cerr << "------------" << std::endl;
  108. std::cerr << "| set-up |" << std::endl;
  109. std::cerr << "------------" << std::endl;
  110. }
  111. this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */, 10 );
  112. // this->eig = new EigValuesTRLAN();
  113. // My time measurements show that both methods use equal time, a comparision
  114. // of their numerical performance has not been done yet
  115. this->parameterUpperBound = _conf->gD ( _confSection, "parameter_upper_bound", 2.5 );
  116. this->parameterLowerBound = _conf->gD ( _confSection, "parameter_lower_bound", 1.0 );
  117. this->parameterStepSize = _conf->gD ( _confSection, "parameter_step_size", 0.1 );
  118. this->verifyApproximation = _conf->gB ( _confSection, "verify_approximation", false );
  119. this->nrOfEigenvaluesToConsider = _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 );
  120. this->nrOfEigenvaluesToConsiderForVarApprox = _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 2 );
  121. bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
  122. if ( verbose )
  123. {
  124. std::cerr << "_confSection: " << _confSection << std::endl;
  125. std::cerr << "use_quantization: " << useQuantization << std::endl;
  126. }
  127. if ( _conf->gB ( _confSection, "use_quantization", false ) ) {
  128. int numBins = _conf->gI ( _confSection, "num_bins", 100 );
  129. if ( verbose )
  130. std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
  131. this->q = new Quantization ( numBins );
  132. } else {
  133. this->q = NULL;
  134. }
  135. bool ils_verbose = _conf->gB ( _confSection, "ils_verbose", false );
  136. ils_max_iterations = _conf->gI ( _confSection, "ils_max_iterations", 1000 );
  137. if ( verbose )
  138. std::cerr << "FMKGPHyperparameterOptimization: maximum number of iterations is " << ils_max_iterations << std::endl;
  139. double ils_min_delta = _conf->gD ( _confSection, "ils_min_delta", 1e-7 );
  140. double ils_min_residual = _conf->gD ( _confSection, "ils_min_residual", 1e-7/*1e-2 */ );
  141. string ils_method = _conf->gS ( _confSection, "ils_method", "CG" );
  142. if ( ils_method.compare ( "CG" ) == 0 )
  143. {
  144. if ( verbose )
  145. 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;
  146. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  147. if ( verbose )
  148. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients" << std::endl;
  149. }
  150. else if ( ils_method.compare ( "CGL" ) == 0 )
  151. {
  152. this->linsolver = new ILSConjugateGradientsLanczos ( ils_verbose , ils_max_iterations );
  153. if ( verbose )
  154. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients (Lanczos)" << std::endl;
  155. }
  156. else if ( ils_method.compare ( "SYMMLQ" ) == 0 )
  157. {
  158. this->linsolver = new ILSSymmLqLanczos ( ils_verbose , ils_max_iterations );
  159. if ( verbose )
  160. std::cerr << "FMKGPHyperparameterOptimization: using ILS SYMMLQ" << std::endl;
  161. }
  162. else if ( ils_method.compare ( "MINRES" ) == 0 )
  163. {
  164. this->linsolver = new ILSMinResLanczos ( ils_verbose , ils_max_iterations );
  165. if ( verbose )
  166. std::cerr << "FMKGPHyperparameterOptimization: using ILS MINRES" << std::endl;
  167. }
  168. else
  169. {
  170. std::cerr << "FMKGPHyperparameterOptimization: " << _confSection << ":ils_method (" << ils_method << ") does not match any type (CG,CGL,SYMMLQ,MINRES), I will use CG" << std::endl;
  171. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  172. }
  173. string optimizationMethod_s = _conf->gS ( _confSection, "optimization_method", "greedy" );
  174. if ( optimizationMethod_s == "greedy" )
  175. optimizationMethod = OPT_GREEDY;
  176. else if ( optimizationMethod_s == "downhillsimplex" )
  177. optimizationMethod = OPT_DOWNHILLSIMPLEX;
  178. else if ( optimizationMethod_s == "none" )
  179. optimizationMethod = OPT_NONE;
  180. else
  181. fthrow ( Exception, "Optimization method " << optimizationMethod_s << " is not known." );
  182. if ( verbose )
  183. std::cerr << "Using optimization method: " << optimizationMethod_s << std::endl;
  184. downhillSimplexMaxIterations = _conf->gI ( _confSection, "downhillsimplex_max_iterations", 20 );
  185. // do not run longer than a day :)
  186. downhillSimplexTimeLimit = _conf->gD ( _confSection, "downhillsimplex_time_limit", 24 * 60 * 60 );
  187. downhillSimplexParamTol = _conf->gD ( _confSection, "downhillsimplex_delta", 0.01 );
  188. optimizeNoise = _conf->gB ( _confSection, "optimize_noise", false );
  189. if ( verbose )
  190. std::cerr << "Optimize noise: " << ( optimizeNoise ? "on" : "off" ) << std::endl;
  191. if ( verbose )
  192. {
  193. std::cerr << "------------" << std::endl;
  194. std::cerr << "| start |" << std::endl;
  195. std::cerr << "------------" << std::endl;
  196. }
  197. }
  198. // get and set methods
  199. void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
  200. {
  201. parameterUpperBound = _parameterUpperBound;
  202. }
  203. void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
  204. {
  205. parameterLowerBound = _parameterLowerBound;
  206. }
  207. std::set<int> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
  208. {
  209. return this->knownClasses;
  210. }
  211. //high level methods
  212. void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize )
  213. {
  214. gplike = new GPLikelihoodApprox ( binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
  215. gplike->setDebug( debug );
  216. gplike->setVerbose( verbose );
  217. parameterVectorSize = ikmsum->getNumParameters();
  218. }
  219. void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & i_noEigenValues )
  220. {
  221. //compute the largest eigenvalue of K + noise
  222. try
  223. {
  224. eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, i_noEigenValues );
  225. }
  226. catch ( char const* exceptionMsg)
  227. {
  228. std::cerr << exceptionMsg << std::endl;
  229. throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
  230. }
  231. // EigenValue computation does not necessarily extract them in decreasing order.
  232. // Therefore: sort eigenvalues decreasingly!
  233. NICE::VectorT< int > ewPermutation;
  234. eigenMax.sortDescend ( ewPermutation );
  235. }
  236. void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  237. {
  238. if (verbose)
  239. std::cerr << "perform optimization" << std::endl;
  240. if ( optimizationMethod == OPT_GREEDY )
  241. {
  242. if ( verbose )
  243. std::cerr << "OPT_GREEDY!!! " << std::endl;
  244. // simple greedy strategy
  245. if ( ikmsum->getNumParameters() != 1 )
  246. fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
  247. NICE::Vector lB = ikmsum->getParameterLowerBounds();
  248. NICE::Vector uB = ikmsum->getParameterUpperBounds();
  249. if ( verbose )
  250. std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
  251. NICE::Vector tmp = gplike.getBestParameters( );
  252. for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
  253. {
  254. OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
  255. gplike.evaluate ( hyperp );
  256. }
  257. }
  258. else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
  259. {
  260. //standard as before, normal optimization
  261. if ( verbose )
  262. std::cerr << "DOWNHILLSIMPLEX WITHOUT BALANCED LEARNING!!! " << std::endl;
  263. // downhill simplex strategy
  264. OPTIMIZATION::DownhillSimplexOptimizer optimizer;
  265. OPTIMIZATION::matrix_type initialParams ( parameterVectorSize, 1 );
  266. NICE::Vector currentParameters;
  267. ikmsum->getParameters ( currentParameters );
  268. for ( uint i = 0 ; i < parameterVectorSize; i++ )
  269. initialParams(i,0) = currentParameters[ i ];
  270. if ( verbose )
  271. std::cerr << "Initial parameters: " << initialParams << std::endl;
  272. //the scales object does not really matter in the actual implementation of Downhill Simplex
  273. //OPTIMIZATION::matrix_type scales ( parameterVectorSize, 1);
  274. //cales.Set(1.0);
  275. OPTIMIZATION::SimpleOptProblem optProblem ( &gplike, initialParams, initialParams /* scales*/ );
  276. // std::cerr << "OPT: " << mypara << " " << nlikelihood << " " << logdet << " " << dataterm << std::endl;
  277. optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
  278. optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
  279. optimizer.setParamTol ( true, downhillSimplexParamTol );
  280. optimizer.optimizeProb ( optProblem );
  281. }
  282. else if ( optimizationMethod == OPT_NONE )
  283. {
  284. if ( verbose )
  285. std::cerr << "NO OPTIMIZATION!!! " << std::endl;
  286. // without optimization
  287. if ( optimizeNoise )
  288. fthrow ( Exception, "Deactivate optimize_noise!" );
  289. if ( verbose )
  290. std::cerr << "Optimization is deactivated!" << std::endl;
  291. double value (1.0);
  292. if ( this->parameterLowerBound == this->parameterUpperBound)
  293. value = this->parameterLowerBound;
  294. pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
  295. pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
  296. // we use the standard value
  297. OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
  298. gplike.setParameterLowerBound ( value );
  299. gplike.setParameterUpperBound ( value );
  300. //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
  301. gplike.computeAlphaDirect( hyperp, eigenMax );
  302. }
  303. if ( verbose )
  304. std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
  305. std::map<int, Vector> bestAlphas = gplike.getBestAlphas();
  306. std::cerr << "length of alpha vectors: " << bestAlphas.size() << std::endl;
  307. std::cerr << "alpha vector: " << bestAlphas.begin()->second << std::endl;
  308. }
  309. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  310. {
  311. // transform all features with the "optimal" parameter
  312. ikmsum->setParameters ( gplike.getBestParameters() );
  313. }
  314. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
  315. {
  316. precomputedA.clear();
  317. precomputedB.clear();
  318. for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
  319. {
  320. PrecomputedType A;
  321. PrecomputedType B;
  322. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  323. A.setIoUntilEndOfFile ( false );
  324. B.setIoUntilEndOfFile ( false );
  325. precomputedA[ i->first ] = A;
  326. precomputedB[ i->first ] = B;
  327. if ( q != NULL )
  328. {
  329. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
  330. //just to be sure that we do not waste space here
  331. if ( precomputedT[ i->first ] != NULL )
  332. delete precomputedT[ i->first ];
  333. precomputedT[ i->first ] = T;
  334. }
  335. //TODO update the variance-related matrices as well here - currently it is done before in the outer method!!!
  336. }
  337. }
  338. #ifdef NICE_USELIB_MATIO
  339. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
  340. {
  341. map<int, int> examples;
  342. Vector y ( yl.size() );
  343. int ind = 0;
  344. for ( uint i = 0 ; i < yl.size(); i++ )
  345. {
  346. if ( positives.find ( i ) != positives.end() ) {
  347. y[ examples.size() ] = 1.0;
  348. examples.insert ( pair<int, int> ( i, ind ) );
  349. ind++;
  350. } else if ( negatives.find ( i ) != negatives.end() ) {
  351. y[ examples.size() ] = -1.0;
  352. examples.insert ( pair<int, int> ( i, ind ) );
  353. ind++;
  354. }
  355. }
  356. y.resize ( examples.size() );
  357. std::cerr << "Examples: " << examples.size() << std::endl;
  358. optimize ( data, y, examples, noise );
  359. }
  360. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
  361. {
  362. Timer t;
  363. t.start();
  364. std::cerr << "Initializing data structure ..." << std::endl;
  365. if ( fmk != NULL ) delete fmk;
  366. fmk = new FastMinKernel ( data, noise, examples );
  367. t.stop();
  368. if (verboseTime)
  369. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  370. optimize ( y );
  371. }
  372. #endif
  373. int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
  374. {
  375. myClasses.clear();
  376. // determine which classes we have in our label vector
  377. // -> MATLAB: myClasses = unique(y);
  378. for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
  379. {
  380. if ( myClasses.find ( *it ) == myClasses.end() )
  381. {
  382. myClasses.insert ( *it );
  383. }
  384. }
  385. //count how many different classes appear in our data
  386. int nrOfClasses = myClasses.size();
  387. binaryLabels.clear();
  388. //compute the corresponding binary label vectors
  389. if ( nrOfClasses > 2 )
  390. {
  391. //resize every labelVector and set all entries to -1.0
  392. for ( set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
  393. {
  394. binaryLabels[ *k ].resize ( y.size() );
  395. binaryLabels[ *k ].set ( -1.0 );
  396. }
  397. // now look on every example and set the entry of its corresponding label vector to 1.0
  398. // proper existance should not be a problem
  399. for ( int i = 0 ; i < ( int ) y.size(); i++ )
  400. binaryLabels[ y[i] ][i] = 1.0;
  401. }
  402. else if ( nrOfClasses == 2 )
  403. {
  404. //binary setting -- prepare two binary label vectors with opposite signs
  405. NICE::Vector yb ( y );
  406. binaryLabelNegative = *(myClasses.begin());
  407. std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
  408. binaryLabelPositive = *classIt;
  409. if ( verbose )
  410. std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
  411. for ( uint i = 0 ; i < yb.size() ; i++ )
  412. yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
  413. binaryLabels[ binaryLabelPositive ] = yb;
  414. //NOTE
  415. //uncomment the following, if you want to perform real binary computations with 2 classes
  416. // //we only need one vector, which already contains +1 and -1, so we need only one computation too
  417. // binaryLabels[ negativeClass ] = yb;
  418. // binaryLabels[ negativeClass ] *= -1.0;
  419. // std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  420. // binaryLabels[ 0 ] = yb;
  421. // binaryLabels[ 0 ] *= -1.0;
  422. //comment the following, if you want to do a real binary computation. It should be senseless, but let's see...
  423. //we do NOT do real binary computation, but an implicite one with only a single object
  424. nrOfClasses--;
  425. std::set<int>::iterator it = myClasses.begin(); it++;
  426. // myClasses.erase(it);
  427. }
  428. else //OCC setting
  429. {
  430. //we set the labels to 1, independent of the previously given class number
  431. //however, the original class numbers are stored and returned in classification
  432. Vector yNew ( y.size(), 1 );
  433. myClasses.clear();
  434. myClasses.insert ( 1 );
  435. //we have to indicate, that we are in an OCC setting
  436. nrOfClasses--;
  437. }
  438. return nrOfClasses;
  439. }
  440. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
  441. {
  442. if ( fmk == NULL )
  443. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  444. this->labels = y;
  445. std::map<int, NICE::Vector> binaryLabels;
  446. prepareBinaryLabels ( binaryLabels, y , knownClasses );
  447. //now call the main function :)
  448. this->optimize(binaryLabels);
  449. }
  450. void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
  451. {
  452. Timer t;
  453. t.start();
  454. //how many different classes do we have right now?
  455. int nrOfClasses = binaryLabels.size();
  456. if (verbose)
  457. {
  458. std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
  459. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  460. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
  461. }
  462. // combine standard model and noise model
  463. Timer t1;
  464. t1.start();
  465. //setup the kernel combination
  466. ikmsum = new IKMLinearCombination ();
  467. if ( verbose )
  468. {
  469. std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  470. }
  471. //First model: noise
  472. ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
  473. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  474. fmk->setNoise ( 0.0 );
  475. //NOTE The GMHIKernel is always the last model which is added (this is necessary for easy store and restore functionality)
  476. ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
  477. t1.stop();
  478. if (verboseTime)
  479. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  480. GPLikelihoodApprox * gplike;
  481. uint parameterVectorSize;
  482. t1.start();
  483. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  484. t1.stop();
  485. if (verboseTime)
  486. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  487. if (verbose)
  488. {
  489. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  490. }
  491. t1.start();
  492. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsider );
  493. t1.stop();
  494. if (verboseTime)
  495. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  496. if ( verbose )
  497. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  498. t1.start();
  499. this->performOptimization ( *gplike, parameterVectorSize );
  500. t1.stop();
  501. if (verboseTime)
  502. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  503. if ( verbose )
  504. std::cerr << "Preparing classification ..." << std::endl;
  505. t1.start();
  506. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  507. t1.stop();
  508. if (verboseTime)
  509. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  510. t1.start();
  511. this->computeMatricesAndLUTs ( *gplike );
  512. t1.stop();
  513. if (verboseTime)
  514. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  515. t.stop();
  516. ResourceStatistics rs;
  517. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  518. long maxMemory;
  519. rs.getMaximumMemory ( maxMemory );
  520. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  521. //don't waste memory
  522. delete gplike;
  523. }
  524. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  525. {
  526. PrecomputedType AVar;
  527. fmk->hikPrepareKVNApproximation ( AVar );
  528. precomputedAForVarEst = AVar;
  529. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  530. if ( q != NULL )
  531. {
  532. double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
  533. precomputedTForVarEst = T;
  534. }
  535. }
  536. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  537. {
  538. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  539. }
  540. int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
  541. {
  542. // loop through all classes
  543. if ( precomputedA.size() == 0 )
  544. {
  545. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  546. }
  547. uint maxClassNo = 0;
  548. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  549. {
  550. uint classno = i->first;
  551. maxClassNo = std::max ( maxClassNo, classno );
  552. double beta;
  553. if ( q != NULL ) {
  554. map<int, double *>::const_iterator j = precomputedT.find ( classno );
  555. double *T = j->second;
  556. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  557. } else {
  558. const PrecomputedType & A = i->second;
  559. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  560. const PrecomputedType & B = j->second;
  561. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  562. // Giving the transformation pf as an additional
  563. // argument is necessary due to the following reason:
  564. // FeatureMatrixT is sorted according to the original values, therefore,
  565. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  566. // values as inputs. However, for calculation we need the transformed features values.
  567. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  568. }
  569. scores[ classno ] = beta;
  570. }
  571. scores.setDim ( maxClassNo + 1 );
  572. if ( precomputedA.size() > 1 )
  573. { // multi-class classification
  574. return scores.maxElement();
  575. }
  576. else
  577. { // binary setting
  578. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  579. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  580. }
  581. }
  582. int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
  583. {
  584. // loop through all classes
  585. if ( precomputedA.size() == 0 )
  586. {
  587. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  588. }
  589. uint maxClassNo = 0;
  590. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  591. {
  592. uint classno = i->first;
  593. maxClassNo = std::max ( maxClassNo, classno );
  594. double beta;
  595. if ( q != NULL ) {
  596. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  597. double *T = j->second;
  598. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  599. } else {
  600. const PrecomputedType & A = i->second;
  601. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  602. const PrecomputedType & B = j->second;
  603. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  604. // Giving the transformation pf as an additional
  605. // argument is necessary due to the following reason:
  606. // FeatureMatrixT is sorted according to the original values, therefore,
  607. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  608. // values as inputs. However, for calculation we need the transformed features values.
  609. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  610. }
  611. scores[ classno ] = beta;
  612. }
  613. scores.setDim ( maxClassNo + 1 );
  614. if ( precomputedA.size() > 1 )
  615. { // multi-class classification
  616. return scores.maxElement();
  617. }
  618. else
  619. { // binary setting
  620. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  621. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  622. }
  623. }
  624. //////////////////////////////////////////
  625. // variance computation: sparse inputs
  626. //////////////////////////////////////////
  627. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
  628. {
  629. // security check!
  630. if ( pf == NULL )
  631. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  632. // ---------------- compute the first term --------------------
  633. double kSelf ( 0.0 );
  634. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  635. {
  636. kSelf += pf->f ( 0, it->second );
  637. // if weighted dimensions:
  638. //kSelf += pf->f(it->first,it->second);
  639. }
  640. // ---------------- compute the approximation of the second term --------------------
  641. double normKStar;
  642. if ( q != NULL )
  643. {
  644. if ( precomputedTForVarEst == NULL )
  645. {
  646. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  647. }
  648. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  649. }
  650. else
  651. {
  652. if ( precomputedAForVarEst.size () == 0 )
  653. {
  654. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  655. }
  656. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  657. }
  658. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  659. }
  660. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
  661. {
  662. // security check!
  663. if ( eigenMaxVectors.rows() == 0 )
  664. {
  665. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  666. }
  667. // ---------------- compute the first term --------------------
  668. // Timer t;
  669. // t.start();
  670. double kSelf ( 0.0 );
  671. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  672. {
  673. kSelf += pf->f ( 0, it->second );
  674. // if weighted dimensions:
  675. //kSelf += pf->f(it->first,it->second);
  676. }
  677. // ---------------- compute the approximation of the second term --------------------
  678. // t.stop();
  679. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  680. // t.start();
  681. NICE::Vector kStar;
  682. fmk->hikComputeKernelVector ( x, kStar );
  683. /* t.stop();
  684. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  685. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  686. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  687. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  688. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  689. //wherefor it takes aeons...
  690. //so we compute it by ourselves
  691. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  692. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  693. // double kStarI ( kStar[tmpI] );
  694. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  695. {
  696. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  697. {
  698. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  699. }
  700. }
  701. double projectionLength ( 0.0 );
  702. double currentSecondTerm ( 0.0 );
  703. double sumOfProjectionLengths ( 0.0 );
  704. int cnt ( 0 );
  705. NICE::Vector::const_iterator it = multiplicationResults.begin();
  706. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  707. {
  708. projectionLength = ( *it );
  709. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  710. sumOfProjectionLengths += pow ( projectionLength, 2 );
  711. it++;
  712. cnt++;
  713. }
  714. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  715. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  716. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  717. {
  718. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  719. }
  720. predVariance = kSelf - currentSecondTerm;
  721. }
  722. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  723. {
  724. // security check!
  725. if ( ikmsum->getNumberOfModels() == 0 )
  726. {
  727. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  728. }
  729. Timer t;
  730. // t.start();
  731. // ---------------- compute the first term --------------------
  732. double kSelf ( 0.0 );
  733. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  734. {
  735. kSelf += pf->f ( 0, it->second );
  736. // if weighted dimensions:
  737. //kSelf += pf->f(it->first,it->second);
  738. }
  739. // ---------------- compute the second term --------------------
  740. // t.stop();
  741. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  742. // t.start();
  743. NICE::Vector kStar;
  744. fmk->hikComputeKernelVector ( x, kStar );
  745. // t.stop();
  746. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  747. //
  748. //now run the ILS method
  749. NICE::Vector diagonalElements;
  750. ikmsum->getDiagonalElements ( diagonalElements );
  751. // t.start();
  752. // init simple jacobi pre-conditioning
  753. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  754. //perform pre-conditioning
  755. if ( linsolver_cg != NULL )
  756. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  757. NICE::Vector beta;
  758. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  759. * K~ = K + sigma^2 I
  760. *
  761. * K~ \approx lambda_max v v^T
  762. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  763. * => \lambda_max v^T alpha = v^T k_*
  764. * => alpha = k_* / lambda_max could be a good initial start
  765. * If we put everything in the first equation this gives us
  766. * v = k_*
  767. * This reduces the number of iterations by 5 or 8
  768. */
  769. beta = (kStar * (1.0 / eigenMax[0]) );
  770. /* t.stop();
  771. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  772. t.start();*/
  773. // t.start();
  774. linsolver->solveLin ( *ikmsum, kStar, beta );
  775. // t.stop();
  776. // t.stop();
  777. // t.stop();
  778. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  779. beta *= kStar;
  780. double currentSecondTerm( beta.Sum() );
  781. predVariance = kSelf - currentSecondTerm;
  782. }
  783. //////////////////////////////////////////
  784. // variance computation: non-sparse inputs
  785. //////////////////////////////////////////
  786. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  787. {
  788. // security check!
  789. if ( pf == NULL )
  790. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  791. // ---------------- compute the first term --------------------
  792. double kSelf ( 0.0 );
  793. int dim ( 0 );
  794. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  795. {
  796. kSelf += pf->f ( 0, *it );
  797. // if weighted dimensions:
  798. //kSelf += pf->f(dim,*it);
  799. }
  800. // ---------------- compute the approximation of the second term --------------------
  801. double normKStar;
  802. if ( q != NULL )
  803. {
  804. if ( precomputedTForVarEst == NULL )
  805. {
  806. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  807. }
  808. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  809. }
  810. else
  811. {
  812. if ( precomputedAForVarEst.size () == 0 )
  813. {
  814. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  815. }
  816. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  817. }
  818. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  819. }
  820. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
  821. {
  822. // security check!
  823. if ( eigenMaxVectors.rows() == 0 )
  824. {
  825. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  826. }
  827. // ---------------- compute the first term --------------------
  828. // Timer t;
  829. // t.start();
  830. double kSelf ( 0.0 );
  831. int dim ( 0 );
  832. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  833. {
  834. kSelf += pf->f ( 0, *it );
  835. // if weighted dimensions:
  836. //kSelf += pf->f(dim,*it);
  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::Vector & x, double & predVariance ) const
  884. {
  885. if ( ikmsum->getNumberOfModels() == 0 )
  886. {
  887. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  888. }
  889. Timer t;
  890. // t.start();
  891. // ---------------- compute the first term --------------------
  892. double kSelf ( 0.0 );
  893. int dim ( 0 );
  894. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  895. {
  896. kSelf += pf->f ( 0, *it );
  897. // if weighted dimensions:
  898. //kSelf += pf->f(dim,*it);
  899. }
  900. // ---------------- compute the second term --------------------
  901. // t.stop();
  902. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  903. // t.start();
  904. NICE::Vector kStar;
  905. fmk->hikComputeKernelVector ( x, kStar );
  906. // t.stop();
  907. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  908. //
  909. //now run the ILS method
  910. NICE::Vector diagonalElements;
  911. ikmsum->getDiagonalElements ( diagonalElements );
  912. // t.start();
  913. // init simple jacobi pre-conditioning
  914. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  915. //perform pre-conditioning
  916. if ( linsolver_cg != NULL )
  917. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  918. NICE::Vector beta;
  919. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  920. * K~ = K + sigma^2 I
  921. *
  922. * K~ \approx lambda_max v v^T
  923. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  924. * => \lambda_max v^T alpha = v^T k_*
  925. * => alpha = k_* / lambda_max could be a good initial start
  926. * If we put everything in the first equation this gives us
  927. * v = k_*
  928. * This reduces the number of iterations by 5 or 8
  929. */
  930. beta = (kStar * (1.0 / eigenMax[0]) );
  931. /* t.stop();
  932. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  933. t.start();*/
  934. // t.start();
  935. linsolver->solveLin ( *ikmsum, kStar, beta );
  936. // t.stop();
  937. // t.stop();
  938. // t.stop();
  939. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  940. beta *= kStar;
  941. double currentSecondTerm( beta.Sum() );
  942. predVariance = kSelf - currentSecondTerm;
  943. }
  944. // ---------------------- STORE AND RESTORE FUNCTIONS ----------------------
  945. void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
  946. {
  947. bool b_restoreVerbose ( false );
  948. if ( is.good() )
  949. {
  950. if ( b_restoreVerbose )
  951. std::cerr << " in FMKGP restore" << std::endl;
  952. std::string tmp;
  953. is >> tmp; //class name
  954. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  955. {
  956. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  957. throw;
  958. }
  959. if (fmk != NULL)
  960. {
  961. delete fmk;
  962. fmk = NULL;
  963. }
  964. if ( ikmsum != NULL )
  965. {
  966. delete ikmsum;
  967. }
  968. ikmsum = new IKMLinearCombination ();
  969. if ( b_restoreVerbose )
  970. std::cerr << "ikmsum object created" << std::endl;
  971. is.precision ( numeric_limits<double>::digits10 + 1 );
  972. bool b_endOfBlock ( false ) ;
  973. while ( !b_endOfBlock )
  974. {
  975. is >> tmp; // start of block
  976. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  977. {
  978. b_endOfBlock = true;
  979. continue;
  980. }
  981. tmp = this->removeStartTag ( tmp );
  982. if ( b_restoreVerbose )
  983. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  984. if ( tmp.compare("fmk") == 0 )
  985. {
  986. fmk = new FastMinKernel;
  987. fmk->restore( is, format );
  988. is >> tmp; // end of block
  989. tmp = this->removeEndTag ( tmp );
  990. }
  991. else if ( tmp.compare("precomputedA") == 0 )
  992. {
  993. is >> tmp; // size
  994. int preCompSize ( 0 );
  995. is >> preCompSize;
  996. precomputedA.clear();
  997. if ( b_restoreVerbose )
  998. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  999. for ( int i = 0; i < preCompSize; i++ )
  1000. {
  1001. int nr;
  1002. is >> nr;
  1003. PrecomputedType pct;
  1004. pct.setIoUntilEndOfFile ( false );
  1005. pct.restore ( is, format );
  1006. precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1007. }
  1008. is >> tmp; // end of block
  1009. tmp = this->removeEndTag ( tmp );
  1010. }
  1011. else if ( tmp.compare("precomputedB") == 0 )
  1012. {
  1013. is >> tmp; // size
  1014. int preCompSize ( 0 );
  1015. is >> preCompSize;
  1016. precomputedB.clear();
  1017. if ( b_restoreVerbose )
  1018. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1019. for ( int i = 0; i < preCompSize; i++ )
  1020. {
  1021. int nr;
  1022. is >> nr;
  1023. PrecomputedType pct;
  1024. pct.setIoUntilEndOfFile ( false );
  1025. pct.restore ( is, format );
  1026. precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1027. }
  1028. is >> tmp; // end of block
  1029. tmp = this->removeEndTag ( tmp );
  1030. }
  1031. else if ( tmp.compare("precomputedT") == 0 )
  1032. {
  1033. is >> tmp; // size
  1034. int precomputedTSize ( 0 );
  1035. is >> precomputedTSize;
  1036. precomputedT.clear();
  1037. if ( b_restoreVerbose )
  1038. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1039. if ( precomputedTSize > 0 )
  1040. {
  1041. if ( b_restoreVerbose )
  1042. std::cerr << " restore precomputedT" << std::endl;
  1043. is >> tmp;
  1044. int sizeOfLUT;
  1045. is >> sizeOfLUT;
  1046. for (int i = 0; i < precomputedTSize; i++)
  1047. {
  1048. is >> tmp;
  1049. int index;
  1050. is >> index;
  1051. double * array = new double [ sizeOfLUT];
  1052. for ( int i = 0; i < sizeOfLUT; i++ )
  1053. {
  1054. is >> array[i];
  1055. }
  1056. precomputedT.insert ( std::pair<int, double*> ( index, array ) );
  1057. }
  1058. }
  1059. else
  1060. {
  1061. if ( b_restoreVerbose )
  1062. std::cerr << " skip restoring precomputedT" << std::endl;
  1063. }
  1064. is >> tmp; // end of block
  1065. tmp = this->removeEndTag ( tmp );
  1066. }
  1067. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1068. {
  1069. int sizeOfAForVarEst;
  1070. is >> sizeOfAForVarEst;
  1071. if ( b_restoreVerbose )
  1072. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1073. if (sizeOfAForVarEst > 0)
  1074. {
  1075. precomputedAForVarEst.clear();
  1076. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1077. precomputedAForVarEst.restore ( is, format );
  1078. }
  1079. is >> tmp; // end of block
  1080. tmp = this->removeEndTag ( tmp );
  1081. }
  1082. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1083. {
  1084. std::string isNull;
  1085. is >> isNull; // NOTNULL or NULL
  1086. if ( b_restoreVerbose )
  1087. std::cerr << "content of isNull: " << isNull << std::endl;
  1088. if (isNull.compare("NOTNULL") == 0)
  1089. {
  1090. if ( b_restoreVerbose )
  1091. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1092. int sizeOfLUT;
  1093. is >> sizeOfLUT;
  1094. precomputedTForVarEst = new double [ sizeOfLUT ];
  1095. for ( int i = 0; i < sizeOfLUT; i++ )
  1096. {
  1097. is >> precomputedTForVarEst[i];
  1098. }
  1099. }
  1100. else
  1101. {
  1102. if ( b_restoreVerbose )
  1103. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1104. if (precomputedTForVarEst != NULL)
  1105. delete precomputedTForVarEst;
  1106. }
  1107. is >> tmp; // end of block
  1108. tmp = this->removeEndTag ( tmp );
  1109. }
  1110. else if ( tmp.compare("eigenMax") == 0 )
  1111. {
  1112. is >> eigenMax;
  1113. is >> tmp; // end of block
  1114. tmp = this->removeEndTag ( tmp );
  1115. }
  1116. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1117. {
  1118. is >> eigenMaxVectors;
  1119. is >> tmp; // end of block
  1120. tmp = this->removeEndTag ( tmp );
  1121. }
  1122. else if ( tmp.compare("ikmsum") == 0 )
  1123. {
  1124. bool b_endOfBlock ( false ) ;
  1125. while ( !b_endOfBlock )
  1126. {
  1127. is >> tmp; // start of block
  1128. if ( this->isEndTag( tmp, "ikmsum" ) )
  1129. {
  1130. b_endOfBlock = true;
  1131. continue;
  1132. }
  1133. tmp = this->removeStartTag ( tmp );
  1134. if ( tmp.compare("IKMNoise") == 0 )
  1135. {
  1136. IKMNoise * ikmnoise = new IKMNoise ();
  1137. ikmnoise->restore ( is, format );
  1138. if ( b_restoreVerbose )
  1139. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1140. ikmsum->addModel ( ikmnoise );
  1141. }
  1142. else
  1143. {
  1144. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1145. throw;
  1146. }
  1147. }
  1148. }
  1149. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1150. {
  1151. is >> binaryLabelPositive;
  1152. is >> tmp; // end of block
  1153. tmp = this->removeEndTag ( tmp );
  1154. }
  1155. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1156. {
  1157. is >> binaryLabelNegative;
  1158. is >> tmp; // end of block
  1159. tmp = this->removeEndTag ( tmp );
  1160. }
  1161. else if ( tmp.compare("labels") == 0 )
  1162. {
  1163. is >> labels;
  1164. is >> tmp; // end of block
  1165. tmp = this->removeEndTag ( tmp );
  1166. }
  1167. else
  1168. {
  1169. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1170. throw;
  1171. }
  1172. }
  1173. //NOTE are there any more models you added? then add them here respectively in the correct order
  1174. //.....
  1175. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1176. if ( b_restoreVerbose )
  1177. std::cerr << " add GMHIKernel" << std::endl;
  1178. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1179. if ( b_restoreVerbose )
  1180. std::cerr << " restore positive and negative label" << std::endl;
  1181. knownClasses.clear();
  1182. if ( b_restoreVerbose )
  1183. std::cerr << " fill known classes object " << std::endl;
  1184. if ( precomputedA.size() == 1)
  1185. {
  1186. knownClasses.insert( binaryLabelPositive );
  1187. knownClasses.insert( binaryLabelNegative );
  1188. if ( b_restoreVerbose )
  1189. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1190. }
  1191. else
  1192. {
  1193. for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
  1194. knownClasses.insert ( itA->first );
  1195. if ( b_restoreVerbose )
  1196. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1197. }
  1198. }
  1199. else
  1200. {
  1201. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1202. throw;
  1203. }
  1204. }
  1205. void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
  1206. {
  1207. if ( os.good() )
  1208. {
  1209. // show starting point
  1210. os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1211. os << this->createStartTag( "fmk" ) << std::endl;
  1212. fmk->store ( os, format );
  1213. os << this->createEndTag( "fmk" ) << std::endl;
  1214. os.precision ( numeric_limits<double>::digits10 + 1 );
  1215. //we only have to store the things we computed, since the remaining settings come with the config file afterwards
  1216. os << this->createStartTag( "precomputedA" ) << std::endl;
  1217. os << "size: " << precomputedA.size() << std::endl;
  1218. std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
  1219. for ( uint i = 0; i < precomputedA.size(); i++ )
  1220. {
  1221. os << preCompIt->first << std::endl;
  1222. ( preCompIt->second ).store ( os, format );
  1223. preCompIt++;
  1224. }
  1225. os << this->createEndTag( "precomputedA" ) << std::endl;
  1226. os << this->createStartTag( "precomputedB" ) << std::endl;
  1227. os << "size: " << precomputedB.size() << std::endl;
  1228. preCompIt = precomputedB.begin();
  1229. for ( uint i = 0; i < precomputedB.size(); i++ )
  1230. {
  1231. os << preCompIt->first << std::endl;
  1232. ( preCompIt->second ).store ( os, format );
  1233. preCompIt++;
  1234. }
  1235. os << this->createEndTag( "precomputedB" ) << std::endl;
  1236. os << this->createStartTag( "precomputedT" ) << std::endl;
  1237. os << "size: " << precomputedT.size() << std::endl;
  1238. if ( precomputedT.size() > 0 )
  1239. {
  1240. int sizeOfLUT ( 0 );
  1241. if ( q != NULL )
  1242. sizeOfLUT = q->size() * this->fmk->get_d();
  1243. os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1244. for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
  1245. {
  1246. os << "index: " << it->first << std::endl;
  1247. for ( int i = 0; i < sizeOfLUT; i++ )
  1248. {
  1249. os << ( it->second ) [i] << " ";
  1250. }
  1251. os << std::endl;
  1252. }
  1253. }
  1254. os << this->createEndTag( "precomputedT" ) << std::endl;
  1255. //now store the things needed for the variance estimation
  1256. os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  1257. os << precomputedAForVarEst.size() << std::endl;
  1258. if (precomputedAForVarEst.size() > 0)
  1259. {
  1260. precomputedAForVarEst.store ( os, format );
  1261. os << std::endl;
  1262. }
  1263. os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  1264. os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  1265. if ( precomputedTForVarEst != NULL )
  1266. {
  1267. os << "NOTNULL" << std::endl;
  1268. int sizeOfLUT ( 0 );
  1269. if ( q != NULL )
  1270. sizeOfLUT = q->size() * this->fmk->get_d();
  1271. os << sizeOfLUT << std::endl;
  1272. for ( int i = 0; i < sizeOfLUT; i++ )
  1273. {
  1274. os << precomputedTForVarEst[i] << " ";
  1275. }
  1276. os << std::endl;
  1277. }
  1278. else
  1279. {
  1280. os << "NULL" << std::endl;
  1281. }
  1282. os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  1283. //store the eigenvalues and eigenvectors
  1284. os << this->createStartTag( "eigenMax" ) << std::endl;
  1285. os << eigenMax << std::endl;
  1286. os << this->createEndTag( "eigenMax" ) << std::endl;
  1287. os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  1288. os << eigenMaxVectors << std::endl;
  1289. os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  1290. os << this->createStartTag( "ikmsum" ) << std::endl;
  1291. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1292. {
  1293. ( ikmsum->getModel ( j ) )->store ( os, format );
  1294. }
  1295. os << this->createEndTag( "ikmsum" ) << std::endl;
  1296. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1297. os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1298. os << binaryLabelPositive << std::endl;
  1299. os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1300. os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1301. os << binaryLabelNegative << std::endl;
  1302. os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1303. os << this->createStartTag( "labels" ) << std::endl;
  1304. os << labels << std::endl;
  1305. os << this->createEndTag( "labels" ) << std::endl;
  1306. // done
  1307. os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1308. }
  1309. else
  1310. {
  1311. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1312. }
  1313. }
  1314. void FMKGPHyperparameterOptimization::clear ( ) {};