FMKGPHyperparameterOptimization.cpp 50 KB

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