FMKGPHyperparameterOptimization.cpp 94 KB

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