FMKGPHyperparameterOptimization.cpp 92 KB

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