FMKGPHyperparameterOptimization.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662
  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. uint maxClassNo = 0;
  930. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  931. {
  932. uint classno = i->first;
  933. maxClassNo = std::max ( maxClassNo, classno );
  934. double beta;
  935. if ( this->q != NULL ) {
  936. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  937. double *T = j->second;
  938. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  939. } else {
  940. const PrecomputedType & A = i->second;
  941. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  942. const PrecomputedType & B = j->second;
  943. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  944. // Giving the transformation pf as an additional
  945. // argument is necessary due to the following reason:
  946. // FeatureMatrixT is sorted according to the original values, therefore,
  947. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  948. // values as inputs. However, for calculation we need the transformed features values.
  949. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, pf );
  950. }
  951. _scores[ classno ] = beta;
  952. }
  953. _scores.setDim ( maxClassNo + 1 );
  954. if ( this->precomputedA.size() > 1 )
  955. { // multi-class classification
  956. return _scores.maxElement();
  957. }
  958. else if ( this->knownClasses.size() == 2 ) // binary setting
  959. {
  960. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  961. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  962. }
  963. else //OCC or regression setting
  964. {
  965. return 1;
  966. }
  967. }
  968. uint FMKGPHyperparameterOptimization::classify ( const NICE::Vector & _xstar,
  969. NICE::SparseVector & _scores
  970. ) const
  971. {
  972. // loop through all classes
  973. if ( this->precomputedA.size() == 0 )
  974. {
  975. fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
  976. }
  977. uint maxClassNo = 0;
  978. for ( std::map<uint, PrecomputedType>::const_iterator i = this->precomputedA.begin() ; i != this->precomputedA.end(); i++ )
  979. {
  980. uint classno = i->first;
  981. maxClassNo = std::max ( maxClassNo, classno );
  982. double beta;
  983. if ( this->q != NULL )
  984. {
  985. std::map<uint, double *>::const_iterator j = this->precomputedT.find ( classno );
  986. double *T = j->second;
  987. this->fmk->hik_kernel_sum_fast ( T, this->q, _xstar, beta );
  988. }
  989. else
  990. {
  991. const PrecomputedType & A = i->second;
  992. std::map<uint, PrecomputedType>::const_iterator j = this->precomputedB.find ( classno );
  993. const PrecomputedType & B = j->second;
  994. // fmk->hik_kernel_sum ( A, B, _xstar, beta ); if A, B are of type Matrix
  995. // Giving the transformation pf as an additional
  996. // argument is necessary due to the following reason:
  997. // FeatureMatrixT is sorted according to the original values, therefore,
  998. // searching for upper and lower bounds ( findFirst... functions ) require original feature
  999. // values as inputs. However, for calculation we need the transformed features values.
  1000. this->fmk->hik_kernel_sum ( A, B, _xstar, beta, this->pf );
  1001. }
  1002. _scores[ classno ] = beta;
  1003. }
  1004. _scores.setDim ( maxClassNo + 1 );
  1005. if ( this->precomputedA.size() > 1 )
  1006. { // multi-class classification
  1007. return _scores.maxElement();
  1008. }
  1009. else if ( this->knownClasses.size() == 2 ) // binary setting
  1010. {
  1011. _scores[ this->i_binaryLabelNegative ] = -_scores[ this->i_binaryLabelPositive ];
  1012. return _scores[ this->i_binaryLabelPositive ] <= 0.0 ? this->i_binaryLabelNegative : this->i_binaryLabelPositive;
  1013. }
  1014. else //OCC or regression setting
  1015. {
  1016. return 1;
  1017. }
  1018. }
  1019. //////////////////////////////////////////
  1020. // variance computation: sparse inputs
  1021. //////////////////////////////////////////
  1022. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & _x,
  1023. double & _predVariance
  1024. ) const
  1025. {
  1026. // security check!
  1027. if ( this->pf == NULL )
  1028. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1029. // ---------------- compute the first term --------------------
  1030. double kSelf ( 0.0 );
  1031. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1032. {
  1033. kSelf += this->pf->f ( 0, it->second );
  1034. // if weighted dimensions:
  1035. //kSelf += pf->f(it->first,it->second);
  1036. }
  1037. // ---------------- compute the approximation of the second term --------------------
  1038. double normKStar;
  1039. if ( this->q != NULL )
  1040. {
  1041. if ( precomputedTForVarEst == NULL )
  1042. {
  1043. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1044. }
  1045. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, _x, normKStar );
  1046. }
  1047. else
  1048. {
  1049. if ( precomputedAForVarEst.size () == 0 )
  1050. {
  1051. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1052. }
  1053. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, _x, normKStar, pf );
  1054. }
  1055. _predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1056. }
  1057. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & _x,
  1058. double & _predVariance
  1059. ) const
  1060. {
  1061. if ( this->b_debug )
  1062. {
  1063. std::cerr << "FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine" << std::endl;
  1064. }
  1065. // security check!
  1066. if ( this->eigenMaxVectors.rows() == 0 )
  1067. {
  1068. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1069. }
  1070. // ---------------- compute the first term --------------------
  1071. // Timer t;
  1072. // t.start();
  1073. double kSelf ( 0.0 );
  1074. for ( NICE::SparseVector::const_iterator it = _x.begin(); it != _x.end(); it++ )
  1075. {
  1076. kSelf += this->pf->f ( 0, it->second );
  1077. // if weighted dimensions:
  1078. //kSelf += pf->f(it->first,it->second);
  1079. }
  1080. if ( this->b_debug )
  1081. {
  1082. std::cerr << "FMKGPHyp::VarApproxFine -- kSelf: " << kSelf << std::endl;
  1083. }
  1084. // ---------------- compute the approximation of the second term --------------------
  1085. // t.stop();
  1086. // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
  1087. // t.start();
  1088. NICE::Vector kStar;
  1089. this->fmk->hikComputeKernelVector ( _x, kStar );
  1090. if ( this->b_debug )
  1091. {
  1092. std::cerr << "FMKGPHyp::VarApproxFine -- kStar: " << kStar << std::endl;
  1093. std::cerr << "nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1094. }
  1095. /* t.stop();
  1096. std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
  1097. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1098. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1099. NICE::Vector multiplicationResults( this->nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1100. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1101. //wherefor it takes aeons...
  1102. //so we compute it by ourselves
  1103. if ( this->b_debug )
  1104. {
  1105. std::cerr << "FMKGPHyp::VarApproxFine -- nrOfEigenvaluesToConsiderForVarApprox: " << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  1106. std::cerr << "FMKGPHyp::VarApproxFine -- initial multiplicationResults: " << multiplicationResults << std::endl;
  1107. }
  1108. // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
  1109. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1110. // double kStarI ( kStar[tmpI] );
  1111. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1112. {
  1113. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1114. {
  1115. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1116. }
  1117. }
  1118. if ( this->b_debug )
  1119. {
  1120. std::cerr << "FMKGPHyp::VarApproxFine -- computed multiplicationResults: " << multiplicationResults << std::endl;
  1121. }
  1122. double projectionLength ( 0.0 );
  1123. double currentSecondTerm ( 0.0 );
  1124. double sumOfProjectionLengths ( 0.0 );
  1125. int cnt ( 0 );
  1126. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1127. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1128. {
  1129. projectionLength = ( *it );
  1130. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1131. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1132. it++;
  1133. cnt++;
  1134. }
  1135. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1136. currentSecondTerm += ( 1.0 / this->eigenMax[this->nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1137. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1138. {
  1139. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1140. }
  1141. _predVariance = kSelf - currentSecondTerm;
  1142. }
  1143. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
  1144. {
  1145. // security check!
  1146. if ( this->ikmsum->getNumberOfModels() == 0 )
  1147. {
  1148. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1149. }
  1150. Timer t;
  1151. // t.start();
  1152. // ---------------- compute the first term --------------------
  1153. double kSelf ( 0.0 );
  1154. for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
  1155. {
  1156. kSelf += this->pf->f ( 0, it->second );
  1157. // if weighted dimensions:
  1158. //kSelf += pf->f(it->first,it->second);
  1159. }
  1160. // ---------------- compute the second term --------------------
  1161. NICE::Vector kStar;
  1162. fmk->hikComputeKernelVector ( x, kStar );
  1163. //now run the ILS method
  1164. NICE::Vector diagonalElements;
  1165. ikmsum->getDiagonalElements ( diagonalElements );
  1166. // init simple jacobi pre-conditioning
  1167. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
  1168. //TODO what to do for other solver techniques?
  1169. //perform pre-conditioning
  1170. if ( linsolver_cg != NULL )
  1171. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1172. NICE::Vector beta;
  1173. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1174. * K~ = K + sigma^2 I
  1175. *
  1176. * K~ \approx lambda_max v v^T
  1177. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1178. * => \lambda_max v^T alpha = v^T k_*
  1179. * => alpha = k_* / lambda_max could be a good initial start
  1180. * If we put everything in the first equation this gives us
  1181. * v = k_*
  1182. * This reduces the number of iterations by 5 or 8
  1183. */
  1184. beta = (kStar * (1.0 / eigenMax[0]) );
  1185. linsolver->solveLin ( *ikmsum, kStar, beta );
  1186. beta *= kStar;
  1187. double currentSecondTerm( beta.Sum() );
  1188. predVariance = kSelf - currentSecondTerm;
  1189. }
  1190. //////////////////////////////////////////
  1191. // variance computation: non-sparse inputs
  1192. //////////////////////////////////////////
  1193. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
  1194. {
  1195. // security check!
  1196. if ( pf == NULL )
  1197. fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1198. // ---------------- compute the first term --------------------
  1199. double kSelf ( 0.0 );
  1200. int dim ( 0 );
  1201. for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
  1202. {
  1203. kSelf += pf->f ( 0, *it );
  1204. // if weighted dimensions:
  1205. //kSelf += pf->f(dim,*it);
  1206. }
  1207. // ---------------- compute the approximation of the second term --------------------
  1208. double normKStar;
  1209. if ( this->q != NULL )
  1210. {
  1211. if ( precomputedTForVarEst == NULL )
  1212. {
  1213. fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
  1214. }
  1215. fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, this->q, x, normKStar );
  1216. }
  1217. else
  1218. {
  1219. if ( precomputedAForVarEst.size () == 0 )
  1220. {
  1221. fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
  1222. }
  1223. fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, this->pf );
  1224. }
  1225. predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
  1226. }
  1227. void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & _x,
  1228. double & _predVariance
  1229. ) const
  1230. {
  1231. // security check!
  1232. if ( this->eigenMaxVectors.rows() == 0 )
  1233. {
  1234. fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
  1235. }
  1236. // ---------------- compute the first term --------------------
  1237. double kSelf ( 0.0 );
  1238. uint dim ( 0 );
  1239. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1240. {
  1241. kSelf += this->pf->f ( 0, *it );
  1242. // if weighted dimensions:
  1243. //kSelf += pf->f(dim,*it);
  1244. }
  1245. // ---------------- compute the approximation of the second term --------------------
  1246. NICE::Vector kStar;
  1247. this->fmk->hikComputeKernelVector ( _x, kStar );
  1248. //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1249. //wherefor it takes aeons...
  1250. //so we compute it by ourselves
  1251. // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
  1252. // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
  1253. NICE::Vector multiplicationResults(this-> nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
  1254. NICE::Matrix::const_iterator eigenVecIt = this->eigenMaxVectors.begin();
  1255. for ( int tmpJ = 0; tmpJ < this->nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
  1256. {
  1257. for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
  1258. {
  1259. multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
  1260. }
  1261. }
  1262. double projectionLength ( 0.0 );
  1263. double currentSecondTerm ( 0.0 );
  1264. double sumOfProjectionLengths ( 0.0 );
  1265. int cnt ( 0 );
  1266. NICE::Vector::const_iterator it = multiplicationResults.begin();
  1267. while ( cnt < ( this->nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
  1268. {
  1269. projectionLength = ( *it );
  1270. currentSecondTerm += ( 1.0 / this->eigenMax[cnt] ) * pow ( projectionLength, 2 );
  1271. sumOfProjectionLengths += pow ( projectionLength, 2 );
  1272. it++;
  1273. cnt++;
  1274. }
  1275. double normKStar ( pow ( kStar.normL2 (), 2 ) );
  1276. currentSecondTerm += ( 1.0 / this->eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
  1277. if ( ( normKStar - sumOfProjectionLengths ) < 0 )
  1278. {
  1279. std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
  1280. }
  1281. _predVariance = kSelf - currentSecondTerm;
  1282. }
  1283. void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & _x,
  1284. double & _predVariance
  1285. ) const
  1286. {
  1287. if ( this->ikmsum->getNumberOfModels() == 0 )
  1288. {
  1289. fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
  1290. }
  1291. // ---------------- compute the first term --------------------
  1292. double kSelf ( 0.0 );
  1293. uint dim ( 0 );
  1294. for ( NICE::Vector::const_iterator it = _x.begin(); it != _x.end(); it++, dim++ )
  1295. {
  1296. kSelf += this->pf->f ( 0, *it );
  1297. // if weighted dimensions:
  1298. //kSelf += pf->f(dim,*it);
  1299. }
  1300. // ---------------- compute the second term --------------------
  1301. NICE::Vector kStar;
  1302. this->fmk->hikComputeKernelVector ( _x, kStar );
  1303. //now run the ILS method
  1304. NICE::Vector diagonalElements;
  1305. this->ikmsum->getDiagonalElements ( diagonalElements );
  1306. // init simple jacobi pre-conditioning
  1307. ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( this->linsolver );
  1308. //perform pre-conditioning
  1309. if ( linsolver_cg != NULL )
  1310. linsolver_cg->setJacobiPreconditioner ( diagonalElements );
  1311. NICE::Vector beta;
  1312. /** About finding a good initial solution (see also GPLikelihoodApproximation)
  1313. * K~ = K + sigma^2 I
  1314. *
  1315. * K~ \approx lambda_max v v^T
  1316. * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
  1317. * => \lambda_max v^T alpha = v^T k_*
  1318. * => alpha = k_* / lambda_max could be a good initial start
  1319. * If we put everything in the first equation this gives us
  1320. * v = k_*
  1321. * This reduces the number of iterations by 5 or 8
  1322. */
  1323. beta = (kStar * (1.0 / this->eigenMax[0]) );
  1324. this->linsolver->solveLin ( *ikmsum, kStar, beta );
  1325. beta *= kStar;
  1326. double currentSecondTerm( beta.Sum() );
  1327. _predVariance = kSelf - currentSecondTerm;
  1328. }
  1329. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1330. // interface specific methods for store and restore
  1331. ///////////////////// INTERFACE PERSISTENT /////////////////////
  1332. void FMKGPHyperparameterOptimization::restore ( std::istream & _is,
  1333. int _format
  1334. )
  1335. {
  1336. bool b_restoreVerbose ( false );
  1337. #ifdef B_RESTOREVERBOSE
  1338. b_restoreVerbose = true;
  1339. #endif
  1340. if ( _is.good() )
  1341. {
  1342. if ( b_restoreVerbose )
  1343. std::cerr << " in FMKGPHyperparameterOptimization restore" << std::endl;
  1344. std::string tmp;
  1345. _is >> tmp; //class name
  1346. if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1347. {
  1348. std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
  1349. throw;
  1350. }
  1351. if (fmk != NULL)
  1352. {
  1353. delete fmk;
  1354. fmk = NULL;
  1355. }
  1356. if ( ikmsum != NULL )
  1357. {
  1358. delete ikmsum;
  1359. }
  1360. ikmsum = new IKMLinearCombination ();
  1361. if ( b_restoreVerbose )
  1362. std::cerr << "ikmsum object created" << std::endl;
  1363. _is.precision ( numeric_limits<double>::digits10 + 1 );
  1364. bool b_endOfBlock ( false ) ;
  1365. while ( !b_endOfBlock )
  1366. {
  1367. _is >> tmp; // start of block
  1368. if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
  1369. {
  1370. b_endOfBlock = true;
  1371. continue;
  1372. }
  1373. tmp = this->removeStartTag ( tmp );
  1374. if ( b_restoreVerbose )
  1375. std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
  1376. ///////////////////////////////////
  1377. // output/debug related settings //
  1378. ///////////////////////////////////
  1379. if ( tmp.compare("verbose") == 0 )
  1380. {
  1381. _is >> this->b_verbose;
  1382. _is >> tmp; // end of block
  1383. tmp = this->removeEndTag ( tmp );
  1384. }
  1385. else if ( tmp.compare("verboseTime") == 0 )
  1386. {
  1387. _is >> this->b_verboseTime;
  1388. _is >> tmp; // end of block
  1389. tmp = this->removeEndTag ( tmp );
  1390. }
  1391. else if ( tmp.compare("debug") == 0 )
  1392. {
  1393. _is >> this->b_debug;
  1394. _is >> tmp; // end of block
  1395. tmp = this->removeEndTag ( tmp );
  1396. }
  1397. //////////////////////////////////////
  1398. // classification related variables //
  1399. //////////////////////////////////////
  1400. else if ( tmp.compare("b_performRegression") == 0 )
  1401. {
  1402. _is >> this->b_performRegression;
  1403. _is >> tmp; // end of block
  1404. tmp = this->removeEndTag ( tmp );
  1405. }
  1406. else if ( tmp.compare("fmk") == 0 )
  1407. {
  1408. if ( this->fmk != NULL )
  1409. delete this->fmk;
  1410. this->fmk = new FastMinKernel();
  1411. this->fmk->restore( _is, _format );
  1412. _is >> tmp; // end of block
  1413. tmp = this->removeEndTag ( tmp );
  1414. }
  1415. else if ( tmp.compare("q") == 0 )
  1416. {
  1417. std::string isNull;
  1418. _is >> isNull; // NOTNULL or NULL
  1419. if (isNull.compare("NOTNULL") == 0)
  1420. {
  1421. if ( this->q != NULL )
  1422. delete this->q;
  1423. std::string s_quantType;
  1424. _is >> s_quantType;
  1425. s_quantType = this->removeStartTag ( s_quantType );
  1426. if ( s_quantType == "Quantization1DAequiDist0To1" )
  1427. {
  1428. this->q = new NICE::Quantization1DAequiDist0To1();
  1429. }
  1430. else if ( s_quantType == "Quantization1DAequiDist0ToMax" )
  1431. {
  1432. this->q = new NICE::Quantization1DAequiDist0ToMax ( );
  1433. }
  1434. else if ( s_quantType == "QuantizationNDAequiDist0ToMax" )
  1435. {
  1436. this->q = new NICE::QuantizationNDAequiDist0ToMax ( );
  1437. }
  1438. else
  1439. {
  1440. fthrow(Exception, "Quantization type is unknown " << s_quantType);
  1441. }
  1442. this->q->restore ( _is, _format );
  1443. }
  1444. else
  1445. {
  1446. if ( this->q != NULL )
  1447. delete this->q;
  1448. this->q = NULL;
  1449. }
  1450. _is >> tmp; // end of block
  1451. tmp = this->removeEndTag ( tmp );
  1452. }
  1453. else if ( tmp.compare("parameterUpperBound") == 0 )
  1454. {
  1455. _is >> this->d_parameterUpperBound;
  1456. _is >> tmp; // end of block
  1457. tmp = this->removeEndTag ( tmp );
  1458. }
  1459. else if ( tmp.compare("parameterLowerBound") == 0 )
  1460. {
  1461. _is >> this->d_parameterLowerBound;
  1462. _is >> tmp; // end of block
  1463. tmp = this->removeEndTag ( tmp );
  1464. }
  1465. else if ( tmp.compare("pf") == 0 )
  1466. {
  1467. _is >> tmp; // start of block
  1468. if ( this->isEndTag( tmp, "pf" ) )
  1469. {
  1470. std::cerr << " ParameterizedFunction object can not be restored. Aborting..." << std::endl;
  1471. throw;
  1472. }
  1473. std::string transform ( this->removeStartTag( tmp ) );
  1474. if ( transform == "PFAbsExp" )
  1475. {
  1476. this->pf = new NICE::PFAbsExp ();
  1477. } else if ( transform == "PFExp" ) {
  1478. this->pf = new NICE::PFExp ();
  1479. }
  1480. else if ( transform == "PFIdentity" )
  1481. {
  1482. this->pf = new NICE::PFIdentity( );
  1483. } else {
  1484. fthrow(Exception, "Transformation type is unknown " << transform);
  1485. }
  1486. this->pf->restore( _is, _format);
  1487. _is >> tmp; // end of block
  1488. tmp = this->removeEndTag ( tmp );
  1489. }
  1490. else if ( tmp.compare("precomputedA") == 0 )
  1491. {
  1492. _is >> tmp; // size
  1493. uint preCompSize ( 0 );
  1494. _is >> preCompSize;
  1495. this->precomputedA.clear();
  1496. if ( b_restoreVerbose )
  1497. std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
  1498. for ( int i = 0; i < preCompSize; i++ )
  1499. {
  1500. uint nr;
  1501. _is >> nr;
  1502. PrecomputedType pct;
  1503. pct.setIoUntilEndOfFile ( false );
  1504. pct.restore ( _is, _format );
  1505. this->precomputedA.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1506. }
  1507. _is >> tmp; // end of block
  1508. tmp = this->removeEndTag ( tmp );
  1509. }
  1510. else if ( tmp.compare("precomputedB") == 0 )
  1511. {
  1512. _is >> tmp; // size
  1513. uint preCompSize ( 0 );
  1514. _is >> preCompSize;
  1515. this->precomputedB.clear();
  1516. if ( b_restoreVerbose )
  1517. std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
  1518. for ( int i = 0; i < preCompSize; i++ )
  1519. {
  1520. uint nr;
  1521. _is >> nr;
  1522. PrecomputedType pct;
  1523. pct.setIoUntilEndOfFile ( false );
  1524. pct.restore ( _is, _format );
  1525. this->precomputedB.insert ( std::pair<uint, PrecomputedType> ( nr, pct ) );
  1526. }
  1527. _is >> tmp; // end of block
  1528. tmp = this->removeEndTag ( tmp );
  1529. }
  1530. else if ( tmp.compare("precomputedT") == 0 )
  1531. {
  1532. _is >> tmp; // size
  1533. uint precomputedTSize ( 0 );
  1534. _is >> precomputedTSize;
  1535. this->precomputedT.clear();
  1536. if ( b_restoreVerbose )
  1537. std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
  1538. if ( precomputedTSize > 0 )
  1539. {
  1540. if ( b_restoreVerbose )
  1541. std::cerr << " restore precomputedT" << std::endl;
  1542. _is >> tmp;
  1543. int sizeOfLUT;
  1544. _is >> sizeOfLUT;
  1545. for (int i = 0; i < precomputedTSize; i++)
  1546. {
  1547. _is >> tmp;
  1548. uint index;
  1549. _is >> index;
  1550. double * array = new double [ sizeOfLUT];
  1551. for ( int i = 0; i < sizeOfLUT; i++ )
  1552. {
  1553. _is >> array[i];
  1554. }
  1555. this->precomputedT.insert ( std::pair<uint, double*> ( index, array ) );
  1556. }
  1557. }
  1558. else
  1559. {
  1560. if ( b_restoreVerbose )
  1561. std::cerr << " skip restoring precomputedT" << std::endl;
  1562. }
  1563. _is >> tmp; // end of block
  1564. tmp = this->removeEndTag ( tmp );
  1565. }
  1566. else if ( tmp.compare("labels") == 0 )
  1567. {
  1568. _is >> this->labels;
  1569. _is >> tmp; // end of block
  1570. tmp = this->removeEndTag ( tmp );
  1571. }
  1572. else if ( tmp.compare("binaryLabelPositive") == 0 )
  1573. {
  1574. _is >> this->i_binaryLabelPositive;
  1575. _is >> tmp; // end of block
  1576. tmp = this->removeEndTag ( tmp );
  1577. }
  1578. else if ( tmp.compare("binaryLabelNegative") == 0 )
  1579. {
  1580. _is >> this->i_binaryLabelNegative;
  1581. _is >> tmp; // end of block
  1582. tmp = this->removeEndTag ( tmp );
  1583. }
  1584. else if ( tmp.compare("knownClasses") == 0 )
  1585. {
  1586. _is >> tmp; // size
  1587. uint knownClassesSize ( 0 );
  1588. _is >> knownClassesSize;
  1589. this->knownClasses.clear();
  1590. if ( knownClassesSize > 0 )
  1591. {
  1592. for (uint i = 0; i < knownClassesSize; i++)
  1593. {
  1594. uint classNo;
  1595. _is >> classNo;
  1596. this->knownClasses.insert ( classNo );
  1597. }
  1598. }
  1599. else
  1600. {
  1601. //nothing to do
  1602. }
  1603. _is >> tmp; // end of block
  1604. tmp = this->removeEndTag ( tmp );
  1605. }
  1606. else if ( tmp.compare("ikmsum") == 0 )
  1607. {
  1608. bool b_endOfBlock ( false ) ;
  1609. while ( !b_endOfBlock )
  1610. {
  1611. _is >> tmp; // start of block
  1612. if ( this->isEndTag( tmp, "ikmsum" ) )
  1613. {
  1614. b_endOfBlock = true;
  1615. continue;
  1616. }
  1617. tmp = this->removeStartTag ( tmp );
  1618. if ( tmp.compare("IKMNoise") == 0 )
  1619. {
  1620. IKMNoise * ikmnoise = new IKMNoise ();
  1621. ikmnoise->restore ( _is, _format );
  1622. if ( b_restoreVerbose )
  1623. std::cerr << " add ikmnoise to ikmsum object " << std::endl;
  1624. ikmsum->addModel ( ikmnoise );
  1625. }
  1626. else
  1627. {
  1628. std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1629. throw;
  1630. }
  1631. }
  1632. }
  1633. //////////////////////////////////////////////
  1634. // Iterative Linear Solver //
  1635. //////////////////////////////////////////////
  1636. else if ( tmp.compare("linsolver") == 0 )
  1637. {
  1638. //TODO linsolver
  1639. // current solution: hard coded with default values, since LinearSolver does not offer Persistent functionalities
  1640. this->linsolver = new ILSConjugateGradients ( false , 1000, 1e-7, 1e-7 );
  1641. _is >> tmp; // end of block
  1642. tmp = this->removeEndTag ( tmp );
  1643. }
  1644. else if ( tmp.compare("ils_max_iterations") == 0 )
  1645. {
  1646. _is >> ils_max_iterations;
  1647. _is >> tmp; // end of block
  1648. tmp = this->removeEndTag ( tmp );
  1649. }
  1650. /////////////////////////////////////
  1651. // optimization related parameters //
  1652. /////////////////////////////////////
  1653. else if ( tmp.compare("optimizationMethod") == 0 )
  1654. {
  1655. unsigned int ui_optimizationMethod;
  1656. _is >> ui_optimizationMethod;
  1657. optimizationMethod = static_cast<OPTIMIZATIONTECHNIQUE> ( ui_optimizationMethod ) ;
  1658. _is >> tmp; // end of block
  1659. tmp = this->removeEndTag ( tmp );
  1660. }
  1661. else if ( tmp.compare("optimizeNoise") == 0 )
  1662. {
  1663. _is >> optimizeNoise;
  1664. _is >> tmp; // end of block
  1665. tmp = this->removeEndTag ( tmp );
  1666. }
  1667. else if ( tmp.compare("parameterStepSize") == 0 )
  1668. {
  1669. _is >> parameterStepSize;
  1670. _is >> tmp; // end of block
  1671. tmp = this->removeEndTag ( tmp );
  1672. }
  1673. else if ( tmp.compare("downhillSimplexMaxIterations") == 0 )
  1674. {
  1675. _is >> downhillSimplexMaxIterations;
  1676. _is >> tmp; // end of block
  1677. tmp = this->removeEndTag ( tmp );
  1678. }
  1679. else if ( tmp.compare("downhillSimplexTimeLimit") == 0 )
  1680. {
  1681. _is >> downhillSimplexTimeLimit;
  1682. _is >> tmp; // end of block
  1683. tmp = this->removeEndTag ( tmp );
  1684. }
  1685. else if ( tmp.compare("downhillSimplexParamTol") == 0 )
  1686. {
  1687. _is >> downhillSimplexParamTol;
  1688. _is >> tmp; // end of block
  1689. tmp = this->removeEndTag ( tmp );
  1690. }
  1691. //////////////////////////////////////////////
  1692. // likelihood computation related variables //
  1693. //////////////////////////////////////////////
  1694. else if ( tmp.compare("verifyApproximation") == 0 )
  1695. {
  1696. _is >> verifyApproximation;
  1697. _is >> tmp; // end of block
  1698. tmp = this->removeEndTag ( tmp );
  1699. }
  1700. else if ( tmp.compare("eig") == 0 )
  1701. {
  1702. //TODO eig
  1703. // currently hard coded, since EV does not offer Persistent functionalities and
  1704. // in addition, we currently have no other choice for EV then EVArnoldi
  1705. this->eig = new EVArnoldi ( false /*eig_verbose */, 10 );
  1706. _is >> tmp; // end of block
  1707. tmp = this->removeEndTag ( tmp );
  1708. }
  1709. else if ( tmp.compare("nrOfEigenvaluesToConsider") == 0 )
  1710. {
  1711. _is >> nrOfEigenvaluesToConsider;
  1712. _is >> tmp; // end of block
  1713. tmp = this->removeEndTag ( tmp );
  1714. }
  1715. else if ( tmp.compare("eigenMax") == 0 )
  1716. {
  1717. _is >> eigenMax;
  1718. _is >> tmp; // end of block
  1719. tmp = this->removeEndTag ( tmp );
  1720. }
  1721. else if ( tmp.compare("eigenMaxVectors") == 0 )
  1722. {
  1723. _is >> eigenMaxVectors;
  1724. _is >> tmp; // end of block
  1725. tmp = this->removeEndTag ( tmp );
  1726. }
  1727. ////////////////////////////////////////////
  1728. // variance computation related variables //
  1729. ////////////////////////////////////////////
  1730. else if ( tmp.compare("nrOfEigenvaluesToConsiderForVarApprox") == 0 )
  1731. {
  1732. _is >> nrOfEigenvaluesToConsiderForVarApprox;
  1733. _is >> tmp; // end of block
  1734. tmp = this->removeEndTag ( tmp );
  1735. }
  1736. else if ( tmp.compare("precomputedAForVarEst") == 0 )
  1737. {
  1738. int sizeOfAForVarEst;
  1739. _is >> sizeOfAForVarEst;
  1740. if ( b_restoreVerbose )
  1741. std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
  1742. if (sizeOfAForVarEst > 0)
  1743. {
  1744. precomputedAForVarEst.clear();
  1745. precomputedAForVarEst.setIoUntilEndOfFile ( false );
  1746. precomputedAForVarEst.restore ( _is, _format );
  1747. }
  1748. _is >> tmp; // end of block
  1749. tmp = this->removeEndTag ( tmp );
  1750. }
  1751. else if ( tmp.compare("precomputedTForVarEst") == 0 )
  1752. {
  1753. std::string isNull;
  1754. _is >> isNull; // NOTNULL or NULL
  1755. if ( b_restoreVerbose )
  1756. std::cerr << "content of isNull: " << isNull << std::endl;
  1757. if (isNull.compare("NOTNULL") == 0)
  1758. {
  1759. if ( b_restoreVerbose )
  1760. std::cerr << "restore precomputedTForVarEst" << std::endl;
  1761. int sizeOfLUT;
  1762. _is >> sizeOfLUT;
  1763. precomputedTForVarEst = new double [ sizeOfLUT ];
  1764. for ( int i = 0; i < sizeOfLUT; i++ )
  1765. {
  1766. _is >> precomputedTForVarEst[i];
  1767. }
  1768. }
  1769. else
  1770. {
  1771. if ( b_restoreVerbose )
  1772. std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
  1773. if (precomputedTForVarEst != NULL)
  1774. delete precomputedTForVarEst;
  1775. }
  1776. _is >> tmp; // end of block
  1777. tmp = this->removeEndTag ( tmp );
  1778. }
  1779. /////////////////////////////////////////////////////
  1780. // online / incremental learning related variables //
  1781. /////////////////////////////////////////////////////
  1782. else if ( tmp.compare("b_usePreviousAlphas") == 0 )
  1783. {
  1784. _is >> b_usePreviousAlphas;
  1785. _is >> tmp; // end of block
  1786. tmp = this->removeEndTag ( tmp );
  1787. }
  1788. else if ( tmp.compare("previousAlphas") == 0 )
  1789. {
  1790. _is >> tmp; // size
  1791. uint sizeOfPreviousAlphas ( 0 );
  1792. _is >> sizeOfPreviousAlphas;
  1793. this->previousAlphas.clear();
  1794. if ( b_restoreVerbose )
  1795. std::cerr << "restore previousAlphas with size: " << sizeOfPreviousAlphas << std::endl;
  1796. for ( int i = 0; i < sizeOfPreviousAlphas; i++ )
  1797. {
  1798. uint classNo;
  1799. _is >> classNo;
  1800. NICE::Vector classAlpha;
  1801. _is >> classAlpha;
  1802. this->previousAlphas.insert ( std::pair< uint, NICE::Vector > ( classNo, classAlpha ) );
  1803. }
  1804. _is >> tmp; // end of block
  1805. tmp = this->removeEndTag ( tmp );
  1806. }
  1807. else
  1808. {
  1809. std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
  1810. throw;
  1811. }
  1812. }
  1813. //NOTE are there any more models you added? then add them here respectively in the correct order
  1814. //.....
  1815. //the last one is the GHIK - which we do not have to restore, but simply reset it
  1816. if ( b_restoreVerbose )
  1817. std::cerr << " add GMHIKernel" << std::endl;
  1818. ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
  1819. if ( b_restoreVerbose )
  1820. std::cerr << " restore positive and negative label" << std::endl;
  1821. this->knownClasses.clear();
  1822. if ( b_restoreVerbose )
  1823. std::cerr << " fill known classes object " << std::endl;
  1824. if ( this->precomputedA.size() == 1)
  1825. {
  1826. this->knownClasses.insert( this->i_binaryLabelPositive );
  1827. this->knownClasses.insert( this->i_binaryLabelNegative );
  1828. if ( b_restoreVerbose )
  1829. std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
  1830. }
  1831. else
  1832. {
  1833. for ( std::map<uint, PrecomputedType>::const_iterator itA = this->precomputedA.begin(); itA != this->precomputedA.end(); itA++)
  1834. knownClasses.insert ( itA->first );
  1835. if ( b_restoreVerbose )
  1836. std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
  1837. }
  1838. }
  1839. else
  1840. {
  1841. std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
  1842. throw;
  1843. }
  1844. }
  1845. void FMKGPHyperparameterOptimization::store ( std::ostream & _os,
  1846. int _format
  1847. ) const
  1848. {
  1849. if ( _os.good() )
  1850. {
  1851. // show starting point
  1852. _os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  1853. // _os.precision ( numeric_limits<double>::digits10 + 1 );
  1854. ///////////////////////////////////
  1855. // output/debug related settings //
  1856. ///////////////////////////////////
  1857. _os << this->createStartTag( "verbose" ) << std::endl;
  1858. _os << this->b_verbose << std::endl;
  1859. _os << this->createEndTag( "verbose" ) << std::endl;
  1860. _os << this->createStartTag( "verboseTime" ) << std::endl;
  1861. _os << this->b_verboseTime << std::endl;
  1862. _os << this->createEndTag( "verboseTime" ) << std::endl;
  1863. _os << this->createStartTag( "debug" ) << std::endl;
  1864. _os << this->b_debug << std::endl;
  1865. _os << this->createEndTag( "debug" ) << std::endl;
  1866. //////////////////////////////////////
  1867. // classification related variables //
  1868. //////////////////////////////////////
  1869. _os << this->createStartTag( "b_performRegression" ) << std::endl;
  1870. _os << b_performRegression << std::endl;
  1871. _os << this->createEndTag( "b_performRegression" ) << std::endl;
  1872. _os << this->createStartTag( "fmk" ) << std::endl;
  1873. this->fmk->store ( _os, _format );
  1874. _os << this->createEndTag( "fmk" ) << std::endl;
  1875. _os << this->createStartTag( "q" ) << std::endl;
  1876. if ( q != NULL )
  1877. {
  1878. _os << "NOTNULL" << std::endl;
  1879. this->q->store ( _os, _format );
  1880. }
  1881. else
  1882. {
  1883. _os << "NULL" << std::endl;
  1884. }
  1885. _os << this->createEndTag( "q" ) << std::endl;
  1886. _os << this->createStartTag( "parameterUpperBound" ) << std::endl;
  1887. _os << this->d_parameterUpperBound << std::endl;
  1888. _os << this->createEndTag( "parameterUpperBound" ) << std::endl;
  1889. _os << this->createStartTag( "parameterLowerBound" ) << std::endl;
  1890. _os << this->d_parameterLowerBound << std::endl;
  1891. _os << this->createEndTag( "parameterLowerBound" ) << std::endl;
  1892. _os << this->createStartTag( "pf" ) << std::endl;
  1893. this->pf->store(_os, _format);
  1894. _os << this->createEndTag( "pf" ) << std::endl;
  1895. _os << this->createStartTag( "precomputedA" ) << std::endl;
  1896. _os << "size: " << this->precomputedA.size() << std::endl;
  1897. std::map< uint, PrecomputedType >::const_iterator preCompIt = this->precomputedA.begin();
  1898. for ( uint i = 0; i < this->precomputedA.size(); i++ )
  1899. {
  1900. _os << preCompIt->first << std::endl;
  1901. ( preCompIt->second ).store ( _os, _format );
  1902. preCompIt++;
  1903. }
  1904. _os << this->createEndTag( "precomputedA" ) << std::endl;
  1905. _os << this->createStartTag( "precomputedB" ) << std::endl;
  1906. _os << "size: " << this->precomputedB.size() << std::endl;
  1907. preCompIt = this->precomputedB.begin();
  1908. for ( uint i = 0; i < this->precomputedB.size(); i++ )
  1909. {
  1910. _os << preCompIt->first << std::endl;
  1911. ( preCompIt->second ).store ( _os, _format );
  1912. preCompIt++;
  1913. }
  1914. _os << this->createEndTag( "precomputedB" ) << std::endl;
  1915. _os << this->createStartTag( "precomputedT" ) << std::endl;
  1916. _os << "size: " << this->precomputedT.size() << std::endl;
  1917. if ( this->precomputedT.size() > 0 )
  1918. {
  1919. int sizeOfLUT ( 0 );
  1920. if ( q != NULL )
  1921. sizeOfLUT = q->size() * this->fmk->get_d();
  1922. _os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
  1923. for ( std::map< uint, double * >::const_iterator it = this->precomputedT.begin(); it != this->precomputedT.end(); it++ )
  1924. {
  1925. _os << "index: " << it->first << std::endl;
  1926. for ( int i = 0; i < sizeOfLUT; i++ )
  1927. {
  1928. _os << ( it->second ) [i] << " ";
  1929. }
  1930. _os << std::endl;
  1931. }
  1932. }
  1933. _os << this->createEndTag( "precomputedT" ) << std::endl;
  1934. _os << this->createStartTag( "labels" ) << std::endl;
  1935. _os << this->labels << std::endl;
  1936. _os << this->createEndTag( "labels" ) << std::endl;
  1937. //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
  1938. _os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
  1939. _os << this->i_binaryLabelPositive << std::endl;
  1940. _os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
  1941. _os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
  1942. _os << this->i_binaryLabelNegative << std::endl;
  1943. _os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
  1944. _os << this->createStartTag( "knownClasses" ) << std::endl;
  1945. _os << "size: " << this->knownClasses.size() << std::endl;
  1946. for ( std::set< uint >::const_iterator itKnownClasses = this->knownClasses.begin();
  1947. itKnownClasses != this->knownClasses.end();
  1948. itKnownClasses++
  1949. )
  1950. {
  1951. _os << *itKnownClasses << " " << std::endl;
  1952. }
  1953. _os << this->createEndTag( "knownClasses" ) << std::endl;
  1954. _os << this->createStartTag( "ikmsum" ) << std::endl;
  1955. for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
  1956. {
  1957. ( ikmsum->getModel ( j ) )->store ( _os, _format );
  1958. }
  1959. _os << this->createEndTag( "ikmsum" ) << std::endl;
  1960. //////////////////////////////////////////////
  1961. // Iterative Linear Solver //
  1962. //////////////////////////////////////////////
  1963. _os << this->createStartTag( "linsolver" ) << std::endl;
  1964. //TODO linsolver
  1965. _os << this->createEndTag( "linsolver" ) << std::endl;
  1966. _os << this->createStartTag( "ils_max_iterations" ) << std::endl;
  1967. _os << this->ils_max_iterations << std::endl;
  1968. _os << this->createEndTag( "ils_max_iterations" ) << std::endl;
  1969. /////////////////////////////////////
  1970. // optimization related parameters //
  1971. /////////////////////////////////////
  1972. _os << this->createStartTag( "optimizationMethod" ) << std::endl;
  1973. _os << this->optimizationMethod << std::endl;
  1974. _os << this->createEndTag( "optimizationMethod" ) << std::endl;
  1975. _os << this->createStartTag( "optimizeNoise" ) << std::endl;
  1976. _os << this->optimizeNoise << std::endl;
  1977. _os << this->createEndTag( "optimizeNoise" ) << std::endl;
  1978. _os << this->createStartTag( "parameterStepSize" ) << std::endl;
  1979. _os << this->parameterStepSize << std::endl;
  1980. _os << this->createEndTag( "parameterStepSize" ) << std::endl;
  1981. _os << this->createStartTag( "downhillSimplexMaxIterations" ) << std::endl;
  1982. _os << this->downhillSimplexMaxIterations << std::endl;
  1983. _os << this->createEndTag( "downhillSimplexMaxIterations" ) << std::endl;
  1984. _os << this->createStartTag( "downhillSimplexTimeLimit" ) << std::endl;
  1985. _os << this->downhillSimplexTimeLimit << std::endl;
  1986. _os << this->createEndTag( "downhillSimplexTimeLimit" ) << std::endl;
  1987. _os << this->createStartTag( "downhillSimplexParamTol" ) << std::endl;
  1988. _os << this->downhillSimplexParamTol << std::endl;
  1989. _os << this->createEndTag( "downhillSimplexParamTol" ) << std::endl;
  1990. //////////////////////////////////////////////
  1991. // likelihood computation related variables //
  1992. //////////////////////////////////////////////
  1993. _os << this->createStartTag( "verifyApproximation" ) << std::endl;
  1994. _os << this->verifyApproximation << std::endl;
  1995. _os << this->createEndTag( "verifyApproximation" ) << std::endl;
  1996. _os << this->createStartTag( "eig" ) << std::endl;
  1997. //TODO eig
  1998. _os << this->createEndTag( "eig" ) << std::endl;
  1999. _os << this->createStartTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2000. _os << this->nrOfEigenvaluesToConsider << std::endl;
  2001. _os << this->createEndTag( "nrOfEigenvaluesToConsider" ) << std::endl;
  2002. _os << this->createStartTag( "eigenMax" ) << std::endl;
  2003. _os << this->eigenMax << std::endl;
  2004. _os << this->createEndTag( "eigenMax" ) << std::endl;
  2005. _os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
  2006. _os << this->eigenMaxVectors << std::endl;
  2007. _os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
  2008. ////////////////////////////////////////////
  2009. // variance computation related variables //
  2010. ////////////////////////////////////////////
  2011. _os << this->createStartTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2012. _os << this->nrOfEigenvaluesToConsiderForVarApprox << std::endl;
  2013. _os << this->createEndTag( "nrOfEigenvaluesToConsiderForVarApprox" ) << std::endl;
  2014. _os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
  2015. _os << precomputedAForVarEst.size() << std::endl;
  2016. if ( this->precomputedAForVarEst.size() > 0)
  2017. {
  2018. this->precomputedAForVarEst.store ( _os, _format );
  2019. _os << std::endl;
  2020. }
  2021. _os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
  2022. _os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
  2023. if ( this->precomputedTForVarEst != NULL )
  2024. {
  2025. _os << "NOTNULL" << std::endl;
  2026. int sizeOfLUT ( 0 );
  2027. if ( q != NULL )
  2028. sizeOfLUT = q->size() * this->fmk->get_d();
  2029. _os << sizeOfLUT << std::endl;
  2030. for ( int i = 0; i < sizeOfLUT; i++ )
  2031. {
  2032. _os << this->precomputedTForVarEst[i] << " ";
  2033. }
  2034. _os << std::endl;
  2035. }
  2036. else
  2037. {
  2038. _os << "NULL" << std::endl;
  2039. }
  2040. _os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
  2041. /////////////////////////////////////////////////////
  2042. // online / incremental learning related variables //
  2043. /////////////////////////////////////////////////////
  2044. _os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
  2045. _os << this->b_usePreviousAlphas << std::endl;
  2046. _os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
  2047. _os << this->createStartTag( "previousAlphas" ) << std::endl;
  2048. _os << "size: " << this->previousAlphas.size() << std::endl;
  2049. std::map< uint, NICE::Vector >::const_iterator prevAlphaIt = this->previousAlphas.begin();
  2050. for ( uint i = 0; i < this->previousAlphas.size(); i++ )
  2051. {
  2052. _os << prevAlphaIt->first << std::endl;
  2053. _os << prevAlphaIt->second << std::endl;
  2054. prevAlphaIt++;
  2055. }
  2056. _os << this->createEndTag( "previousAlphas" ) << std::endl;
  2057. // done
  2058. _os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
  2059. }
  2060. else
  2061. {
  2062. std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
  2063. }
  2064. }
  2065. void FMKGPHyperparameterOptimization::clear ( ) {};
  2066. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2067. // interface specific methods for incremental extensions
  2068. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  2069. void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
  2070. const double & label,
  2071. const bool & performOptimizationAfterIncrement
  2072. )
  2073. {
  2074. if ( this->b_verbose )
  2075. std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
  2076. NICE::Timer t;
  2077. t.start();
  2078. std::set< uint > newClasses;
  2079. this->labels.append ( label );
  2080. //have we seen this class already?
  2081. if ( !this->b_performRegression && ( this->knownClasses.find( label ) == this->knownClasses.end() ) )
  2082. {
  2083. this->knownClasses.insert( label );
  2084. newClasses.insert( label );
  2085. }
  2086. // If we currently have been in a binary setting, we now have to take care
  2087. // that we also compute an alpha vector for the second class, which previously
  2088. // could be dealt with implicitely.
  2089. // Therefore, we insert its label here...
  2090. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2091. newClasses.insert( this->i_binaryLabelNegative );
  2092. // add the new example to our data structure
  2093. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2094. NICE::Timer tFmk;
  2095. tFmk.start();
  2096. this->fmk->addExample ( example, pf );
  2097. tFmk.stop();
  2098. if ( this->b_verboseTime)
  2099. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2100. // add examples to all implicite kernel matrices we currently use
  2101. this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
  2102. // update the corresponding matrices A, B and lookup tables T
  2103. // optional: do the optimization again using the previously known solutions as initialization
  2104. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2105. //clean up
  2106. newClasses.clear();
  2107. t.stop();
  2108. NICE::ResourceStatistics rs;
  2109. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2110. long maxMemory;
  2111. rs.getMaximumMemory ( maxMemory );
  2112. if ( this->b_verbose )
  2113. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2114. if ( this->b_verbose )
  2115. std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
  2116. }
  2117. void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  2118. const NICE::Vector & newLabels,
  2119. const bool & performOptimizationAfterIncrement
  2120. )
  2121. {
  2122. if ( this->b_verbose )
  2123. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples --- " << std::endl;
  2124. NICE::Timer t;
  2125. t.start();
  2126. std::set< uint > newClasses;
  2127. this->labels.append ( newLabels );
  2128. //have we seen this class already?
  2129. if ( !this->b_performRegression)
  2130. {
  2131. for ( NICE::Vector::const_iterator vecIt = newLabels.begin();
  2132. vecIt != newLabels.end();
  2133. vecIt++
  2134. )
  2135. {
  2136. if ( this->knownClasses.find( *vecIt ) == this->knownClasses.end() )
  2137. {
  2138. this->knownClasses.insert( *vecIt );
  2139. newClasses.insert( *vecIt );
  2140. }
  2141. }
  2142. // If we currently have been in a OCC setting, and only add a single new class
  2143. // we have to take care that are still efficient, i.e., that we solve for alpha
  2144. // only ones, since scores are symmetric in binary cases
  2145. // Therefore, we remove the label of the secodn class from newClasses, to skip
  2146. // alpha computations for this class lateron...
  2147. //
  2148. // Therefore, we insert its label here...
  2149. if ( (newClasses.size() == 1 ) && ( (this->knownClasses.size() - newClasses.size() ) == 1 ) )
  2150. newClasses.clear();
  2151. // If we currently have been in a binary setting, we now have to take care
  2152. // that we also compute an alpha vector for the second class, which previously
  2153. // could be dealt with implicitely.
  2154. // Therefore, we insert its label here...
  2155. if ( (newClasses.size() > 0 ) && ( (this->knownClasses.size() - newClasses.size() ) == 2 ) )
  2156. newClasses.insert( this->i_binaryLabelNegative );
  2157. }
  2158. // in a regression setting, we do not have to remember any "class labels"
  2159. else{}
  2160. // add the new example to our data structure
  2161. // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
  2162. NICE::Timer tFmk;
  2163. tFmk.start();
  2164. this->fmk->addMultipleExamples ( newExamples, pf );
  2165. tFmk.stop();
  2166. if ( this->b_verboseTime)
  2167. std::cerr << "Time used for adding the data to the fmk object: " << tFmk.getLast() << std::endl;
  2168. // add examples to all implicite kernel matrices we currently use
  2169. this->ikmsum->addMultipleExamples ( newExamples, newLabels, performOptimizationAfterIncrement );
  2170. // update the corresponding matrices A, B and lookup tables T
  2171. // optional: do the optimization again using the previously known solutions as initialization
  2172. this->updateAfterIncrement ( newClasses, performOptimizationAfterIncrement );
  2173. //clean up
  2174. newClasses.clear();
  2175. t.stop();
  2176. NICE::ResourceStatistics rs;
  2177. std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
  2178. long maxMemory;
  2179. rs.getMaximumMemory ( maxMemory );
  2180. if ( this->b_verbose )
  2181. std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
  2182. if ( this->b_verbose )
  2183. std::cerr << " --- FMKGPHyperparameterOptimization::addMultipleExamples done --- " << std::endl;
  2184. }