FMKGPHyperparameterOptimization.cpp 63 KB

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