FMKGPHyperparameterOptimization.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  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. {
  305. std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
  306. std::map<int, NICE::Vector> bestAlphas = gplike.getBestAlphas();
  307. std::cerr << "length of alpha vectors: " << bestAlphas.size() << std::endl;
  308. std::cerr << "alpha vector for first class: " << bestAlphas.begin()->second << std::endl;
  309. }
  310. }
  311. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  312. {
  313. // transform all features with the "optimal" parameter
  314. ikmsum->setParameters ( gplike.getBestParameters() );
  315. }
  316. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
  317. {
  318. precomputedA.clear();
  319. precomputedB.clear();
  320. for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
  321. {
  322. PrecomputedType A;
  323. PrecomputedType B;
  324. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  325. A.setIoUntilEndOfFile ( false );
  326. B.setIoUntilEndOfFile ( false );
  327. precomputedA[ i->first ] = A;
  328. precomputedB[ i->first ] = B;
  329. if ( q != NULL )
  330. {
  331. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
  332. //just to be sure that we do not waste space here
  333. if ( precomputedT[ i->first ] != NULL )
  334. delete precomputedT[ i->first ];
  335. precomputedT[ i->first ] = T;
  336. }
  337. //TODO update the variance-related matrices as well here - currently it is done before in the outer method!!!
  338. }
  339. }
  340. #ifdef NICE_USELIB_MATIO
  341. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
  342. {
  343. map<int, int> examples;
  344. Vector y ( yl.size() );
  345. int ind = 0;
  346. for ( uint i = 0 ; i < yl.size(); i++ )
  347. {
  348. if ( positives.find ( i ) != positives.end() ) {
  349. y[ examples.size() ] = 1.0;
  350. examples.insert ( pair<int, int> ( i, ind ) );
  351. ind++;
  352. } else if ( negatives.find ( i ) != negatives.end() ) {
  353. y[ examples.size() ] = -1.0;
  354. examples.insert ( pair<int, int> ( i, ind ) );
  355. ind++;
  356. }
  357. }
  358. y.resize ( examples.size() );
  359. std::cerr << "Examples: " << examples.size() << std::endl;
  360. optimize ( data, y, examples, noise );
  361. }
  362. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
  363. {
  364. Timer t;
  365. t.start();
  366. std::cerr << "Initializing data structure ..." << std::endl;
  367. if ( fmk != NULL ) delete fmk;
  368. fmk = new FastMinKernel ( data, noise, examples );
  369. t.stop();
  370. if (verboseTime)
  371. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  372. optimize ( y );
  373. }
  374. #endif
  375. int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
  376. {
  377. myClasses.clear();
  378. // determine which classes we have in our label vector
  379. // -> MATLAB: myClasses = unique(y);
  380. for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
  381. {
  382. if ( myClasses.find ( *it ) == myClasses.end() )
  383. {
  384. myClasses.insert ( *it );
  385. }
  386. }
  387. //count how many different classes appear in our data
  388. int nrOfClasses = myClasses.size();
  389. binaryLabels.clear();
  390. //compute the corresponding binary label vectors
  391. if ( nrOfClasses > 2 )
  392. {
  393. //resize every labelVector and set all entries to -1.0
  394. for ( set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
  395. {
  396. binaryLabels[ *k ].resize ( y.size() );
  397. binaryLabels[ *k ].set ( -1.0 );
  398. }
  399. // now look on every example and set the entry of its corresponding label vector to 1.0
  400. // proper existance should not be a problem
  401. for ( int i = 0 ; i < ( int ) y.size(); i++ )
  402. binaryLabels[ y[i] ][i] = 1.0;
  403. }
  404. else if ( nrOfClasses == 2 )
  405. {
  406. //binary setting -- prepare two binary label vectors with opposite signs
  407. NICE::Vector yb ( y );
  408. binaryLabelNegative = *(myClasses.begin());
  409. std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
  410. binaryLabelPositive = *classIt;
  411. if ( verbose )
  412. std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
  413. for ( uint i = 0 ; i < yb.size() ; i++ )
  414. yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
  415. binaryLabels[ binaryLabelPositive ] = yb;
  416. //NOTE
  417. //uncomment the following, if you want to perform real binary computations with 2 classes
  418. // //we only need one vector, which already contains +1 and -1, so we need only one computation too
  419. // binaryLabels[ negativeClass ] = yb;
  420. // binaryLabels[ negativeClass ] *= -1.0;
  421. // std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  422. // binaryLabels[ 0 ] = yb;
  423. // binaryLabels[ 0 ] *= -1.0;
  424. //comment the following, if you want to do a real binary computation. It should be senseless, but let's see...
  425. //we do NOT do real binary computation, but an implicite one with only a single object
  426. nrOfClasses--;
  427. std::set<int>::iterator it = myClasses.begin(); it++;
  428. // myClasses.erase(it);
  429. }
  430. else //OCC setting
  431. {
  432. //we set the labels to 1, independent of the previously given class number
  433. //however, the original class numbers are stored and returned in classification
  434. Vector yNew ( y.size(), 1 );
  435. myClasses.clear();
  436. myClasses.insert ( 1 );
  437. //we have to indicate, that we are in an OCC setting
  438. nrOfClasses--;
  439. }
  440. return nrOfClasses;
  441. }
  442. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
  443. {
  444. if ( fmk == NULL )
  445. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  446. this->labels = y;
  447. std::map<int, NICE::Vector> binaryLabels;
  448. prepareBinaryLabels ( binaryLabels, y , knownClasses );
  449. //now call the main function :)
  450. this->optimize(binaryLabels);
  451. }
  452. void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
  453. {
  454. Timer t;
  455. t.start();
  456. //how many different classes do we have right now?
  457. int nrOfClasses = binaryLabels.size();
  458. if (verbose)
  459. {
  460. std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
  461. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  462. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
  463. }
  464. // combine standard model and noise model
  465. Timer t1;
  466. t1.start();
  467. //setup the kernel combination
  468. ikmsum = new IKMLinearCombination ();
  469. if ( verbose )
  470. {
  471. std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  472. }
  473. //First model: noise
  474. ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
  475. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  476. fmk->setNoise ( 0.0 );
  477. //NOTE The GMHIKernel is always the last model which is added (this is necessary for easy store and restore functionality)
  478. ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
  479. t1.stop();
  480. if (verboseTime)
  481. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  482. GPLikelihoodApprox * gplike;
  483. uint parameterVectorSize;
  484. t1.start();
  485. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  486. t1.stop();
  487. if (verboseTime)
  488. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  489. if (verbose)
  490. {
  491. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  492. }
  493. t1.start();
  494. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsider );
  495. t1.stop();
  496. if (verboseTime)
  497. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  498. if ( verbose )
  499. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  500. t1.start();
  501. this->performOptimization ( *gplike, parameterVectorSize );
  502. t1.stop();
  503. if (verboseTime)
  504. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  505. if ( verbose )
  506. std::cerr << "Preparing classification ..." << std::endl;
  507. t1.start();
  508. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  509. t1.stop();
  510. if (verboseTime)
  511. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  512. t1.start();
  513. this->computeMatricesAndLUTs ( *gplike );
  514. t1.stop();
  515. if (verboseTime)
  516. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  517. t.stop();
  518. ResourceStatistics rs;
  519. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  520. long maxMemory;
  521. rs.getMaximumMemory ( maxMemory );
  522. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  523. //don't waste memory
  524. delete gplike;
  525. }
  526. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  527. {
  528. PrecomputedType AVar;
  529. fmk->hikPrepareKVNApproximation ( AVar );
  530. precomputedAForVarEst = AVar;
  531. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  532. if ( q != NULL )
  533. {
  534. double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
  535. precomputedTForVarEst = T;
  536. }
  537. }
  538. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  539. {
  540. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  541. }
  542. int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
  543. {
  544. // loop through all classes
  545. if ( precomputedA.size() == 0 )
  546. {
  547. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  548. }
  549. uint maxClassNo = 0;
  550. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  551. {
  552. uint classno = i->first;
  553. maxClassNo = std::max ( maxClassNo, classno );
  554. double beta;
  555. if ( q != NULL ) {
  556. map<int, double *>::const_iterator j = precomputedT.find ( classno );
  557. double *T = j->second;
  558. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  559. } else {
  560. const PrecomputedType & A = i->second;
  561. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  562. const PrecomputedType & B = j->second;
  563. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  564. // Giving the transformation pf as an additional
  565. // argument is necessary due to the following reason:
  566. // FeatureMatrixT is sorted according to the original values, therefore,
  567. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  568. // values as inputs. However, for calculation we need the transformed features values.
  569. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  570. }
  571. scores[ classno ] = beta;
  572. }
  573. scores.setDim ( maxClassNo + 1 );
  574. if ( precomputedA.size() > 1 )
  575. { // multi-class classification
  576. return scores.maxElement();
  577. }
  578. else
  579. { // binary setting
  580. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  581. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  582. }
  583. }
  584. int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
  585. {
  586. // loop through all classes
  587. if ( precomputedA.size() == 0 )
  588. {
  589. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  590. }
  591. uint maxClassNo = 0;
  592. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  593. {
  594. uint classno = i->first;
  595. maxClassNo = std::max ( maxClassNo, classno );
  596. double beta;
  597. if ( q != NULL ) {
  598. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  599. double *T = j->second;
  600. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  601. } else {
  602. const PrecomputedType & A = i->second;
  603. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  604. const PrecomputedType & B = j->second;
  605. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  606. // Giving the transformation pf as an additional
  607. // argument is necessary due to the following reason:
  608. // FeatureMatrixT is sorted according to the original values, therefore,
  609. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  610. // values as inputs. However, for calculation we need the transformed features values.
  611. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  612. }
  613. scores[ classno ] = beta;
  614. }
  615. scores.setDim ( maxClassNo + 1 );
  616. if ( precomputedA.size() > 1 )
  617. { // multi-class classification
  618. return scores.maxElement();
  619. }
  620. else
  621. { // binary setting
  622. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  623. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  624. }
  625. }
  626. //////////////////////////////////////////
  627. // variance computation: sparse inputs
  628. //////////////////////////////////////////
  629. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
  630. {
  631. // security check!
  632. if ( pf == NULL )
  633. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  634. // ---------------- compute the first term --------------------
  635. double kSelf ( 0.0 );
  636. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  637. {
  638. kSelf += pf->f ( 0, it->second );
  639. // if weighted dimensions:
  640. //kSelf += pf->f(it->first,it->second);
  641. }
  642. // ---------------- compute the approximation of the second term --------------------
  643. double normKStar;
  644. if ( q != NULL )
  645. {
  646. if ( precomputedTForVarEst == NULL )
  647. {
  648. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  649. }
  650. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  651. }
  652. else
  653. {
  654. if ( precomputedAForVarEst.size () == 0 )
  655. {
  656. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  657. }
  658. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  659. }
  660. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  661. }
  662. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
  663. {
  664. // security check!
  665. if ( eigenMaxVectors.rows() == 0 )
  666. {
  667. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  668. }
  669. // ---------------- compute the first term --------------------
  670. // Timer t;
  671. // t.start();
  672. double kSelf ( 0.0 );
  673. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  674. {
  675. kSelf += pf->f ( 0, it->second );
  676. // if weighted dimensions:
  677. //kSelf += pf->f(it->first,it->second);
  678. }
  679. // ---------------- compute the approximation of the second term --------------------
  680. // t.stop();
  681. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  682. // t.start();
  683. NICE::Vector kStar;
  684. fmk->hikComputeKernelVector ( x, kStar );
  685. /* t.stop();
  686. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  687. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  688. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  689. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  690. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  691. //wherefor it takes aeons...
  692. //so we compute it by ourselves
  693. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  694. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  695. // double kStarI ( kStar[tmpI] );
  696. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  697. {
  698. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  699. {
  700. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  701. }
  702. }
  703. double projectionLength ( 0.0 );
  704. double currentSecondTerm ( 0.0 );
  705. double sumOfProjectionLengths ( 0.0 );
  706. int cnt ( 0 );
  707. NICE::Vector::const_iterator it = multiplicationResults.begin();
  708. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  709. {
  710. projectionLength = ( *it );
  711. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  712. sumOfProjectionLengths += pow ( projectionLength, 2 );
  713. it++;
  714. cnt++;
  715. }
  716. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  717. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  718. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  719. {
  720. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  721. }
  722. predVariance = kSelf - currentSecondTerm;
  723. }
  724. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  725. {
  726. // security check!
  727. if ( ikmsum->getNumberOfModels() == 0 )
  728. {
  729. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  730. }
  731. Timer t;
  732. // t.start();
  733. // ---------------- compute the first term --------------------
  734. double kSelf ( 0.0 );
  735. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  736. {
  737. kSelf += pf->f ( 0, it->second );
  738. // if weighted dimensions:
  739. //kSelf += pf->f(it->first,it->second);
  740. }
  741. // ---------------- compute the second term --------------------
  742. // t.stop();
  743. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  744. // t.start();
  745. NICE::Vector kStar;
  746. fmk->hikComputeKernelVector ( x, kStar );
  747. // t.stop();
  748. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  749. //
  750. //now run the ILS method
  751. NICE::Vector diagonalElements;
  752. ikmsum->getDiagonalElements ( diagonalElements );
  753. // t.start();
  754. // init simple jacobi pre-conditioning
  755. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  756. //perform pre-conditioning
  757. if ( linsolver_cg != NULL )
  758. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  759. NICE::Vector beta;
  760. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  761. * K~ = K + sigma^2 I
  762. *
  763. * K~ \approx lambda_max v v^T
  764. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  765. * => \lambda_max v^T alpha = v^T k_*
  766. * => alpha = k_* / lambda_max could be a good initial start
  767. * If we put everything in the first equation this gives us
  768. * v = k_*
  769. * This reduces the number of iterations by 5 or 8
  770. */
  771. beta = (kStar * (1.0 / eigenMax[0]) );
  772. /* t.stop();
  773. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  774. t.start();*/
  775. // t.start();
  776. linsolver->solveLin ( *ikmsum, kStar, beta );
  777. // t.stop();
  778. // t.stop();
  779. // t.stop();
  780. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  781. beta *= kStar;
  782. double currentSecondTerm( beta.Sum() );
  783. predVariance = kSelf - currentSecondTerm;
  784. }
  785. //////////////////////////////////////////
  786. // variance computation: non-sparse inputs
  787. //////////////////////////////////////////
  788. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & 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. int dim ( 0 );
  796. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  797. {
  798. kSelf += pf->f ( 0, *it );
  799. // if weighted dimensions:
  800. //kSelf += pf->f(dim,*it);
  801. }
  802. // ---------------- compute the approximation of the second term --------------------
  803. double normKStar;
  804. if ( q != NULL )
  805. {
  806. if ( precomputedTForVarEst == NULL )
  807. {
  808. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  809. }
  810. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  811. }
  812. else
  813. {
  814. if ( precomputedAForVarEst.size () == 0 )
  815. {
  816. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  817. }
  818. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  819. }
  820. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  821. }
  822. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
  823. {
  824. // security check!
  825. if ( eigenMaxVectors.rows() == 0 )
  826. {
  827. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  828. }
  829. // ---------------- compute the first term --------------------
  830. // Timer t;
  831. // t.start();
  832. double kSelf ( 0.0 );
  833. int dim ( 0 );
  834. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  835. {
  836. kSelf += pf->f ( 0, *it );
  837. // if weighted dimensions:
  838. //kSelf += pf->f(dim,*it);
  839. }
  840. // ---------------- compute the approximation of the second term --------------------
  841. // t.stop();
  842. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  843. // t.start();
  844. NICE::Vector kStar;
  845. fmk->hikComputeKernelVector ( x, kStar );
  846. /* t.stop();
  847. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  848. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  849. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  850. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  851. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  852. //wherefor it takes aeons...
  853. //so we compute it by ourselves
  854. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  855. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  856. // double kStarI ( kStar[tmpI] );
  857. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  858. {
  859. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  860. {
  861. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  862. }
  863. }
  864. double projectionLength ( 0.0 );
  865. double currentSecondTerm ( 0.0 );
  866. double sumOfProjectionLengths ( 0.0 );
  867. int cnt ( 0 );
  868. NICE::Vector::const_iterator it = multiplicationResults.begin();
  869. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  870. {
  871. projectionLength = ( *it );
  872. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  873. sumOfProjectionLengths += pow ( projectionLength, 2 );
  874. it++;
  875. cnt++;
  876. }
  877. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  878. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  879. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  880. {
  881. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  882. }
  883. predVariance = kSelf - currentSecondTerm;
  884. }
  885. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & x, double & predVariance ) const
  886. {
  887. if ( ikmsum->getNumberOfModels() == 0 )
  888. {
  889. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  890. }
  891. Timer t;
  892. // t.start();
  893. // ---------------- compute the first term --------------------
  894. double kSelf ( 0.0 );
  895. int dim ( 0 );
  896. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  897. {
  898. kSelf += pf->f ( 0, *it );
  899. // if weighted dimensions:
  900. //kSelf += pf->f(dim,*it);
  901. }
  902. // ---------------- compute the second term --------------------
  903. // t.stop();
  904. // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
  905. // t.start();
  906. NICE::Vector kStar;
  907. fmk->hikComputeKernelVector ( x, kStar );
  908. // t.stop();
  909. // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
  910. //
  911. //now run the ILS method
  912. NICE::Vector diagonalElements;
  913. ikmsum->getDiagonalElements ( diagonalElements );
  914. // t.start();
  915. // init simple jacobi pre-conditioning
  916. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  917. //perform pre-conditioning
  918. if ( linsolver_cg != NULL )
  919. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  920. NICE::Vector beta;
  921. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  922. * K~ = K + sigma^2 I
  923. *
  924. * K~ \approx lambda_max v v^T
  925. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  926. * => \lambda_max v^T alpha = v^T k_*
  927. * => alpha = k_* / lambda_max could be a good initial start
  928. * If we put everything in the first equation this gives us
  929. * v = k_*
  930. * This reduces the number of iterations by 5 or 8
  931. */
  932. beta = (kStar * (1.0 / eigenMax[0]) );
  933. /* t.stop();
  934. std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
  935. t.start();*/
  936. // t.start();
  937. linsolver->solveLin ( *ikmsum, kStar, beta );
  938. // t.stop();
  939. // t.stop();
  940. // t.stop();
  941. // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
  942. beta *= kStar;
  943. double currentSecondTerm( beta.Sum() );
  944. predVariance = kSelf - currentSecondTerm;
  945. }
  946. // ---------------------- STORE AND RESTORE FUNCTIONS ----------------------
  947. void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
  948. {
  949. bool b_restoreVerbose ( false );
  950. #ifdef B_RESTOREVERBOSE
  951. b_restoreVerbose = true;
  952. #endif
  953. if ( is.good() )
  954. {
  955. if ( b_restoreVerbose )
  956. std::cerr << " in FMKGP restore" << std::endl;
  957. std::string tmp;
  958. is >> tmp; //class name
  959. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  960. {
  961. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  962. throw;
  963. }
  964. if (fmk != NULL)
  965. {
  966. delete fmk;
  967. fmk = NULL;
  968. }
  969. if ( ikmsum != NULL )
  970. {
  971. delete ikmsum;
  972. }
  973. ikmsum = new IKMLinearCombination ();
  974. if ( b_restoreVerbose )
  975. std::cerr << "ikmsum object created" << std::endl;
  976. is.precision ( numeric_limits<double>::digits10 + 1 );
  977. bool b_endOfBlock ( false ) ;
  978. while ( !b_endOfBlock )
  979. {
  980. is >> tmp; // start of block
  981. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  982. {
  983. b_endOfBlock = true;
  984. continue;
  985. }
  986. tmp = this->removeStartTag ( tmp );
  987. if ( b_restoreVerbose )
  988. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  989. if ( tmp.compare("fmk") == 0 )
  990. {
  991. fmk = new FastMinKernel;
  992. fmk->restore( is, format );
  993. is >> tmp; // end of block
  994. tmp = this->removeEndTag ( tmp );
  995. }
  996. else if ( tmp.compare("precomputedA") == 0 )
  997. {
  998. is >> tmp; // size
  999. int preCompSize ( 0 );
  1000. is >> preCompSize;
  1001. precomputedA.clear();
  1002. if ( b_restoreVerbose )
  1003. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1004. for ( int i = 0; i < preCompSize; i++ )
  1005. {
  1006. int nr;
  1007. is >> nr;
  1008. PrecomputedType pct;
  1009. pct.setIoUntilEndOfFile ( false );
  1010. pct.restore ( is, format );
  1011. precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1012. }
  1013. is >> tmp; // end of block
  1014. tmp = this->removeEndTag ( tmp );
  1015. }
  1016. else if ( tmp.compare("precomputedB") == 0 )
  1017. {
  1018. is >> tmp; // size
  1019. int preCompSize ( 0 );
  1020. is >> preCompSize;
  1021. precomputedB.clear();
  1022. if ( b_restoreVerbose )
  1023. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1024. for ( int i = 0; i < preCompSize; i++ )
  1025. {
  1026. int nr;
  1027. is >> nr;
  1028. PrecomputedType pct;
  1029. pct.setIoUntilEndOfFile ( false );
  1030. pct.restore ( is, format );
  1031. precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1032. }
  1033. is >> tmp; // end of block
  1034. tmp = this->removeEndTag ( tmp );
  1035. }
  1036. else if ( tmp.compare("precomputedT") == 0 )
  1037. {
  1038. is >> tmp; // size
  1039. int precomputedTSize ( 0 );
  1040. is >> precomputedTSize;
  1041. precomputedT.clear();
  1042. if ( b_restoreVerbose )
  1043. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1044. if ( precomputedTSize > 0 )
  1045. {
  1046. if ( b_restoreVerbose )
  1047. std::cerr << " restore precomputedT" << std::endl;
  1048. is >> tmp;
  1049. int sizeOfLUT;
  1050. is >> sizeOfLUT;
  1051. for (int i = 0; i < precomputedTSize; i++)
  1052. {
  1053. is >> tmp;
  1054. int index;
  1055. is >> index;
  1056. double * array = new double [ sizeOfLUT];
  1057. for ( int i = 0; i < sizeOfLUT; i++ )
  1058. {
  1059. is >> array[i];
  1060. }
  1061. precomputedT.insert ( std::pair<int, double*> ( index, array ) );
  1062. }
  1063. }
  1064. else
  1065. {
  1066. if ( b_restoreVerbose )
  1067. std::cerr << " skip restoring precomputedT" << std::endl;
  1068. }
  1069. is >> tmp; // end of block
  1070. tmp = this->removeEndTag ( tmp );
  1071. }
  1072. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1073. {
  1074. int sizeOfAForVarEst;
  1075. is >> sizeOfAForVarEst;
  1076. if ( b_restoreVerbose )
  1077. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1078. if (sizeOfAForVarEst > 0)
  1079. {
  1080. precomputedAForVarEst.clear();
  1081. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1082. precomputedAForVarEst.restore ( is, format );
  1083. }
  1084. is >> tmp; // end of block
  1085. tmp = this->removeEndTag ( tmp );
  1086. }
  1087. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1088. {
  1089. std::string isNull;
  1090. is >> isNull; // NOTNULL or NULL
  1091. if ( b_restoreVerbose )
  1092. std::cerr << "content of isNull: " << isNull << std::endl;
  1093. if (isNull.compare("NOTNULL") == 0)
  1094. {
  1095. if ( b_restoreVerbose )
  1096. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1097. int sizeOfLUT;
  1098. is >> sizeOfLUT;
  1099. precomputedTForVarEst = new double [ sizeOfLUT ];
  1100. for ( int i = 0; i < sizeOfLUT; i++ )
  1101. {
  1102. is >> precomputedTForVarEst[i];
  1103. }
  1104. }
  1105. else
  1106. {
  1107. if ( b_restoreVerbose )
  1108. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1109. if (precomputedTForVarEst != NULL)
  1110. delete precomputedTForVarEst;
  1111. }
  1112. is >> tmp; // end of block
  1113. tmp = this->removeEndTag ( tmp );
  1114. }
  1115. else if ( tmp.compare("eigenMax") == 0 )
  1116. {
  1117. is >> eigenMax;
  1118. is >> tmp; // end of block
  1119. tmp = this->removeEndTag ( tmp );
  1120. }
  1121. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1122. {
  1123. is >> eigenMaxVectors;
  1124. is >> tmp; // end of block
  1125. tmp = this->removeEndTag ( tmp );
  1126. }
  1127. else if ( tmp.compare("ikmsum") == 0 )
  1128. {
  1129. bool b_endOfBlock ( false ) ;
  1130. while ( !b_endOfBlock )
  1131. {
  1132. is >> tmp; // start of block
  1133. if ( this->isEndTag( tmp, "ikmsum" ) )
  1134. {
  1135. b_endOfBlock = true;
  1136. continue;
  1137. }
  1138. tmp = this->removeStartTag ( tmp );
  1139. if ( tmp.compare("IKMNoise") == 0 )
  1140. {
  1141. IKMNoise * ikmnoise = new IKMNoise ();
  1142. ikmnoise->restore ( is, format );
  1143. if ( b_restoreVerbose )
  1144. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1145. ikmsum->addModel ( ikmnoise );
  1146. }
  1147. else
  1148. {
  1149. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1150. throw;
  1151. }
  1152. }
  1153. }
  1154. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1155. {
  1156. is >> binaryLabelPositive;
  1157. is >> tmp; // end of block
  1158. tmp = this->removeEndTag ( tmp );
  1159. }
  1160. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1161. {
  1162. is >> binaryLabelNegative;
  1163. is >> tmp; // end of block
  1164. tmp = this->removeEndTag ( tmp );
  1165. }
  1166. else if ( tmp.compare("labels") == 0 )
  1167. {
  1168. is >> labels;
  1169. is >> tmp; // end of block
  1170. tmp = this->removeEndTag ( tmp );
  1171. }
  1172. else
  1173. {
  1174. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1175. throw;
  1176. }
  1177. }
  1178. //NOTE are there any more models you added? then add them here respectively in the correct order
  1179. //.....
  1180. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1181. if ( b_restoreVerbose )
  1182. std::cerr << " add GMHIKernel" << std::endl;
  1183. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1184. if ( b_restoreVerbose )
  1185. std::cerr << " restore positive and negative label" << std::endl;
  1186. knownClasses.clear();
  1187. if ( b_restoreVerbose )
  1188. std::cerr << " fill known classes object " << std::endl;
  1189. if ( precomputedA.size() == 1)
  1190. {
  1191. knownClasses.insert( binaryLabelPositive );
  1192. knownClasses.insert( binaryLabelNegative );
  1193. if ( b_restoreVerbose )
  1194. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1195. }
  1196. else
  1197. {
  1198. for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
  1199. knownClasses.insert ( itA->first );
  1200. if ( b_restoreVerbose )
  1201. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1202. }
  1203. }
  1204. else
  1205. {
  1206. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1207. throw;
  1208. }
  1209. }
  1210. void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
  1211. {
  1212. if ( os.good() )
  1213. {
  1214. // show starting point
  1215. os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1216. os << this->createStartTag( "fmk" ) << std::endl;
  1217. fmk->store ( os, format );
  1218. os << this->createEndTag( "fmk" ) << std::endl;
  1219. os.precision ( numeric_limits<double>::digits10 + 1 );
  1220. //we only have to store the things we computed, since the remaining settings come with the config file afterwards
  1221. os << this->createStartTag( "precomputedA" ) << std::endl;
  1222. os << "size: " << precomputedA.size() << std::endl;
  1223. std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
  1224. for ( uint i = 0; i < precomputedA.size(); i++ )
  1225. {
  1226. os << preCompIt->first << std::endl;
  1227. ( preCompIt->second ).store ( os, format );
  1228. preCompIt++;
  1229. }
  1230. os << this->createEndTag( "precomputedA" ) << std::endl;
  1231. os << this->createStartTag( "precomputedB" ) << std::endl;
  1232. os << "size: " << precomputedB.size() << std::endl;
  1233. preCompIt = precomputedB.begin();
  1234. for ( uint i = 0; i < precomputedB.size(); i++ )
  1235. {
  1236. os << preCompIt->first << std::endl;
  1237. ( preCompIt->second ).store ( os, format );
  1238. preCompIt++;
  1239. }
  1240. os << this->createEndTag( "precomputedB" ) << std::endl;
  1241. os << this->createStartTag( "precomputedT" ) << std::endl;
  1242. os << "size: " << precomputedT.size() << std::endl;
  1243. if ( precomputedT.size() > 0 )
  1244. {
  1245. int sizeOfLUT ( 0 );
  1246. if ( q != NULL )
  1247. sizeOfLUT = q->size() * this->fmk->get_d();
  1248. os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1249. for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
  1250. {
  1251. os << "index: " << it->first << std::endl;
  1252. for ( int i = 0; i < sizeOfLUT; i++ )
  1253. {
  1254. os << ( it->second ) [i] << " ";
  1255. }
  1256. os << std::endl;
  1257. }
  1258. }
  1259. os << this->createEndTag( "precomputedT" ) << std::endl;
  1260. //now store the things needed for the variance estimation
  1261. os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  1262. os << precomputedAForVarEst.size() << std::endl;
  1263. if (precomputedAForVarEst.size() > 0)
  1264. {
  1265. precomputedAForVarEst.store ( os, format );
  1266. os << std::endl;
  1267. }
  1268. os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  1269. os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  1270. if ( precomputedTForVarEst != NULL )
  1271. {
  1272. os << "NOTNULL" << std::endl;
  1273. int sizeOfLUT ( 0 );
  1274. if ( q != NULL )
  1275. sizeOfLUT = q->size() * this->fmk->get_d();
  1276. os << sizeOfLUT << std::endl;
  1277. for ( int i = 0; i < sizeOfLUT; i++ )
  1278. {
  1279. os << precomputedTForVarEst[i] << " ";
  1280. }
  1281. os << std::endl;
  1282. }
  1283. else
  1284. {
  1285. os << "NULL" << std::endl;
  1286. }
  1287. os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  1288. //store the eigenvalues and eigenvectors
  1289. os << this->createStartTag( "eigenMax" ) << std::endl;
  1290. os << eigenMax << std::endl;
  1291. os << this->createEndTag( "eigenMax" ) << std::endl;
  1292. os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  1293. os << eigenMaxVectors << std::endl;
  1294. os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  1295. os << this->createStartTag( "ikmsum" ) << std::endl;
  1296. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1297. {
  1298. ( ikmsum->getModel ( j ) )->store ( os, format );
  1299. }
  1300. os << this->createEndTag( "ikmsum" ) << std::endl;
  1301. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1302. os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1303. os << binaryLabelPositive << std::endl;
  1304. os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1305. os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1306. os << binaryLabelNegative << std::endl;
  1307. os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1308. os << this->createStartTag( "labels" ) << std::endl;
  1309. os << labels << std::endl;
  1310. os << this->createEndTag( "labels" ) << std::endl;
  1311. // done
  1312. os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1313. }
  1314. else
  1315. {
  1316. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1317. }
  1318. }
  1319. void FMKGPHyperparameterOptimization::clear ( ) {};