FMKGPHyperparameterOptimization.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  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 "gp-hik-core/FMKGPHyperparameterOptimization.h"
  29. #include "gp-hik-core/FastMinKernel.h"
  30. #include "gp-hik-core/GMHIKernel.h"
  31. #include "gp-hik-core/IKMNoise.h"
  32. //
  33. #include "gp-hik-core/parameterizedFunctions/PFIdentity.h"
  34. #include "gp-hik-core/parameterizedFunctions/PFAbsExp.h"
  35. #include "gp-hik-core/parameterizedFunctions/PFExp.h"
  36. #include "gp-hik-core/parameterizedFunctions/PFMKL.h"
  37. #include "gp-hik-core/parameterizedFunctions/PFWeightedDim.h"
  38. using namespace NICE;
  39. using namespace std;
  40. /////////////////////////////////////////////////////
  41. /////////////////////////////////////////////////////
  42. // PROTECTED METHODS
  43. /////////////////////////////////////////////////////
  44. /////////////////////////////////////////////////////
  45. void FMKGPHyperparameterOptimization::updateAfterIncrement (
  46. const std::set < int > newClasses,
  47. const bool & performOptimizationAfterIncrement )
  48. {
  49. if ( this->fmk == NULL )
  50. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  51. std::map<int, NICE::Vector> binaryLabels;
  52. std::set<int> classesToUse;
  53. //TODO this could be made faster when storing the previous binary label vectors...
  54. if ( this->b_performRegression )
  55. {
  56. // for regression, we are not interested in regression scores, rather than in any "label"
  57. int regressionLabel ( 1 );
  58. binaryLabels.insert ( std::pair< int, NICE::Vector> ( regressionLabel, this->labels ) );
  59. }
  60. else
  61. this->prepareBinaryLabels ( binaryLabels, this->labels , classesToUse );
  62. if ( this->verbose )
  63. std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
  64. NICE::Timer t1;
  65. NICE::GPLikelihoodApprox * gplike;
  66. uint parameterVectorSize;
  67. t1.start();
  68. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  69. t1.stop();
  70. if ( this->verboseTime )
  71. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  72. t1.start();
  73. if ( this->b_usePreviousAlphas && ( this->previousAlphas.size() > 0) )
  74. {
  75. //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
  76. //default in GPLikelihoodApprox for the first time:
  77. // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
  78. double factor ( 1.0 / this->eigenMax[0] );
  79. // if we came from an OCC setting and are going to a binary setting,
  80. // we have to be aware that the 'positive' label is always the one associated with the previous alpha
  81. // otherwise, we would get into trouble when going to more classes...
  82. // note that this is needed, since knownClasses is a map, so we loose the order of insertion
  83. if ( ( this->previousAlphas.size () == 1 ) && ( this->knownClasses.size () == 2 ) )
  84. {
  85. // if the first class has a larger value then the currently added second class, we have to
  86. // switch the index, which unfortunately is not sooo easy in the map
  87. if ( this->previousAlphas.begin()->first == this->binaryLabelNegative )
  88. {
  89. this->previousAlphas.insert( std::pair<int, NICE::Vector> ( this->binaryLabelPositive, this->previousAlphas.begin()->second) );
  90. this->previousAlphas.erase( this->binaryLabelNegative );
  91. }
  92. }
  93. std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
  94. for ( std::map<int, NICE::Vector>::iterator prevAlphaIt = this->previousAlphas.begin();
  95. prevAlphaIt != this->previousAlphas.end();
  96. prevAlphaIt++
  97. )
  98. {
  99. int oldSize ( prevAlphaIt->second.size() );
  100. prevAlphaIt->second.resize ( oldSize + 1 );
  101. if ( binaryLabelsIt->second[oldSize] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
  102. prevAlphaIt->second[oldSize] = factor;
  103. else
  104. prevAlphaIt->second[oldSize] = -factor; //we follow the initialization as done in previous steps
  105. //prevAlphaIt->second[oldSize] = 0.0; // following the suggestion of Yeh and Darrell
  106. binaryLabelsIt++;
  107. }
  108. //compute unaffected alpha-vectors for the new classes
  109. for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
  110. {
  111. NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
  112. previousAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
  113. }
  114. gplike->setInitialAlphaGuess ( &previousAlphas );
  115. }
  116. else
  117. {
  118. //if we do not use previous alphas, we do not have to set up anything here
  119. gplike->setInitialAlphaGuess ( NULL );
  120. }
  121. t1.stop();
  122. if ( this->verboseTime )
  123. std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
  124. if ( this->verbose )
  125. std::cerr << "update Eigendecomposition " << std::endl;
  126. t1.start();
  127. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  128. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  129. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  130. t1.stop();
  131. if ( this->verboseTime )
  132. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  133. ////////////////////// //////////////////////
  134. // RE-RUN THE OPTIMIZATION, IF DESIRED //
  135. ////////////////////// //////////////////////
  136. if ( this->verbose )
  137. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  138. // we can reuse the already given performOptimization-method:
  139. // OPT_GREEDY
  140. // for this strategy we can't reuse any of the previously computed scores
  141. // so come on, let's do the whole thing again...
  142. // OPT_DOWNHILLSIMPLEX
  143. // Here we can benefit from previous results, when we use them as initialization for our optimizer
  144. // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
  145. // as initialization
  146. // OPT_NONE
  147. // nothing to do, obviously
  148. if ( this->verbose )
  149. std::cerr << "perform optimization after increment " << std::endl;
  150. OPTIMIZATIONTECHNIQUE optimizationMethodTmpCopy;
  151. if ( !performOptimizationAfterIncrement )
  152. {
  153. // if no optimization shall be carried out, we simply set the optimization method to NONE but run the optimization
  154. // call nonetheless, thereby computing alpha vectors, etc. which would be not initialized
  155. optimizationMethodTmpCopy = this->optimizationMethod;
  156. this->optimizationMethod = OPT_NONE;
  157. }
  158. t1.start();
  159. this->performOptimization ( *gplike, parameterVectorSize);
  160. t1.stop();
  161. if ( this->verboseTime )
  162. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  163. if ( this->verbose )
  164. std::cerr << "Preparing after retraining for classification ..." << std::endl;
  165. t1.start();
  166. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  167. t1.stop();
  168. if ( this->verboseTime)
  169. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  170. if ( !performOptimizationAfterIncrement )
  171. {
  172. this->optimizationMethod = optimizationMethodTmpCopy;
  173. }
  174. //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
  175. // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
  176. // Since we are not aware of any such method, we have to compute them completely new
  177. // :/
  178. t1.start();
  179. this->computeMatricesAndLUTs ( *gplike );
  180. t1.stop();
  181. if ( this->verboseTime )
  182. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  183. //don't waste memory
  184. delete gplike;
  185. }
  186. /////////////////////////////////////////////////////
  187. /////////////////////////////////////////////////////
  188. // PUBLIC METHODS
  189. /////////////////////////////////////////////////////
  190. /////////////////////////////////////////////////////
  191. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization( )
  192. {
  193. // initialize pointer variables
  194. this->pf = NULL;
  195. this->eig = NULL;
  196. this->linsolver = NULL;
  197. this->fmk = NULL;
  198. this->q = NULL;
  199. this->precomputedTForVarEst = NULL;
  200. this->ikmsum = NULL;
  201. // initialize boolean flags
  202. this->verbose = false;
  203. this->verboseTime = false;
  204. this->debug = false;
  205. //stupid unneeded default values
  206. this->binaryLabelPositive = -1;
  207. this->binaryLabelNegative = -2;
  208. this->knownClasses.clear();
  209. this->b_usePreviousAlphas = false;
  210. this->b_performRegression = false;
  211. }
  212. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization( const bool & b_performRegression )
  213. {
  214. ///////////
  215. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  216. ///////////
  217. // initialize pointer variables
  218. this->pf = NULL;
  219. this->eig = NULL;
  220. this->linsolver = NULL;
  221. this->fmk = NULL;
  222. this->q = NULL;
  223. this->precomputedTForVarEst = NULL;
  224. this->ikmsum = NULL;
  225. // initialize boolean flags
  226. this->verbose = false;
  227. this->verboseTime = false;
  228. this->debug = false;
  229. //stupid unneeded default values
  230. this->binaryLabelPositive = -1;
  231. this->binaryLabelNegative = -2;
  232. this->knownClasses.clear();
  233. this->b_usePreviousAlphas = false;
  234. this->b_performRegression = false;
  235. ///////////
  236. // here comes the new code part different from the empty constructor
  237. ///////////
  238. this->b_performRegression = b_performRegression;
  239. }
  240. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, const string & _confSection )
  241. {
  242. ///////////
  243. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  244. ///////////
  245. // initialize pointer variables
  246. this->pf = NULL;
  247. this->eig = NULL;
  248. this->linsolver = NULL;
  249. this->fmk = NULL;
  250. this->q = NULL;
  251. this->precomputedTForVarEst = NULL;
  252. this->ikmsum = NULL;
  253. // initialize boolean flags
  254. this->verbose = false;
  255. this->verboseTime = false;
  256. this->debug = false;
  257. //stupid unneeded default values
  258. this->binaryLabelPositive = -1;
  259. this->binaryLabelNegative = -2;
  260. this->knownClasses.clear();
  261. this->b_usePreviousAlphas = false;
  262. this->b_performRegression = false;
  263. ///////////
  264. // here comes the new code part different from the empty constructor
  265. ///////////
  266. this->initFromConfig ( _conf, _confSection );
  267. }
  268. FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, FastMinKernel *_fmk, const string & _confSection )
  269. {
  270. ///////////
  271. // same code as in empty constructor - duplication can be avoided with C++11 allowing for constructor delegation
  272. ///////////
  273. // initialize pointer variables
  274. this->pf = NULL;
  275. this->eig = NULL;
  276. this->linsolver = NULL;
  277. this->fmk = NULL;
  278. this->q = NULL;
  279. this->precomputedTForVarEst = NULL;
  280. this->ikmsum = NULL;
  281. // initialize boolean flags
  282. this->verbose = false;
  283. this->verboseTime = false;
  284. this->debug = false;
  285. //stupid unneeded default values
  286. this->binaryLabelPositive = -1;
  287. this->binaryLabelNegative = -2;
  288. this->knownClasses.clear();
  289. this->b_usePreviousAlphas = false;
  290. this->b_performRegression = false;
  291. ///////////
  292. // here comes the new code part different from the empty constructor
  293. ///////////
  294. this->initFromConfig ( _conf, _confSection );
  295. this->setFastMinKernel( _fmk );
  296. }
  297. FMKGPHyperparameterOptimization::~FMKGPHyperparameterOptimization()
  298. {
  299. //////////////////////////////////////
  300. // classification related variables //
  301. //////////////////////////////////////
  302. if ( this->fmk != NULL )
  303. delete this->fmk;
  304. if ( this->q != NULL )
  305. delete this->q;
  306. if ( this->pf != NULL )
  307. delete this->pf;
  308. for ( uint i = 0 ; i < this->precomputedT.size(); i++ )
  309. delete [] ( this->precomputedT[i] );
  310. if ( this->ikmsum != NULL )
  311. delete this->ikmsum;
  312. //////////////////////////////////////////////
  313. // Iterative Linear Solver //
  314. //////////////////////////////////////////////
  315. if ( this->linsolver != NULL )
  316. delete this->linsolver;
  317. //////////////////////////////////////////////
  318. // likelihood computation related variables //
  319. //////////////////////////////////////////////
  320. if ( this->eig != NULL )
  321. delete this->eig;
  322. ////////////////////////////////////////////
  323. // variance computation related variables //
  324. ////////////////////////////////////////////
  325. if ( this->precomputedTForVarEst != NULL )
  326. delete this->precomputedTForVarEst;
  327. }
  328. void FMKGPHyperparameterOptimization::initFromConfig ( const Config *_conf, const std::string & _confSection )
  329. {
  330. ///////////////////////////////////
  331. // output/debug related settings //
  332. ///////////////////////////////////
  333. this->verbose = _conf->gB ( _confSection, "verbose", false );
  334. this->verboseTime = _conf->gB ( _confSection, "verboseTime", false );
  335. this->debug = _conf->gB ( _confSection, "debug", false );
  336. if ( this->verbose )
  337. {
  338. std::cerr << "------------" << std::endl;
  339. std::cerr << "| set-up |" << std::endl;
  340. std::cerr << "------------" << std::endl;
  341. }
  342. //////////////////////////////////////
  343. // classification related variables //
  344. //////////////////////////////////////
  345. this->b_performRegression = _conf->gB ( _confSection, "b_performRegression", false );
  346. bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
  347. if ( this->verbose )
  348. {
  349. std::cerr << "_confSection: " << _confSection << std::endl;
  350. std::cerr << "use_quantization: " << useQuantization << std::endl;
  351. }
  352. if ( _conf->gB ( _confSection, "use_quantization", false ) )
  353. {
  354. int numBins = _conf->gI ( _confSection, "num_bins", 100 );
  355. if ( this->verbose )
  356. std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
  357. this->q = new Quantization ( numBins );
  358. }
  359. else
  360. {
  361. this->q = NULL;
  362. }
  363. this->parameterUpperBound = _conf->gD ( _confSection, "parameter_upper_bound", 2.5 );
  364. this->parameterLowerBound = _conf->gD ( _confSection, "parameter_lower_bound", 1.0 );
  365. std::string transform = _conf->gS( _confSection, "transform", "absexp" );
  366. if ( transform == "identity" )
  367. {
  368. this->pf = new NICE::PFIdentity( );
  369. }
  370. else if ( transform == "absexp" )
  371. {
  372. this->pf = new NICE::PFAbsExp( 1.0, parameterLowerBound, parameterUpperBound );
  373. }
  374. else if ( transform == "exp" )
  375. {
  376. this->pf = new NICE::PFExp( 1.0, parameterLowerBound, parameterUpperBound );
  377. }
  378. else if ( transform == "MKL" )
  379. {
  380. //TODO generic, please :) load from a separate file or something like this!
  381. std::set<int> steps; steps.insert(4000); steps.insert(6000); //specific for VISAPP
  382. this->pf = new NICE::PFMKL( steps, parameterLowerBound, parameterUpperBound );
  383. }
  384. else if ( transform == "weightedDim" )
  385. {
  386. int pf_dim = _conf->gI ( _confSection, "pf_dim", 8 );
  387. this->pf = new NICE::PFWeightedDim( pf_dim, parameterLowerBound, parameterUpperBound );
  388. }
  389. else
  390. {
  391. fthrow(Exception, "Transformation type is unknown " << transform);
  392. }
  393. //////////////////////////////////////////////
  394. // Iterative Linear Solver //
  395. //////////////////////////////////////////////
  396. bool ils_verbose = _conf->gB ( _confSection, "ils_verbose", false );
  397. ils_max_iterations = _conf->gI ( _confSection, "ils_max_iterations", 1000 );
  398. if ( this->verbose )
  399. std::cerr << "FMKGPHyperparameterOptimization: maximum number of iterations is " << ils_max_iterations << std::endl;
  400. double ils_min_delta = _conf->gD ( _confSection, "ils_min_delta", 1e-7 );
  401. double ils_min_residual = _conf->gD ( _confSection, "ils_min_residual", 1e-7/*1e-2 */ );
  402. string ils_method = _conf->gS ( _confSection, "ils_method", "CG" );
  403. if ( ils_method.compare ( "CG" ) == 0 )
  404. {
  405. if ( this->verbose )
  406. 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;
  407. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  408. if ( this->verbose )
  409. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients" << std::endl;
  410. }
  411. else if ( ils_method.compare ( "CGL" ) == 0 )
  412. {
  413. this->linsolver = new ILSConjugateGradientsLanczos ( ils_verbose , ils_max_iterations );
  414. if ( this->verbose )
  415. std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients (Lanczos)" << std::endl;
  416. }
  417. else if ( ils_method.compare ( "SYMMLQ" ) == 0 )
  418. {
  419. this->linsolver = new ILSSymmLqLanczos ( ils_verbose , ils_max_iterations );
  420. if ( this->verbose )
  421. std::cerr << "FMKGPHyperparameterOptimization: using ILS SYMMLQ" << std::endl;
  422. }
  423. else if ( ils_method.compare ( "MINRES" ) == 0 )
  424. {
  425. this->linsolver = new ILSMinResLanczos ( ils_verbose , ils_max_iterations );
  426. if ( this->verbose )
  427. std::cerr << "FMKGPHyperparameterOptimization: using ILS MINRES" << std::endl;
  428. }
  429. else
  430. {
  431. std::cerr << "FMKGPHyperparameterOptimization: " << _confSection << ":ils_method (" << ils_method << ") does not match any type (CG,CGL,SYMMLQ,MINRES), I will use CG" << std::endl;
  432. this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
  433. }
  434. /////////////////////////////////////
  435. // optimization related parameters //
  436. /////////////////////////////////////
  437. std::string optimizationMethod_s = _conf->gS ( _confSection, "optimization_method", "greedy" );
  438. if ( optimizationMethod_s == "greedy" )
  439. optimizationMethod = OPT_GREEDY;
  440. else if ( optimizationMethod_s == "downhillsimplex" )
  441. optimizationMethod = OPT_DOWNHILLSIMPLEX;
  442. else if ( optimizationMethod_s == "none" )
  443. optimizationMethod = OPT_NONE;
  444. else
  445. fthrow ( Exception, "Optimization method " << optimizationMethod_s << " is not known." );
  446. if ( this->verbose )
  447. std::cerr << "Using optimization method: " << optimizationMethod_s << std::endl;
  448. this->parameterStepSize = _conf->gD ( _confSection, "parameter_step_size", 0.1 );
  449. this->optimizeNoise = _conf->gB ( _confSection, "optimize_noise", false );
  450. if ( this->verbose )
  451. std::cerr << "Optimize noise: " << ( optimizeNoise ? "on" : "off" ) << std::endl;
  452. // if nothing is to be optimized and we have no other hyperparameters, then we could explicitly switch-off the optimization
  453. if ( !optimizeNoise && (transform == "identity") && (optimizationMethod != OPT_NONE) )
  454. {
  455. std::cerr << "FMKGPHyperparameterOptimization::initFromConfig No hyperparameter to optimize but optimization chosen... We ignore optimization. You might want to check this!" << std::endl;
  456. this->optimizationMethod = OPT_NONE;
  457. }
  458. downhillSimplexMaxIterations = _conf->gI ( _confSection, "downhillsimplex_max_iterations", 20 );
  459. // do not run longer than a day :)
  460. downhillSimplexTimeLimit = _conf->gD ( _confSection, "downhillsimplex_time_limit", 24 * 60 * 60 );
  461. downhillSimplexParamTol = _conf->gD ( _confSection, "downhillsimplex_delta", 0.01 );
  462. //////////////////////////////////////////////
  463. // likelihood computation related variables //
  464. //////////////////////////////////////////////
  465. this->verifyApproximation = _conf->gB ( _confSection, "verify_approximation", false );
  466. // this->eig = new EigValuesTRLAN();
  467. // My time measurements show that both methods use equal time, a comparision
  468. // of their numerical performance has not been done yet
  469. this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */, 10 );
  470. this->nrOfEigenvaluesToConsider = _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 );
  471. ////////////////////////////////////////////
  472. // variance computation related variables //
  473. ////////////////////////////////////////////
  474. this->nrOfEigenvaluesToConsiderForVarApprox = _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 );
  475. /////////////////////////////////////////////////////
  476. // online / incremental learning related variables //
  477. /////////////////////////////////////////////////////
  478. this->b_usePreviousAlphas = _conf->gB ( _confSection, "b_usePreviousAlphas", true );
  479. if ( this->verbose )
  480. {
  481. std::cerr << "------------" << std::endl;
  482. std::cerr << "| start |" << std::endl;
  483. std::cerr << "------------" << std::endl;
  484. }
  485. }
  486. ///////////////////// ///////////////////// /////////////////////
  487. // GET / SET
  488. ///////////////////// ///////////////////// /////////////////////
  489. void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
  490. {
  491. parameterUpperBound = _parameterUpperBound;
  492. }
  493. void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
  494. {
  495. parameterLowerBound = _parameterLowerBound;
  496. }
  497. std::set<int> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
  498. {
  499. return this->knownClasses;
  500. }
  501. void FMKGPHyperparameterOptimization::setPerformRegression ( const bool & b_performRegression )
  502. {
  503. //TODO check previously whether we already trained
  504. if ( false )
  505. throw NICE::Exception ( "FMPGKHyperparameterOptimization already initialized - switching between classification and regression not allowed!" );
  506. else
  507. this->b_performRegression = b_performRegression;
  508. }
  509. void FMKGPHyperparameterOptimization::setFastMinKernel ( FastMinKernel * _fmk )
  510. {
  511. //TODO check previously whether we already trained
  512. if ( _fmk != NULL )
  513. {
  514. if ( this->fmk != NULL )
  515. {
  516. delete this->fmk;
  517. this->fmk = NULL;
  518. }
  519. this->fmk = _fmk;
  520. }
  521. }
  522. void FMKGPHyperparameterOptimization::setNrOfEigenvaluesToConsiderForVarApprox ( const int & i_nrOfEigenvaluesToConsiderForVarApprox )
  523. {
  524. //TODO check previously whether we already trained
  525. this->nrOfEigenvaluesToConsiderForVarApprox = i_nrOfEigenvaluesToConsiderForVarApprox;
  526. }
  527. ///////////////////// ///////////////////// /////////////////////
  528. // CLASSIFIER STUFF
  529. ///////////////////// ///////////////////// /////////////////////
  530. inline void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize )
  531. {
  532. gplike = new GPLikelihoodApprox ( binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
  533. gplike->setDebug( debug );
  534. gplike->setVerbose( this->verbose );
  535. parameterVectorSize = ikmsum->getNumParameters();
  536. }
  537. void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & i_noEigenValues )
  538. {
  539. //compute the largest eigenvalue of K + noise
  540. try
  541. {
  542. eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, i_noEigenValues );
  543. }
  544. catch ( char const* exceptionMsg)
  545. {
  546. std::cerr << exceptionMsg << std::endl;
  547. throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
  548. }
  549. //NOTE EigenValue computation extracts EV and EW per default in decreasing order.
  550. }
  551. void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  552. {
  553. if (verbose)
  554. std::cerr << "perform optimization" << std::endl;
  555. if ( optimizationMethod == OPT_GREEDY )
  556. {
  557. if ( this->verbose )
  558. std::cerr << "OPT_GREEDY!!! " << std::endl;
  559. // simple greedy strategy
  560. if ( ikmsum->getNumParameters() != 1 )
  561. fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
  562. NICE::Vector lB = ikmsum->getParameterLowerBounds();
  563. NICE::Vector uB = ikmsum->getParameterUpperBounds();
  564. if ( this->verbose )
  565. std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
  566. for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
  567. {
  568. OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
  569. gplike.evaluate ( hyperp );
  570. }
  571. }
  572. else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
  573. {
  574. //standard as before, normal optimization
  575. if ( this->verbose )
  576. std::cerr << "DOWNHILLSIMPLEX!!! " << std::endl;
  577. // downhill simplex strategy
  578. OPTIMIZATION::DownhillSimplexOptimizer optimizer;
  579. OPTIMIZATION::matrix_type initialParams ( parameterVectorSize, 1 );
  580. NICE::Vector currentParameters;
  581. ikmsum->getParameters ( currentParameters );
  582. for ( uint i = 0 ; i < parameterVectorSize; i++ )
  583. initialParams(i,0) = currentParameters[ i ];
  584. if ( this->verbose )
  585. std::cerr << "Initial parameters: " << initialParams << std::endl;
  586. //the scales object does not really matter in the actual implementation of Downhill Simplex
  587. // OPTIMIZATION::matrix_type scales ( parameterVectorSize, 1);
  588. // scales.set(1.0);
  589. OPTIMIZATION::SimpleOptProblem optProblem ( &gplike, initialParams, initialParams /* scales */ );
  590. optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
  591. optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
  592. optimizer.setParamTol ( true, downhillSimplexParamTol );
  593. optimizer.optimizeProb ( optProblem );
  594. }
  595. else if ( optimizationMethod == OPT_NONE )
  596. {
  597. if ( this->verbose )
  598. std::cerr << "NO OPTIMIZATION!!! " << std::endl;
  599. // without optimization
  600. if ( optimizeNoise )
  601. fthrow ( Exception, "Deactivate optimize_noise!" );
  602. if ( this->verbose )
  603. std::cerr << "Optimization is deactivated!" << std::endl;
  604. double value (1.0);
  605. if ( this->parameterLowerBound == this->parameterUpperBound)
  606. value = this->parameterLowerBound;
  607. pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
  608. pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
  609. // we use the standard value
  610. OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
  611. gplike.setParameterLowerBound ( value );
  612. gplike.setParameterUpperBound ( value );
  613. //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
  614. gplike.computeAlphaDirect( hyperp, eigenMax );
  615. }
  616. if ( this->verbose )
  617. {
  618. std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
  619. }
  620. }
  621. void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
  622. {
  623. // transform all features with the currently "optimal" parameter
  624. ikmsum->setParameters ( gplike.getBestParameters() );
  625. }
  626. void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
  627. {
  628. precomputedA.clear();
  629. precomputedB.clear();
  630. for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
  631. {
  632. PrecomputedType A;
  633. PrecomputedType B;
  634. fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
  635. A.setIoUntilEndOfFile ( false );
  636. B.setIoUntilEndOfFile ( false );
  637. precomputedA[ i->first ] = A;
  638. precomputedB[ i->first ] = B;
  639. if ( q != NULL )
  640. {
  641. double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
  642. //just to be sure that we do not waste space here
  643. if ( precomputedT[ i->first ] != NULL )
  644. delete precomputedT[ i->first ];
  645. precomputedT[ i->first ] = T;
  646. }
  647. }
  648. if ( this->precomputedTForVarEst != NULL )
  649. {
  650. this->prepareVarianceApproximationRough();
  651. }
  652. else if ( this->nrOfEigenvaluesToConsiderForVarApprox > 0)
  653. {
  654. this->prepareVarianceApproximationFine();
  655. }
  656. // in case that we should want to store the alpha vectors for incremental extensions
  657. if ( this->b_usePreviousAlphas )
  658. this->previousAlphas = gplike.getBestAlphas();
  659. }
  660. #ifdef NICE_USELIB_MATIO
  661. void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
  662. {
  663. std::map<int, int> examples;
  664. NICE::Vector y ( yl.size() );
  665. int ind = 0;
  666. for ( uint i = 0 ; i < yl.size(); i++ )
  667. {
  668. if ( positives.find ( i ) != positives.end() ) {
  669. y[ examples.size() ] = 1.0;
  670. examples.insert ( pair<int, int> ( i, ind ) );
  671. ind++;
  672. } else if ( negatives.find ( i ) != negatives.end() ) {
  673. y[ examples.size() ] = -1.0;
  674. examples.insert ( pair<int, int> ( i, ind ) );
  675. ind++;
  676. }
  677. }
  678. y.resize ( examples.size() );
  679. std::cerr << "Examples: " << examples.size() << std::endl;
  680. optimize ( data, y, examples, noise );
  681. }
  682. void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
  683. {
  684. NICE::Timer t;
  685. t.start();
  686. std::cerr << "Initializing data structure ..." << std::endl;
  687. if ( fmk != NULL ) delete fmk;
  688. fmk = new FastMinKernel ( data, noise, examples );
  689. t.stop();
  690. if (verboseTime)
  691. std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
  692. optimize ( y );
  693. }
  694. #endif
  695. int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
  696. {
  697. myClasses.clear();
  698. // determine which classes we have in our label vector
  699. // -> MATLAB: myClasses = unique(y);
  700. for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
  701. {
  702. if ( myClasses.find ( *it ) == myClasses.end() )
  703. {
  704. myClasses.insert ( *it );
  705. }
  706. }
  707. //count how many different classes appear in our data
  708. int nrOfClasses = myClasses.size();
  709. binaryLabels.clear();
  710. //compute the corresponding binary label vectors
  711. if ( nrOfClasses > 2 )
  712. {
  713. //resize every labelVector and set all entries to -1.0
  714. for ( std::set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
  715. {
  716. binaryLabels[ *k ].resize ( y.size() );
  717. binaryLabels[ *k ].set ( -1.0 );
  718. }
  719. // now look on every example and set the entry of its corresponding label vector to 1.0
  720. // proper existance should not be a problem
  721. for ( int i = 0 ; i < ( int ) y.size(); i++ )
  722. binaryLabels[ y[i] ][i] = 1.0;
  723. }
  724. else if ( nrOfClasses == 2 )
  725. {
  726. //binary setting -- prepare a binary label vector
  727. NICE::Vector yb ( y );
  728. this->binaryLabelNegative = *(myClasses.begin());
  729. std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
  730. this->binaryLabelPositive = *classIt;
  731. if ( this->verbose )
  732. std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
  733. for ( uint i = 0 ; i < yb.size() ; i++ )
  734. yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
  735. binaryLabels[ binaryLabelPositive ] = yb;
  736. //we do NOT do real binary computation, but an implicite one with only a single object
  737. nrOfClasses--;
  738. }
  739. else //OCC setting
  740. {
  741. //we set the labels to 1, independent of the previously given class number
  742. //however, the original class numbers are stored and returned in classification
  743. NICE::Vector yOne ( y.size(), 1 );
  744. binaryLabels[ *(myClasses.begin()) ] = yOne;
  745. //we have to indicate, that we are in an OCC setting
  746. nrOfClasses--;
  747. }
  748. return nrOfClasses;
  749. }
  750. void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
  751. {
  752. if ( fmk == NULL )
  753. fthrow ( Exception, "FastMinKernel object was not initialized!" );
  754. this->labels = y;
  755. std::map<int, NICE::Vector> binaryLabels;
  756. if ( this->b_performRegression )
  757. {
  758. // for regression, we are not interested in regression scores, rather than in any "label"
  759. int regressionLabel ( 1 );
  760. binaryLabels.insert ( std::pair< int, NICE::Vector> ( regressionLabel, y ) );
  761. this->knownClasses.clear();
  762. this->knownClasses.insert ( regressionLabel );
  763. }
  764. else
  765. {
  766. this->prepareBinaryLabels ( binaryLabels, y , knownClasses );
  767. }
  768. //now call the main function :)
  769. this->optimize(binaryLabels);
  770. }
  771. void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
  772. {
  773. Timer t;
  774. t.start();
  775. //how many different classes do we have right now?
  776. int nrOfClasses = binaryLabels.size();
  777. if (verbose)
  778. {
  779. std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
  780. std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
  781. std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
  782. }
  783. // combine standard model and noise model
  784. Timer t1;
  785. t1.start();
  786. //setup the kernel combination
  787. ikmsum = new IKMLinearCombination ();
  788. if ( this->verbose )
  789. {
  790. std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
  791. }
  792. //First model: noise
  793. ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
  794. // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
  795. fmk->setNoise ( 0.0 );
  796. ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
  797. t1.stop();
  798. if (verboseTime)
  799. std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
  800. GPLikelihoodApprox * gplike;
  801. uint parameterVectorSize;
  802. t1.start();
  803. this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
  804. t1.stop();
  805. if (verboseTime)
  806. std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
  807. if (verbose)
  808. {
  809. std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
  810. }
  811. t1.start();
  812. // we compute all needed eigenvectors for standard classification and variance prediction at ones.
  813. // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
  814. this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
  815. t1.stop();
  816. if (verboseTime)
  817. std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
  818. if ( this->verbose )
  819. std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
  820. t1.start();
  821. this->performOptimization ( *gplike, parameterVectorSize );
  822. t1.stop();
  823. if (verboseTime)
  824. std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
  825. if ( this->verbose )
  826. std::cerr << "Preparing classification ..." << std::endl;
  827. t1.start();
  828. this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
  829. t1.stop();
  830. if (verboseTime)
  831. std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
  832. t1.start();
  833. this->computeMatricesAndLUTs ( *gplike );
  834. t1.stop();
  835. if (verboseTime)
  836. std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
  837. t.stop();
  838. ResourceStatistics rs;
  839. std::cerr << "Time used for learning: " << t.getLast() << std::endl;
  840. long maxMemory;
  841. rs.getMaximumMemory ( maxMemory );
  842. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  843. //don't waste memory
  844. delete gplike;
  845. }
  846. void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
  847. {
  848. PrecomputedType AVar;
  849. fmk->hikPrepareKVNApproximation ( AVar );
  850. precomputedAForVarEst = AVar;
  851. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  852. if ( q != NULL )
  853. {
  854. double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
  855. this->precomputedTForVarEst = T;
  856. }
  857. }
  858. void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
  859. {
  860. if ( this->eigenMax.size() < (uint) this->nrOfEigenvaluesToConsiderForVarApprox )
  861. {
  862. std::cerr << "not enough eigenvectors computed for fine approximation of predictive variance. " <<std::endl;
  863. std::cerr << "Current number of EV: " << this->eigenMax.size() << " but required: " << (uint) this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  864. this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
  865. }
  866. }
  867. int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
  868. {
  869. // loop through all classes
  870. if ( precomputedA.size() == 0 )
  871. {
  872. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  873. }
  874. uint maxClassNo = 0;
  875. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  876. {
  877. uint classno = i->first;
  878. maxClassNo = std::max ( maxClassNo, classno );
  879. double beta;
  880. if ( q != NULL ) {
  881. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  882. double *T = j->second;
  883. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  884. } else {
  885. const PrecomputedType & A = i->second;
  886. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  887. const PrecomputedType & B = j->second;
  888. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  889. // Giving the transformation pf as an additional
  890. // argument is necessary due to the following reason:
  891. // FeatureMatrixT is sorted according to the original values, therefore,
  892. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  893. // values as inputs. However, for calculation we need the transformed features values.
  894. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  895. }
  896. scores[ classno ] = beta;
  897. }
  898. scores.setDim ( maxClassNo + 1 );
  899. if ( precomputedA.size() > 1 )
  900. { // multi-class classification
  901. return scores.maxElement();
  902. }
  903. else if ( this->knownClasses.size() == 2 ) // binary setting
  904. {
  905. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  906. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  907. }
  908. else //OCC or regression setting
  909. {
  910. return 1;
  911. }
  912. }
  913. int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
  914. {
  915. // loop through all classes
  916. if ( precomputedA.size() == 0 )
  917. {
  918. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  919. }
  920. uint maxClassNo = 0;
  921. for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
  922. {
  923. uint classno = i->first;
  924. maxClassNo = std::max ( maxClassNo, classno );
  925. double beta;
  926. if ( q != NULL ) {
  927. std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
  928. double *T = j->second;
  929. fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
  930. } else {
  931. const PrecomputedType & A = i->second;
  932. std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
  933. const PrecomputedType & B = j->second;
  934. // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
  935. // Giving the transformation pf as an additional
  936. // argument is necessary due to the following reason:
  937. // FeatureMatrixT is sorted according to the original values, therefore,
  938. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  939. // values as inputs. However, for calculation we need the transformed features values.
  940. fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
  941. }
  942. scores[ classno ] = beta;
  943. }
  944. scores.setDim ( maxClassNo + 1 );
  945. if ( precomputedA.size() > 1 )
  946. { // multi-class classification
  947. return scores.maxElement();
  948. }
  949. else if ( this->knownClasses.size() == 2 ) // binary setting
  950. {
  951. scores[binaryLabelNegative] = -scores[binaryLabelPositive];
  952. return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
  953. }
  954. else //OCC or regression setting
  955. {
  956. return 1;
  957. }
  958. }
  959. //////////////////////////////////////////
  960. // variance computation: sparse inputs
  961. //////////////////////////////////////////
  962. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
  963. {
  964. // security check!
  965. if ( pf == NULL )
  966. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  967. // ---------------- compute the first term --------------------
  968. double kSelf ( 0.0 );
  969. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  970. {
  971. kSelf += pf->f ( 0, it->second );
  972. // if weighted dimensions:
  973. //kSelf += pf->f(it->first,it->second);
  974. }
  975. // ---------------- compute the approximation of the second term --------------------
  976. double normKStar;
  977. if ( q != NULL )
  978. {
  979. if ( precomputedTForVarEst == NULL )
  980. {
  981. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  982. }
  983. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  984. }
  985. else
  986. {
  987. if ( precomputedAForVarEst.size () == 0 )
  988. {
  989. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  990. }
  991. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  992. }
  993. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  994. }
  995. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
  996. {
  997. // security check!
  998. if ( eigenMaxVectors.rows() == 0 )
  999. {
  1000. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1001. }
  1002. // ---------------- compute the first term --------------------
  1003. // Timer t;
  1004. // t.start();
  1005. double kSelf ( 0.0 );
  1006. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1007. {
  1008. kSelf += pf->f ( 0, it->second );
  1009. // if weighted dimensions:
  1010. //kSelf += pf->f(it->first,it->second);
  1011. }
  1012. // ---------------- compute the approximation of the second term --------------------
  1013. // t.stop();
  1014. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1015. // t.start();
  1016. NICE::Vector kStar;
  1017. fmk->hikComputeKernelVector ( x, kStar );
  1018. /* t.stop();
  1019. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1020. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1021. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1022. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1023. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1024. //wherefor it takes aeons...
  1025. //so we compute it by ourselves
  1026. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  1027. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  1028. // double kStarI ( kStar[tmpI] );
  1029. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1030. {
  1031. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1032. {
  1033. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1034. }
  1035. }
  1036. double projectionLength ( 0.0 );
  1037. double currentSecondTerm ( 0.0 );
  1038. double sumOfProjectionLengths ( 0.0 );
  1039. int cnt ( 0 );
  1040. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1041. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1042. {
  1043. projectionLength = ( *it );
  1044. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1045. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1046. it++;
  1047. cnt++;
  1048. }
  1049. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1050. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1051. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1052. {
  1053. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1054. }
  1055. predVariance = kSelf - currentSecondTerm;
  1056. }
  1057. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1058. {
  1059. // security check!
  1060. if ( ikmsum->getNumberOfModels() == 0 )
  1061. {
  1062. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1063. }
  1064. Timer t;
  1065. // t.start();
  1066. // ---------------- compute the first term --------------------
  1067. double kSelf ( 0.0 );
  1068. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1069. {
  1070. kSelf += pf->f ( 0, it->second );
  1071. // if weighted dimensions:
  1072. //kSelf += pf->f(it->first,it->second);
  1073. }
  1074. // ---------------- compute the second term --------------------
  1075. NICE::Vector kStar;
  1076. fmk->hikComputeKernelVector ( x, kStar );
  1077. //now run the ILS method
  1078. NICE::Vector diagonalElements;
  1079. ikmsum->getDiagonalElements ( diagonalElements );
  1080. // init simple jacobi pre-conditioning
  1081. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1082. //TODO what to do for other solver techniques?
  1083. //perform pre-conditioning
  1084. if ( linsolver_cg != NULL )
  1085. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1086. NICE::Vector beta;
  1087. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1088. * K~ = K + sigma^2 I
  1089. *
  1090. * K~ \approx lambda_max v v^T
  1091. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1092. * => \lambda_max v^T alpha = v^T k_*
  1093. * => alpha = k_* / lambda_max could be a good initial start
  1094. * If we put everything in the first equation this gives us
  1095. * v = k_*
  1096. * This reduces the number of iterations by 5 or 8
  1097. */
  1098. beta = (kStar * (1.0 / eigenMax[0]) );
  1099. linsolver->solveLin ( *ikmsum, kStar, beta );
  1100. beta *= kStar;
  1101. double currentSecondTerm( beta.Sum() );
  1102. predVariance = kSelf - currentSecondTerm;
  1103. }
  1104. //////////////////////////////////////////
  1105. // variance computation: non-sparse inputs
  1106. //////////////////////////////////////////
  1107. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1108. {
  1109. // security check!
  1110. if ( pf == NULL )
  1111. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1112. // ---------------- compute the first term --------------------
  1113. double kSelf ( 0.0 );
  1114. int dim ( 0 );
  1115. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1116. {
  1117. kSelf += pf->f ( 0, *it );
  1118. // if weighted dimensions:
  1119. //kSelf += pf->f(dim,*it);
  1120. }
  1121. // ---------------- compute the approximation of the second term --------------------
  1122. double normKStar;
  1123. if ( q != NULL )
  1124. {
  1125. if ( precomputedTForVarEst == NULL )
  1126. {
  1127. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1128. }
  1129. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
  1130. }
  1131. else
  1132. {
  1133. if ( precomputedAForVarEst.size () == 0 )
  1134. {
  1135. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1136. }
  1137. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
  1138. }
  1139. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1140. }
  1141. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
  1142. {
  1143. // security check!
  1144. if ( eigenMaxVectors.rows() == 0 )
  1145. {
  1146. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1147. }
  1148. // ---------------- compute the first term --------------------
  1149. double kSelf ( 0.0 );
  1150. int dim ( 0 );
  1151. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1152. {
  1153. kSelf += pf->f ( 0, *it );
  1154. // if weighted dimensions:
  1155. //kSelf += pf->f(dim,*it);
  1156. }
  1157. // ---------------- compute the approximation of the second term --------------------
  1158. NICE::Vector kStar;
  1159. fmk->hikComputeKernelVector ( x, kStar );
  1160. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1161. //wherefor it takes aeons...
  1162. //so we compute it by ourselves
  1163. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1164. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1165. NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1166. NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
  1167. for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1168. {
  1169. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1170. {
  1171. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1172. }
  1173. }
  1174. double projectionLength ( 0.0 );
  1175. double currentSecondTerm ( 0.0 );
  1176. double sumOfProjectionLengths ( 0.0 );
  1177. int cnt ( 0 );
  1178. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1179. while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1180. {
  1181. projectionLength = ( *it );
  1182. currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1183. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1184. it++;
  1185. cnt++;
  1186. }
  1187. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1188. currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1189. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1190. {
  1191. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1192. }
  1193. predVariance = kSelf - currentSecondTerm;
  1194. }
  1195. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & x, double & predVariance ) const
  1196. {
  1197. if ( ikmsum->getNumberOfModels() == 0 )
  1198. {
  1199. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1200. }
  1201. // ---------------- compute the first term --------------------
  1202. double kSelf ( 0.0 );
  1203. int dim ( 0 );
  1204. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1205. {
  1206. kSelf += pf->f ( 0, *it );
  1207. // if weighted dimensions:
  1208. //kSelf += pf->f(dim,*it);
  1209. }
  1210. // ---------------- compute the second term --------------------
  1211. NICE::Vector kStar;
  1212. fmk->hikComputeKernelVector ( x, kStar );
  1213. //now run the ILS method
  1214. NICE::Vector diagonalElements;
  1215. ikmsum->getDiagonalElements ( diagonalElements );
  1216. // init simple jacobi pre-conditioning
  1217. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1218. //perform pre-conditioning
  1219. if ( linsolver_cg != NULL )
  1220. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1221. NICE::Vector beta;
  1222. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1223. * K~ = K + sigma^2 I
  1224. *
  1225. * K~ \approx lambda_max v v^T
  1226. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1227. * => \lambda_max v^T alpha = v^T k_*
  1228. * => alpha = k_* / lambda_max could be a good initial start
  1229. * If we put everything in the first equation this gives us
  1230. * v = k_*
  1231. * This reduces the number of iterations by 5 or 8
  1232. */
  1233. beta = (kStar * (1.0 / eigenMax[0]) );
  1234. linsolver->solveLin ( *ikmsum, kStar, beta );
  1235. beta *= kStar;
  1236. double currentSecondTerm( beta.Sum() );
  1237. predVariance = kSelf - currentSecondTerm;
  1238. }
  1239. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1240. // interface specific methods for store and restore
  1241. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1242. void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
  1243. {
  1244. bool b_restoreVerbose ( false );
  1245. #ifdef B_RESTOREVERBOSE
  1246. b_restoreVerbose = true;
  1247. #endif
  1248. if ( is.good() )
  1249. {
  1250. if ( b_restoreVerbose )
  1251. std::cerr << " in FMKGP restore" << std::endl;
  1252. std::string tmp;
  1253. is >> tmp; //class name
  1254. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1255. {
  1256. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1257. throw;
  1258. }
  1259. if (fmk != NULL)
  1260. {
  1261. delete fmk;
  1262. fmk = NULL;
  1263. }
  1264. if ( ikmsum != NULL )
  1265. {
  1266. delete ikmsum;
  1267. }
  1268. ikmsum = new IKMLinearCombination ();
  1269. if ( b_restoreVerbose )
  1270. std::cerr << "ikmsum object created" << std::endl;
  1271. is.precision ( numeric_limits<double>::digits10 + 1 );
  1272. bool b_endOfBlock ( false ) ;
  1273. while ( !b_endOfBlock )
  1274. {
  1275. is >> tmp; // start of block
  1276. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1277. {
  1278. b_endOfBlock = true;
  1279. continue;
  1280. }
  1281. tmp = this->removeStartTag ( tmp );
  1282. if ( b_restoreVerbose )
  1283. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1284. ///////////////////////////////////
  1285. // output/debug related settings //
  1286. ///////////////////////////////////
  1287. if ( tmp.compare("verbose") == 0 )
  1288. {
  1289. is >> verbose;
  1290. is >> tmp; // end of block
  1291. tmp = this->removeEndTag ( tmp );
  1292. }
  1293. else if ( tmp.compare("verboseTime") == 0 )
  1294. {
  1295. is >> verboseTime;
  1296. is >> tmp; // end of block
  1297. tmp = this->removeEndTag ( tmp );
  1298. }
  1299. else if ( tmp.compare("debug") == 0 )
  1300. {
  1301. is >> debug;
  1302. is >> tmp; // end of block
  1303. tmp = this->removeEndTag ( tmp );
  1304. }
  1305. //////////////////////////////////////
  1306. // classification related variables //
  1307. //////////////////////////////////////
  1308. else if ( tmp.compare("b_performRegression") == 0 )
  1309. {
  1310. is >> b_performRegression;
  1311. is >> tmp; // end of block
  1312. tmp = this->removeEndTag ( tmp );
  1313. }
  1314. else if ( tmp.compare("fmk") == 0 )
  1315. {
  1316. if ( fmk != NULL )
  1317. delete fmk;
  1318. fmk = new FastMinKernel();
  1319. fmk->restore( is, format );
  1320. is >> tmp; // end of block
  1321. tmp = this->removeEndTag ( tmp );
  1322. }
  1323. else if ( tmp.compare("q") == 0 )
  1324. {
  1325. std::string isNull;
  1326. is >> isNull; // NOTNULL or NULL
  1327. if (isNull.compare("NOTNULL") == 0)
  1328. {
  1329. if ( q != NULL )
  1330. delete q;
  1331. q = new Quantization();
  1332. q->restore ( is, format );
  1333. }
  1334. else
  1335. {
  1336. if ( q != NULL )
  1337. delete q;
  1338. q = NULL;
  1339. }
  1340. is >> tmp; // end of block
  1341. tmp = this->removeEndTag ( tmp );
  1342. }
  1343. else if ( tmp.compare("parameterUpperBound") == 0 )
  1344. {
  1345. is >> parameterUpperBound;
  1346. is >> tmp; // end of block
  1347. tmp = this->removeEndTag ( tmp );
  1348. }
  1349. else if ( tmp.compare("parameterLowerBound") == 0 )
  1350. {
  1351. is >> parameterLowerBound;
  1352. is >> tmp; // end of block
  1353. tmp = this->removeEndTag ( tmp );
  1354. }
  1355. else if ( tmp.compare("pf") == 0 )
  1356. {
  1357. is >> tmp; // start of block
  1358. if ( this->isEndTag( tmp, "pf" ) )
  1359. {
  1360. std::cerr << " ParameterizedFunction object can not be restored. Aborting..." << std::endl;
  1361. throw;
  1362. }
  1363. std::string transform = this->removeStartTag ( tmp );
  1364. if ( transform == "PFAbsExp" )
  1365. {
  1366. this->pf = new PFAbsExp ();
  1367. } else if ( transform == "PFExp" ) {
  1368. this->pf = new PFExp ();
  1369. } else {
  1370. fthrow(Exception, "Transformation type is unknown " << transform);
  1371. }
  1372. pf->restore(is, format);
  1373. is >> tmp; // end of block
  1374. tmp = this->removeEndTag ( tmp );
  1375. }
  1376. else if ( tmp.compare("precomputedA") == 0 )
  1377. {
  1378. is >> tmp; // size
  1379. int preCompSize ( 0 );
  1380. is >> preCompSize;
  1381. precomputedA.clear();
  1382. if ( b_restoreVerbose )
  1383. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1384. for ( int i = 0; i < preCompSize; i++ )
  1385. {
  1386. int nr;
  1387. is >> nr;
  1388. PrecomputedType pct;
  1389. pct.setIoUntilEndOfFile ( false );
  1390. pct.restore ( is, format );
  1391. precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1392. }
  1393. is >> tmp; // end of block
  1394. tmp = this->removeEndTag ( tmp );
  1395. }
  1396. else if ( tmp.compare("precomputedB") == 0 )
  1397. {
  1398. is >> tmp; // size
  1399. int preCompSize ( 0 );
  1400. is >> preCompSize;
  1401. precomputedB.clear();
  1402. if ( b_restoreVerbose )
  1403. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1404. for ( int i = 0; i < preCompSize; i++ )
  1405. {
  1406. int nr;
  1407. is >> nr;
  1408. PrecomputedType pct;
  1409. pct.setIoUntilEndOfFile ( false );
  1410. pct.restore ( is, format );
  1411. precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
  1412. }
  1413. is >> tmp; // end of block
  1414. tmp = this->removeEndTag ( tmp );
  1415. }
  1416. else if ( tmp.compare("precomputedT") == 0 )
  1417. {
  1418. is >> tmp; // size
  1419. int precomputedTSize ( 0 );
  1420. is >> precomputedTSize;
  1421. precomputedT.clear();
  1422. if ( b_restoreVerbose )
  1423. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1424. if ( precomputedTSize > 0 )
  1425. {
  1426. if ( b_restoreVerbose )
  1427. std::cerr << " restore precomputedT" << std::endl;
  1428. is >> tmp;
  1429. int sizeOfLUT;
  1430. is >> sizeOfLUT;
  1431. for (int i = 0; i < precomputedTSize; i++)
  1432. {
  1433. is >> tmp;
  1434. int index;
  1435. is >> index;
  1436. double * array = new double [ sizeOfLUT];
  1437. for ( int i = 0; i < sizeOfLUT; i++ )
  1438. {
  1439. is >> array[i];
  1440. }
  1441. precomputedT.insert ( std::pair<int, double*> ( index, array ) );
  1442. }
  1443. }
  1444. else
  1445. {
  1446. if ( b_restoreVerbose )
  1447. std::cerr << " skip restoring precomputedT" << std::endl;
  1448. }
  1449. is >> tmp; // end of block
  1450. tmp = this->removeEndTag ( tmp );
  1451. }
  1452. else if ( tmp.compare("labels") == 0 )
  1453. {
  1454. is >> labels;
  1455. is >> tmp; // end of block
  1456. tmp = this->removeEndTag ( tmp );
  1457. }
  1458. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1459. {
  1460. is >> binaryLabelPositive;
  1461. is >> tmp; // end of block
  1462. tmp = this->removeEndTag ( tmp );
  1463. }
  1464. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1465. {
  1466. is >> binaryLabelNegative;
  1467. is >> tmp; // end of block
  1468. tmp = this->removeEndTag ( tmp );
  1469. }
  1470. else if ( tmp.compare("knownClasses") == 0 )
  1471. {
  1472. is >> tmp; // size
  1473. int knownClassesSize ( 0 );
  1474. is >> knownClassesSize;
  1475. knownClasses.clear();
  1476. if ( knownClassesSize > 0 )
  1477. {
  1478. for (int i = 0; i < knownClassesSize; i++)
  1479. {
  1480. int classNo;
  1481. is >> classNo;
  1482. knownClasses.insert ( classNo );
  1483. }
  1484. }
  1485. else
  1486. {
  1487. //nothing to do
  1488. }
  1489. is >> tmp; // end of block
  1490. tmp = this->removeEndTag ( tmp );
  1491. }
  1492. else if ( tmp.compare("ikmsum") == 0 )
  1493. {
  1494. bool b_endOfBlock ( false ) ;
  1495. while ( !b_endOfBlock )
  1496. {
  1497. is >> tmp; // start of block
  1498. if ( this->isEndTag( tmp, "ikmsum" ) )
  1499. {
  1500. b_endOfBlock = true;
  1501. continue;
  1502. }
  1503. tmp = this->removeStartTag ( tmp );
  1504. if ( tmp.compare("IKMNoise") == 0 )
  1505. {
  1506. IKMNoise * ikmnoise = new IKMNoise ();
  1507. ikmnoise->restore ( is, format );
  1508. if ( b_restoreVerbose )
  1509. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1510. ikmsum->addModel ( ikmnoise );
  1511. }
  1512. else
  1513. {
  1514. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1515. throw;
  1516. }
  1517. }
  1518. }
  1519. //////////////////////////////////////////////
  1520. // Iterative Linear Solver //
  1521. //////////////////////////////////////////////
  1522. else if ( tmp.compare("linsolver") == 0 )
  1523. {
  1524. //TODO linsolver
  1525. // current solution: hard coded with default values, since LinearSolver does not offer Persistent functionalities
  1526. this->linsolver = new ILSConjugateGradients ( false , 1000, 1e-7, 1e-7 );
  1527. is >> tmp; // end of block
  1528. tmp = this->removeEndTag ( tmp );
  1529. }
  1530. else if ( tmp.compare("ils_max_iterations") == 0 )
  1531. {
  1532. is >> ils_max_iterations;
  1533. is >> tmp; // end of block
  1534. tmp = this->removeEndTag ( tmp );
  1535. }
  1536. /////////////////////////////////////
  1537. // optimization related parameters //
  1538. /////////////////////////////////////
  1539. else if ( tmp.compare("optimizationMethod") == 0 )
  1540. {
  1541. unsigned int ui_optimizationMethod;
  1542. is >> ui_optimizationMethod;
  1543. optimizationMethod = static_cast<OPTIMIZATIONTECHNIQUE> ( ui_optimizationMethod ) ;
  1544. is >> tmp; // end of block
  1545. tmp = this->removeEndTag ( tmp );
  1546. }
  1547. else if ( tmp.compare("optimizeNoise") == 0 )
  1548. {
  1549. is >> optimizeNoise;
  1550. is >> tmp; // end of block
  1551. tmp = this->removeEndTag ( tmp );
  1552. }
  1553. else if ( tmp.compare("parameterStepSize") == 0 )
  1554. {
  1555. is >> parameterStepSize;
  1556. is >> tmp; // end of block
  1557. tmp = this->removeEndTag ( tmp );
  1558. }
  1559. else if ( tmp.compare("downhillSimplexMaxIterations") == 0 )
  1560. {
  1561. is >> downhillSimplexMaxIterations;
  1562. is >> tmp; // end of block
  1563. tmp = this->removeEndTag ( tmp );
  1564. }
  1565. else if ( tmp.compare("downhillSimplexTimeLimit") == 0 )
  1566. {
  1567. is >> downhillSimplexTimeLimit;
  1568. is >> tmp; // end of block
  1569. tmp = this->removeEndTag ( tmp );
  1570. }
  1571. else if ( tmp.compare("downhillSimplexParamTol") == 0 )
  1572. {
  1573. is >> downhillSimplexParamTol;
  1574. is >> tmp; // end of block
  1575. tmp = this->removeEndTag ( tmp );
  1576. }
  1577. //////////////////////////////////////////////
  1578. // likelihood computation related variables //
  1579. //////////////////////////////////////////////
  1580. else if ( tmp.compare("verifyApproximation") == 0 )
  1581. {
  1582. is >> verifyApproximation;
  1583. is >> tmp; // end of block
  1584. tmp = this->removeEndTag ( tmp );
  1585. }
  1586. else if ( tmp.compare("eig") == 0 )
  1587. {
  1588. //TODO eig
  1589. // currently hard coded, since EV does not offer Persistent functionalities and
  1590. // in addition, we currently have no other choice for EV then EVArnoldi
  1591. this->eig = new EVArnoldi ( false /*eig_verbose */, 10 );
  1592. is >> tmp; // end of block
  1593. tmp = this->removeEndTag ( tmp );
  1594. }
  1595. else if ( tmp.compare("nrOfEigenvaluesToConsider") == 0 )
  1596. {
  1597. is >> nrOfEigenvaluesToConsider;
  1598. is >> tmp; // end of block
  1599. tmp = this->removeEndTag ( tmp );
  1600. }
  1601. else if ( tmp.compare("eigenMax") == 0 )
  1602. {
  1603. is >> eigenMax;
  1604. is >> tmp; // end of block
  1605. tmp = this->removeEndTag ( tmp );
  1606. }
  1607. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1608. {
  1609. is >> eigenMaxVectors;
  1610. is >> tmp; // end of block
  1611. tmp = this->removeEndTag ( tmp );
  1612. }
  1613. ////////////////////////////////////////////
  1614. // variance computation related variables //
  1615. ////////////////////////////////////////////
  1616. else if ( tmp.compare("nrOfEigenvaluesToConsiderForVarApprox") == 0 )
  1617. {
  1618. is >> nrOfEigenvaluesToConsiderForVarApprox;
  1619. is >> tmp; // end of block
  1620. tmp = this->removeEndTag ( tmp );
  1621. }
  1622. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1623. {
  1624. int sizeOfAForVarEst;
  1625. is >> sizeOfAForVarEst;
  1626. if ( b_restoreVerbose )
  1627. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1628. if (sizeOfAForVarEst > 0)
  1629. {
  1630. precomputedAForVarEst.clear();
  1631. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1632. precomputedAForVarEst.restore ( is, format );
  1633. }
  1634. is >> tmp; // end of block
  1635. tmp = this->removeEndTag ( tmp );
  1636. }
  1637. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1638. {
  1639. std::string isNull;
  1640. is >> isNull; // NOTNULL or NULL
  1641. if ( b_restoreVerbose )
  1642. std::cerr << "content of isNull: " << isNull << std::endl;
  1643. if (isNull.compare("NOTNULL") == 0)
  1644. {
  1645. if ( b_restoreVerbose )
  1646. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1647. int sizeOfLUT;
  1648. is >> sizeOfLUT;
  1649. precomputedTForVarEst = new double [ sizeOfLUT ];
  1650. for ( int i = 0; i < sizeOfLUT; i++ )
  1651. {
  1652. is >> precomputedTForVarEst[i];
  1653. }
  1654. }
  1655. else
  1656. {
  1657. if ( b_restoreVerbose )
  1658. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1659. if (precomputedTForVarEst != NULL)
  1660. delete precomputedTForVarEst;
  1661. }
  1662. is >> tmp; // end of block
  1663. tmp = this->removeEndTag ( tmp );
  1664. }
  1665. /////////////////////////////////////////////////////
  1666. // online / incremental learning related variables //
  1667. /////////////////////////////////////////////////////
  1668. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1669. {
  1670. is >> b_usePreviousAlphas;
  1671. is >> tmp; // end of block
  1672. tmp = this->removeEndTag ( tmp );
  1673. }
  1674. else if ( tmp.compare("previousAlphas") == 0 )
  1675. {
  1676. is >> tmp; // size
  1677. int sizeOfPreviousAlphas ( 0 );
  1678. is >> sizeOfPreviousAlphas;
  1679. previousAlphas.clear();
  1680. if ( b_restoreVerbose )
  1681. std::cerr << "restore previousAlphas with size: " << sizeOfPreviousAlphas << std::endl;
  1682. for ( int i = 0; i < sizeOfPreviousAlphas; i++ )
  1683. {
  1684. int classNo;
  1685. is >> classNo;
  1686. NICE::Vector classAlpha;
  1687. is >> classAlpha;
  1688. previousAlphas.insert ( std::pair< int, NICE::Vector > ( classNo, classAlpha ) );
  1689. }
  1690. is >> tmp; // end of block
  1691. tmp = this->removeEndTag ( tmp );
  1692. }
  1693. else
  1694. {
  1695. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1696. throw;
  1697. }
  1698. }
  1699. //NOTE are there any more models you added? then add them here respectively in the correct order
  1700. //.....
  1701. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1702. if ( b_restoreVerbose )
  1703. std::cerr << " add GMHIKernel" << std::endl;
  1704. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1705. if ( b_restoreVerbose )
  1706. std::cerr << " restore positive and negative label" << std::endl;
  1707. knownClasses.clear();
  1708. if ( b_restoreVerbose )
  1709. std::cerr << " fill known classes object " << std::endl;
  1710. if ( precomputedA.size() == 1)
  1711. {
  1712. knownClasses.insert( binaryLabelPositive );
  1713. knownClasses.insert( binaryLabelNegative );
  1714. if ( b_restoreVerbose )
  1715. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1716. }
  1717. else
  1718. {
  1719. for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
  1720. knownClasses.insert ( itA->first );
  1721. if ( b_restoreVerbose )
  1722. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1723. }
  1724. }
  1725. else
  1726. {
  1727. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1728. throw;
  1729. }
  1730. }
  1731. void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
  1732. {
  1733. if ( os.good() )
  1734. {
  1735. // show starting point
  1736. os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1737. // os.precision ( numeric_limits<double>::digits10 + 1 );
  1738. ///////////////////////////////////
  1739. // output/debug related settings //
  1740. ///////////////////////////////////
  1741. os << this->createStartTag( "verbose" ) << std::endl;
  1742. os << verbose << std::endl;
  1743. os << this->createEndTag( "verbose" ) << std::endl;
  1744. os << this->createStartTag( "verboseTime" ) << std::endl;
  1745. os << verboseTime << std::endl;
  1746. os << this->createEndTag( "verboseTime" ) << std::endl;
  1747. os << this->createStartTag( "debug" ) << std::endl;
  1748. os << debug << std::endl;
  1749. os << this->createEndTag( "debug" ) << std::endl;
  1750. //////////////////////////////////////
  1751. // classification related variables //
  1752. //////////////////////////////////////
  1753. os << this->createStartTag( "b_performRegression" ) << std::endl;
  1754. os << b_performRegression << std::endl;
  1755. os << this->createEndTag( "b_performRegression" ) << std::endl;
  1756. os << this->createStartTag( "fmk" ) << std::endl;
  1757. fmk->store ( os, format );
  1758. os << this->createEndTag( "fmk" ) << std::endl;
  1759. os << this->createStartTag( "q" ) << std::endl;
  1760. if ( q != NULL )
  1761. {
  1762. os << "NOTNULL" << std::endl;
  1763. q->store ( os, format );
  1764. }
  1765. else
  1766. {
  1767. os << "NULL" << std::endl;
  1768. }
  1769. os << this->createEndTag( "q" ) << std::endl;
  1770. os << this->createStartTag( "parameterUpperBound" ) << std::endl;
  1771. os << parameterUpperBound << std::endl;
  1772. os << this->createEndTag( "parameterUpperBound" ) << std::endl;
  1773. os << this->createStartTag( "parameterLowerBound" ) << std::endl;
  1774. os << parameterLowerBound << std::endl;
  1775. os << this->createEndTag( "parameterLowerBound" ) << std::endl;
  1776. os << this->createStartTag( "pf" ) << std::endl;
  1777. pf->store(os, format);
  1778. os << this->createEndTag( "pf" ) << std::endl;
  1779. os << this->createStartTag( "precomputedA" ) << std::endl;
  1780. os << "size: " << precomputedA.size() << std::endl;
  1781. std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
  1782. for ( uint i = 0; i < precomputedA.size(); i++ )
  1783. {
  1784. os << preCompIt->first << std::endl;
  1785. ( preCompIt->second ).store ( os, format );
  1786. preCompIt++;
  1787. }
  1788. os << this->createEndTag( "precomputedA" ) << std::endl;
  1789. os << this->createStartTag( "precomputedB" ) << std::endl;
  1790. os << "size: " << precomputedB.size() << std::endl;
  1791. preCompIt = precomputedB.begin();
  1792. for ( uint i = 0; i < precomputedB.size(); i++ )
  1793. {
  1794. os << preCompIt->first << std::endl;
  1795. ( preCompIt->second ).store ( os, format );
  1796. preCompIt++;
  1797. }
  1798. os << this->createEndTag( "precomputedB" ) << std::endl;
  1799. os << this->createStartTag( "precomputedT" ) << std::endl;
  1800. os << "size: " << precomputedT.size() << std::endl;
  1801. if ( precomputedT.size() > 0 )
  1802. {
  1803. int sizeOfLUT ( 0 );
  1804. if ( q != NULL )
  1805. sizeOfLUT = q->size() * this->fmk->get_d();
  1806. os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1807. for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
  1808. {
  1809. os << "index: " << it->first << std::endl;
  1810. for ( int i = 0; i < sizeOfLUT; i++ )
  1811. {
  1812. os << ( it->second ) [i] << " ";
  1813. }
  1814. os << std::endl;
  1815. }
  1816. }
  1817. os << this->createEndTag( "precomputedT" ) << std::endl;
  1818. os << this->createStartTag( "labels" ) << std::endl;
  1819. os << labels << std::endl;
  1820. os << this->createEndTag( "labels" ) << std::endl;
  1821. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1822. os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1823. os << binaryLabelPositive << std::endl;
  1824. os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1825. os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1826. os << binaryLabelNegative << std::endl;
  1827. os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1828. os << this->createStartTag( "knownClasses" ) << std::endl;
  1829. os << "size: " << knownClasses.size() << std::endl;
  1830. for ( std::set< int >::const_iterator itKnownClasses = knownClasses.begin();
  1831. itKnownClasses != knownClasses.end();
  1832. itKnownClasses++
  1833. )
  1834. {
  1835. os << *itKnownClasses << " " << std::endl;
  1836. }
  1837. os << this->createEndTag( "knownClasses" ) << std::endl;
  1838. os << this->createStartTag( "ikmsum" ) << std::endl;
  1839. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1840. {
  1841. ( ikmsum->getModel ( j ) )->store ( os, format );
  1842. }
  1843. os << this->createEndTag( "ikmsum" ) << std::endl;
  1844. //////////////////////////////////////////////
  1845. // Iterative Linear Solver //
  1846. //////////////////////////////////////////////
  1847. os << this->createStartTag( "linsolver" ) << std::endl;
  1848. //TODO linsolver
  1849. os << this->createEndTag( "linsolver" ) << std::endl;
  1850. os << this->createStartTag( "ils_max_iterations" ) << std::endl;
  1851. os << ils_max_iterations << std::endl;
  1852. os << this->createEndTag( "ils_max_iterations" ) << std::endl;
  1853. /////////////////////////////////////
  1854. // optimization related parameters //
  1855. /////////////////////////////////////
  1856. os << this->createStartTag( "optimizationMethod" ) << std::endl;
  1857. os << optimizationMethod << std::endl;
  1858. os << this->createEndTag( "optimizationMethod" ) << std::endl;
  1859. os << this->createStartTag( "optimizeNoise" ) << std::endl;
  1860. os << optimizeNoise << std::endl;
  1861. os << this->createEndTag( "optimizeNoise" ) << std::endl;
  1862. os << this->createStartTag( "parameterStepSize" ) << std::endl;
  1863. os << parameterStepSize << std::endl;
  1864. os << this->createEndTag( "parameterStepSize" ) << std::endl;
  1865. os << this->createStartTag( "downhillSimplexMaxIterations" ) << std::endl;
  1866. os << downhillSimplexMaxIterations << std::endl;
  1867. os << this->createEndTag( "downhillSimplexMaxIterations" ) << std::endl;
  1868. os << this->createStartTag( "downhillSimplexTimeLimit" ) << std::endl;
  1869. os << downhillSimplexTimeLimit << std::endl;
  1870. os << this->createEndTag( "downhillSimplexTimeLimit" ) << std::endl;
  1871. os << this->createStartTag( "downhillSimplexParamTol" ) << std::endl;
  1872. os << downhillSimplexParamTol << std::endl;
  1873. os << this->createEndTag( "downhillSimplexParamTol" ) << std::endl;
  1874. //////////////////////////////////////////////
  1875. // likelihood computation related variables //
  1876. //////////////////////////////////////////////
  1877. os << this->createStartTag( "verifyApproximation" ) << std::endl;
  1878. os << verifyApproximation << std::endl;
  1879. os << this->createEndTag( "verifyApproximation" ) << std::endl;
  1880. os << this->createStartTag( "eig" ) << std::endl;
  1881. //TODO eig
  1882. os << this->createEndTag( "eig" ) << std::endl;
  1883. os << this->createStartTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  1884. os << nrOfEigenvaluesToConsider << std::endl;
  1885. os << this->createEndTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  1886. os << this->createStartTag( "eigenMax" ) << std::endl;
  1887. os << eigenMax << std::endl;
  1888. os << this->createEndTag( "eigenMax" ) << std::endl;
  1889. os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  1890. os << eigenMaxVectors << std::endl;
  1891. os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  1892. ////////////////////////////////////////////
  1893. // variance computation related variables //
  1894. ////////////////////////////////////////////
  1895. os << this->createStartTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  1896. os << nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1897. os << this->createEndTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  1898. os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  1899. os << precomputedAForVarEst.size() << std::endl;
  1900. if (precomputedAForVarEst.size() > 0)
  1901. {
  1902. precomputedAForVarEst.store ( os, format );
  1903. os << std::endl;
  1904. }
  1905. os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  1906. os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  1907. if ( precomputedTForVarEst != NULL )
  1908. {
  1909. os << "NOTNULL" << std::endl;
  1910. int sizeOfLUT ( 0 );
  1911. if ( q != NULL )
  1912. sizeOfLUT = q->size() * this->fmk->get_d();
  1913. os << sizeOfLUT << std::endl;
  1914. for ( int i = 0; i < sizeOfLUT; i++ )
  1915. {
  1916. os << precomputedTForVarEst[i] << " ";
  1917. }
  1918. os << std::endl;
  1919. }
  1920. else
  1921. {
  1922. os << "NULL" << std::endl;
  1923. }
  1924. os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  1925. /////////////////////////////////////////////////////
  1926. // online / incremental learning related variables //
  1927. /////////////////////////////////////////////////////
  1928. os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  1929. os << b_usePreviousAlphas << std::endl;
  1930. os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  1931. os << this->createStartTag( "previousAlphas" ) << std::endl;
  1932. os << "size: " << previousAlphas.size() << std::endl;
  1933. std::map< int, NICE::Vector >::const_iterator prevAlphaIt = previousAlphas.begin();
  1934. for ( uint i = 0; i < previousAlphas.size(); i++ )
  1935. {
  1936. os << prevAlphaIt->first << std::endl;
  1937. os << prevAlphaIt->second << std::endl;
  1938. prevAlphaIt++;
  1939. }
  1940. os << this->createEndTag( "previousAlphas" ) << std::endl;
  1941. // done
  1942. os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1943. }
  1944. else
  1945. {
  1946. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  1947. }
  1948. }
  1949. void FMKGPHyperparameterOptimization::clear ( ) {};
  1950. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1951. // interface specific methods for incremental extensions
  1952. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  1953. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  1954. const double & label,
  1955. const bool & performOptimizationAfterIncrement
  1956. )
  1957. {
  1958. if ( this->verbose )
  1959. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  1960. NICE::Timer t;
  1961. t.start();
  1962. std::set< int > newClasses;
  1963. this->labels.append ( label );
  1964. //have we seen this class already?
  1965. if ( !this->b_performRegression && ( this->knownClasses.find( label ) == this->knownClasses.end() ) )
  1966. {
  1967. this->knownClasses.insert( label );
  1968. newClasses.insert( label );
  1969. }
  1970. // If we currently have been in a binary setting, we now have to take care
  1971. // that we also compute an alpha vector for the second class, which previously
  1972. // could be dealt with implicitely.
  1973. // Therefore, we insert its label here...
  1974. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  1975. newClasses.insert( binaryLabelNegative );
  1976. // add the new example to our data structure
  1977. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  1978. NICE::Timer tFmk;
  1979. tFmk.start();
  1980. this->fmk->addExample ( example, pf );
  1981. tFmk.stop();
  1982. if ( this->verboseTime)
  1983. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  1984. // add examples to all implicite kernel matrices we currently use
  1985. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  1986. // update the corresponding matrices A, B and lookup tables T
  1987. // optional: do the optimization again using the previously known solutions as initialization
  1988. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  1989. //clean up
  1990. newClasses.clear();
  1991. t.stop();
  1992. NICE::ResourceStatistics rs;
  1993. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  1994. long maxMemory;
  1995. rs.getMaximumMemory ( maxMemory );
  1996. if ( this->verbose )
  1997. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  1998. if ( this->verbose )
  1999. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  2000. }
  2001. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  2002. const NICE::Vector & newLabels,
  2003. const bool & performOptimizationAfterIncrement
  2004. )
  2005. {
  2006. if ( this->verbose )
  2007. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples --- " << std::endl;
  2008. NICE::Timer t;
  2009. t.start();
  2010. std::set< int > newClasses;
  2011. this->labels.append ( newLabels );
  2012. //have we seen this class already?
  2013. if ( !this->b_performRegression)
  2014. {
  2015. for ( NICE::Vector::const_iterator vecIt = newLabels.begin();
  2016. vecIt != newLabels.end();
  2017. vecIt++
  2018. )
  2019. {
  2020. if ( this->knownClasses.find( *vecIt ) == this->knownClasses.end() )
  2021. {
  2022. this->knownClasses.insert( *vecIt );
  2023. newClasses.insert( *vecIt );
  2024. }
  2025. }
  2026. // If we currently have been in a OCC setting, and only add a single new class
  2027. // we have to take care that are still efficient, i.e., that we solve for alpha
  2028. // only ones, since scores are symmetric in binary cases
  2029. // Therefore, we remove the label of the secodn class from newClasses, to skip
  2030. // alpha computations for this class lateron...
  2031. //
  2032. // Therefore, we insert its label here...
  2033. if ( (newClasses.size() == 1 ) && ( (this->knownClasses.size() - newClasses.size() ) == 1 ) )
  2034. newClasses.clear();
  2035. // If we currently have been in a binary setting, we now have to take care
  2036. // that we also compute an alpha vector for the second class, which previously
  2037. // could be dealt with implicitely.
  2038. // Therefore, we insert its label here...
  2039. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2040. newClasses.insert( binaryLabelNegative );
  2041. }
  2042. // in a regression setting, we do not have to remember any "class labels"
  2043. else{}
  2044. // add the new example to our data structure
  2045. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2046. NICE::Timer tFmk;
  2047. tFmk.start();
  2048. this->fmk->addMultipleExamples ( newExamples, pf );
  2049. tFmk.stop();
  2050. if ( this->verboseTime)
  2051. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2052. // add examples to all implicite kernel matrices we currently use
  2053. this->ikmsum->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  2054. // update the corresponding matrices A, B and lookup tables T
  2055. // optional: do the optimization again using the previously known solutions as initialization
  2056. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2057. //clean up
  2058. newClasses.clear();
  2059. t.stop();
  2060. NICE::ResourceStatistics rs;
  2061. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2062. long maxMemory;
  2063. rs.getMaximumMemory ( maxMemory );
  2064. if ( this->verbose )
  2065. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2066. if ( this->verbose )
  2067. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples done --- " << std::endl;
  2068. }