FMKGPHyperparameterOptimization.cpp 64 KB

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