FMKGPHyperparameterOptimization.cpp 87 KB

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