FMKGPHyperparameterOptimization.cpp 92 KB

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