FMKGPHyperparameterOptimization.cpp 63 KB

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