123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190 |
- /**
- * @file FMKGPHyperparameterOptimization.cpp
- * @brief Heart of the framework to set up everything, perform optimization, classification, and variance prediction (Implementation)
- * @author Erik Rodner, Alexander Freytag
- * @date 01/02/2012
- */
- // STL includes
- #include <iostream>
- #include <map>
- // NICE-core includes
- #include <core/algebra/ILSConjugateGradients.h>
- #include <core/algebra/ILSConjugateGradientsLanczos.h>
- #include <core/algebra/ILSSymmLqLanczos.h>
- #include <core/algebra/ILSMinResLanczos.h>
- #include <core/algebra/ILSPlainGradient.h>
- #include <core/algebra/EigValuesTRLAN.h>
- #include <core/algebra/CholeskyRobust.h>
- //
- #include <core/basics/Timer.h>
- #include <core/basics/ResourceStatistics.h>
- #include <core/basics/Exception.h>
- //
- #include <core/vector/Algorithms.h>
- #include <core/vector/Eigen.h>
- //
- #include <core/optimization/blackbox/DownhillSimplexOptimizer.h>
- // gp-hik-core includes
- #include "FMKGPHyperparameterOptimization.h"
- #include "FastMinKernel.h"
- #include "GMHIKernel.h"
- #include "IKMNoise.h"
- using namespace NICE;
- using namespace std;
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- // PROTECTED METHODS
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- void FMKGPHyperparameterOptimization::updateAfterSingleIncrement (
- const NICE::SparseVector & x,
- const std::set < int > newClasses,
- const bool & performOptimizationAfterIncrement )
- {
- NICE::Timer t;
- t.start();
- if ( this->fmk == NULL )
- fthrow ( Exception, "FastMinKernel object was not initialized!" );
- std::map<int, NICE::Vector> binaryLabels;
- std::set<int> classesToUse;
- //TODO this could be made faster when storing the previous binary label vectors...
- this->prepareBinaryLabels ( binaryLabels, this->labels , classesToUse );
-
- if ( this->verbose )
- std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
- NICE::Timer t1;
- NICE::GPLikelihoodApprox * gplike;
- uint parameterVectorSize;
- std::cerr << "setup GPLikelihoodApprox object " << std::endl;
- t1.start();
- this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
- std::cerr << "setup previous alpha guess " << std::endl;
- t1.start();
- if ( this->b_usePreviousAlphas )
- {
- //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
- //default in GPLikelihoodApprox for the first time:
- // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
- double factor ( 1.0 / this->eigenMax[0] );
-
- std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
-
- for ( std::map<int, NICE::Vector>::iterator lastAlphaIt = lastAlphas.begin() ;lastAlphaIt != lastAlphas.end(); lastAlphaIt++ )
- {
- int oldSize ( lastAlphaIt->second.size() );
- lastAlphaIt->second.resize ( oldSize + 1 );
-
- if ( binaryLabelsIt->second[oldSize] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
- lastAlphaIt->second[oldSize] = factor;
- else
- lastAlphaIt->second[oldSize] = -factor; //we follow the initialization as done in previous steps
- //lastAlphaIt->second[oldSize] = 0.0; // following the suggestion of Yeh and Darrell
- binaryLabelsIt++;
-
- }
- //compute unaffected alpha-vectors for the new classes
- for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
- {
- NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
- lastAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
- }
- gplike->setInitialAlphaGuess ( &lastAlphas );
- }
- else
- {
- //if we do not use previous alphas, we do not have to set up anything here
- }
-
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
- std::cerr << "update Eigendecomposition " << std::endl;
- t1.start();
- // we compute all needed eigenvectors for standard classification and variance prediction at ones.
- // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
- this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
- if ( this->verbose )
- std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
- // we can reuse the already given performOptimization-method:
- // OPT_GREEDY
- // for this strategy we can't reuse any of the previously computed scores
- // so come on, let's do the whole thing again...
- // OPT_DOWNHILLSIMPLEX
- // Here we can benefit from previous results, when we use them as initialization for our optimizer
- // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
- // as initialization
- // OPT_NONE
- // nothing to do, obviously
- //NOTE we could skip this, if we do not want to change our parameters given new examples
- if ( this->verbose )
- std::cerr << "perform optimization after increment " << std::endl;
-
- int optimizationMethodTmpCopy;
- if ( !performOptimizationAfterIncrement )
- {
- // if no optimization shall be carried out, we simply set the optimization method to NONE but run the optimization
- // call nonetheless, thereby computing alpha vectors, etc. which would be not initialized
- optimizationMethodTmpCopy = this->optimizationMethod;
- this->optimizationMethod = OPT_NONE;
- }
-
- t1.start();
- //TODO add option for handing over previous solution!
- this->performOptimization ( *gplike, parameterVectorSize);
- // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
- if ( this->verbose )
- std::cerr << "Preparing after retraining for classification ..." << std::endl;
- t1.start();
- this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
- t1.stop();
- if ( this->verboseTime)
- std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
- if ( !performOptimizationAfterIncrement )
- {
- this->optimizationMethod = optimizationMethodTmpCopy;
- }
-
- //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
- // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
- // Since we are not aware of any such method, we have to compute them completely new
- // :/
- t1.start();
- this->computeMatricesAndLUTs ( *gplike );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
- t.stop();
- NICE::ResourceStatistics rs;
- std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
- long maxMemory;
- rs.getMaximumMemory ( maxMemory );
- std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
- //don't waste memory
- delete gplike;
- }
- void FMKGPHyperparameterOptimization::updateAfterMultipleIncrements (
- const std::vector<const NICE::SparseVector*> & x,
- const std::set < int > newClasses,
- const bool & performOptimizationAfterIncrement )
- {
- Timer t;
- t.start();
- if ( fmk == NULL )
- fthrow ( Exception, "FastMinKernel object was not initialized!" );
- std::map<int, NICE::Vector> binaryLabels;
- std::set<int> classesToUse;
- this->prepareBinaryLabels ( binaryLabels, labels , classesToUse );
- //actually, this is not needed, since we have the global set knownClasses
- classesToUse.clear();
-
- std::map<int, NICE::Vector> newBinaryLabels;
- if ( newClasses.size() > 0)
- {
- for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
- {
- std::map<int, NICE::Vector>::iterator binLabelIt = binaryLabels.find(*newClIt);
- newBinaryLabels.insert(*binLabelIt);
- }
- }
-
- if ( this->verbose )
- std::cerr << "labels.size() after increment: " << this->labels.size() << std::endl;
-
-
- // ************************************************************
- // include the information for classes we know so far
- // ************************************************************
- if ( this->verbose)
- std::cerr << "include the information for classes we know so far " << std::endl;
-
- NICE::Timer t1;
- t1.start();
- //update the kernel combinations
- //TODO verify that this is not needed anymore in any IKMLinearCombination class
-
- //we have to reset the fmk explicitely
- ( ( GMHIKernel* ) this->ikmsum->getModel ( this->ikmsum->getNumberOfModels() - 1 ) )->setFastMinKernel ( this->fmk );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the ikm-objects for known classes: " << t1.getLast() << std::endl;
-
- // *********************************************
- // work on the new classes
- // *********************************************
-
- if ( this->verbose )
- std::cerr << "work on the new classes " << std::endl;
-
- double tmpNoise;
- (this->ikmsum->getModel( 0 ))->getFirstDiagonalElement(tmpNoise);
-
-
- // ******************************************************************************************
- // now do everything which is independent of the number of new classes
- // ******************************************************************************************
- if ( this->verbose )
- std::cerr << "now do everything which is independent of the number of new classes" << std::endl;
- NICE::GPLikelihoodApprox * gplike;
- uint parameterVectorSize;
- t1.start();
- this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
- t1.start();
- // we compute all needed eigenvectors for standard classification and variance prediction at ones.
- // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
- this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
- t1.start();
- if ( this->b_usePreviousAlphas )
- {
- double factor ( 1.0 / this->eigenMax[0] );
-
- std::map<int, NICE::Vector>::const_iterator binaryLabelsIt = binaryLabels.begin();
-
- for ( std::map<int, NICE::Vector>::iterator lastAlphaIt = lastAlphas.begin() ;lastAlphaIt != lastAlphas.end(); lastAlphaIt++ )
- {
-
- int oldSize ( lastAlphaIt->second.size() );
- lastAlphaIt->second.resize ( oldSize + x.size() );
- //We initialize it with the same values as we use in GPLikelihoodApprox in batch training
- //default in GPLikelihoodApprox for the first time:
- // alpha = (binaryLabels[classCnt] * (1.0 / eigenmax[0]) );
-
- for ( uint i = 0; i < x.size(); i++ )
- {
- if ( binaryLabelsIt->second[oldSize+i] > 0 ) //we only have +1 and -1, so this might be benefitial in terms of speed
- lastAlphaIt->second[oldSize+i] = factor;
- else
- lastAlphaIt->second[oldSize+i] = -factor; //we follow the initialization as done in previous steps
- //lastAlphaIt->second[oldSize+i] = 0.0; // following the suggestion of Yeh and Darrell
- }
- binaryLabelsIt++;
- }
- //compute unaffected alpha-vectors for the new classes
- for (std::set<int>::const_iterator newClIt = newClasses.begin(); newClIt != newClasses.end(); newClIt++)
- {
- NICE::Vector alphaVec = (binaryLabels[*newClIt] * factor ); //see GPLikelihoodApprox for an explanation
- lastAlphas.insert( std::pair<int, NICE::Vector>(*newClIt, alphaVec) );
- }
- //TODO check that memory will not be erased when calling delete!
- gplike->setInitialAlphaGuess ( &lastAlphas );
- }
- else
- {
- }
-
- //if we do not use previous alphas, we do not have to set up anything here
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the alpha-objects: " << t1.getLast() << std::endl;
- if ( this->verbose )
- std::cerr << "resulting eigenvalues of first class: " << eigenMax[0] << std::endl;
- // we can reuse the already given performOptimization-method:
- // OPT_GREEDY
- // for this strategy we can't reuse any of the previously computed scores
- // so come on, let's do the whole thing again...
- // OPT_DOWNHILLSIMPLEX
- // Here we can benefit from previous results, when we use them as initialization for our optimizer
- // ikmsums.begin()->second->getParameters ( currentParameters ); uses the previously computed optimal parameters
- // as initialization
- // OPT_NONE
- // nothing to do, obviously
- //NOTE we can skip this, if we do not want to change our parameters given new examples
- if ( performOptimizationAfterIncrement )
- {
- t1.start();
- //TODO add option for handing over previous solution!
- this->performOptimization ( *gplike, parameterVectorSize);
- // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
-
- t1.start();
- this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
- t1.stop();
- if ( this->verboseTime)
- std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
- }
- else
- {
- //deactivate the optimization method;
- int originalOptimizationMethod = optimizationMethod;
- this->optimizationMethod = OPT_NONE;
- //and deactive the noise-optimization as well
- if ( this->optimizeNoise )
- this->optimizeNoise = false;
-
- t1.start();
- //this is needed to compute the alpha vectors for the standard parameter settings
- //TODO add option for handing over previous solution!
- this->performOptimization ( *gplike, parameterVectorSize);
- // this->performOptimization ( *gplike, parameterVectorSize, false /* initialize not with default values but using the last solution */ );
- t1.stop();
- std::cerr << "skip optimization after increment" << std::endl;
- if ( this->verboseTime )
- std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
- std::cerr << "skip feature transformation" << std::endl;
- if ( this->verboseTime )
- std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
-
- //re-activate the optimization method
- this->optimizationMethod = originalOptimizationMethod;
- }
- if ( this->verbose )
- std::cerr << "Preparing after retraining for classification ..." << std::endl;
- //NOTE unfortunately, the whole vector alpha differs, and not only its last entry.
- // If we knew any method, which could update this efficiently, we could also compute A and B more efficiently by updating them.
- // Since we are not aware of any such method, we have to compute them completely new
- // :/
- t1.start();
- this->computeMatricesAndLUTs ( *gplike );
- t1.stop();
- if ( this->verboseTime )
- std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
- t.stop();
- NICE::ResourceStatistics rs;
- std::cerr << "Time used for re-learning: " << t.getLast() << std::endl;
- long maxMemory;
- rs.getMaximumMemory ( maxMemory );
- std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
- //don't waste memory
- delete gplike;
- }
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- // PUBLIC METHODS
- /////////////////////////////////////////////////////
- /////////////////////////////////////////////////////
- FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization()
- {
- // initialize pointer variables
- pf = NULL;
- eig = NULL;
- linsolver = NULL;
- fmk = NULL;
- q = NULL;
- precomputedTForVarEst = NULL;
- ikmsum = NULL;
-
- // initialize boolean flags
- verbose = false;
- verboseTime = false;
- debug = false;
-
- //stupid unneeded default values
- binaryLabelPositive = -1;
- binaryLabelNegative = -2;
-
- this->b_usePreviousAlphas = false;
- }
- FMKGPHyperparameterOptimization::FMKGPHyperparameterOptimization ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const string & _confSection )
- {
- // initialize pointer variables
- pf = NULL;
- eig = NULL;
- linsolver = NULL;
- fmk = NULL;
- q = NULL;
- precomputedTForVarEst = NULL;
- ikmsum = NULL;
-
- //stupid unneeded default values
- binaryLabelPositive = -1;
- binaryLabelNegative = -2;
- knownClasses.clear();
- //TODO
- if ( _fmk == NULL )
- this->initialize ( _conf, _pf ); //then the confSection is also the default value
- else
- this->initialize ( _conf, _pf, _fmk, _confSection );
- }
- FMKGPHyperparameterOptimization::~FMKGPHyperparameterOptimization()
- {
- //pf will delete from outer program
- if ( this->eig != NULL )
- delete this->eig;
- if ( this->linsolver != NULL )
- delete this->linsolver;
- if ( this->fmk != NULL )
- delete this->fmk;
- if ( this->q != NULL )
- delete this->q;
- for ( uint i = 0 ; i < precomputedT.size(); i++ )
- delete [] ( precomputedT[i] );
- if ( precomputedTForVarEst != NULL )
- delete precomputedTForVarEst;
- if ( ikmsum != NULL )
- delete ikmsum;
- }
- void FMKGPHyperparameterOptimization::initialize ( const Config *_conf, ParameterizedFunction *_pf, FastMinKernel *_fmk, const std::string & _confSection )
- {
- if ( _fmk != NULL )
- {
- if ( this->fmk != NULL )
- {
- delete this->fmk;
- fmk = NULL;
- }
- this->fmk = _fmk;
- }
-
- this->pf = _pf;
-
- this->verbose = _conf->gB ( _confSection, "verbose", false );
- this->verboseTime = _conf->gB ( _confSection, "verboseTime", false );
- this->debug = _conf->gB ( _confSection, "debug", false );
- if ( verbose )
- {
- std::cerr << "------------" << std::endl;
- std::cerr << "| set-up |" << std::endl;
- std::cerr << "------------" << std::endl;
- }
- this->eig = new EVArnoldi ( _conf->gB ( _confSection, "eig_verbose", false ) /* verbose flag */, 10 );
- // this->eig = new EigValuesTRLAN();
- // My time measurements show that both methods use equal time, a comparision
- // of their numerical performance has not been done yet
- this->parameterUpperBound = _conf->gD ( _confSection, "parameter_upper_bound", 2.5 );
- this->parameterLowerBound = _conf->gD ( _confSection, "parameter_lower_bound", 1.0 );
- this->parameterStepSize = _conf->gD ( _confSection, "parameter_step_size", 0.1 );
- this->verifyApproximation = _conf->gB ( _confSection, "verify_approximation", false );
- this->nrOfEigenvaluesToConsider = _conf->gI ( _confSection, "nrOfEigenvaluesToConsider", 1 );
- this->nrOfEigenvaluesToConsiderForVarApprox = _conf->gI ( _confSection, "nrOfEigenvaluesToConsiderForVarApprox", 1 );
- bool useQuantization = _conf->gB ( _confSection, "use_quantization", false );
-
- if ( verbose )
- {
- std::cerr << "_confSection: " << _confSection << std::endl;
- std::cerr << "use_quantization: " << useQuantization << std::endl;
- }
-
- if ( _conf->gB ( _confSection, "use_quantization", false ) ) {
- int numBins = _conf->gI ( _confSection, "num_bins", 100 );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: quantization initialized with " << numBins << " bins." << std::endl;
- this->q = new Quantization ( numBins );
- } else {
- this->q = NULL;
- }
- bool ils_verbose = _conf->gB ( _confSection, "ils_verbose", false );
- ils_max_iterations = _conf->gI ( _confSection, "ils_max_iterations", 1000 );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: maximum number of iterations is " << ils_max_iterations << std::endl;
- double ils_min_delta = _conf->gD ( _confSection, "ils_min_delta", 1e-7 );
- double ils_min_residual = _conf->gD ( _confSection, "ils_min_residual", 1e-7/*1e-2 */ );
- string ils_method = _conf->gS ( _confSection, "ils_method", "CG" );
- if ( ils_method.compare ( "CG" ) == 0 )
- {
- if ( verbose )
- 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;
- this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients" << std::endl;
- }
- else if ( ils_method.compare ( "CGL" ) == 0 )
- {
- this->linsolver = new ILSConjugateGradientsLanczos ( ils_verbose , ils_max_iterations );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: using ILS ConjugateGradients (Lanczos)" << std::endl;
- }
- else if ( ils_method.compare ( "SYMMLQ" ) == 0 )
- {
- this->linsolver = new ILSSymmLqLanczos ( ils_verbose , ils_max_iterations );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: using ILS SYMMLQ" << std::endl;
- }
- else if ( ils_method.compare ( "MINRES" ) == 0 )
- {
- this->linsolver = new ILSMinResLanczos ( ils_verbose , ils_max_iterations );
- if ( verbose )
- std::cerr << "FMKGPHyperparameterOptimization: using ILS MINRES" << std::endl;
- }
- else
- {
- std::cerr << "FMKGPHyperparameterOptimization: " << _confSection << ":ils_method (" << ils_method << ") does not match any type (CG,CGL,SYMMLQ,MINRES), I will use CG" << std::endl;
- this->linsolver = new ILSConjugateGradients ( ils_verbose , ils_max_iterations, ils_min_delta, ils_min_residual );
- }
-
- string optimizationMethod_s = _conf->gS ( _confSection, "optimization_method", "greedy" );
- if ( optimizationMethod_s == "greedy" )
- optimizationMethod = OPT_GREEDY;
- else if ( optimizationMethod_s == "downhillsimplex" )
- optimizationMethod = OPT_DOWNHILLSIMPLEX;
- else if ( optimizationMethod_s == "none" )
- optimizationMethod = OPT_NONE;
- else
- fthrow ( Exception, "Optimization method " << optimizationMethod_s << " is not known." );
- if ( verbose )
- std::cerr << "Using optimization method: " << optimizationMethod_s << std::endl;
- downhillSimplexMaxIterations = _conf->gI ( _confSection, "downhillsimplex_max_iterations", 20 );
- // do not run longer than a day :)
- downhillSimplexTimeLimit = _conf->gD ( _confSection, "downhillsimplex_time_limit", 24 * 60 * 60 );
- downhillSimplexParamTol = _conf->gD ( _confSection, "downhillsimplex_delta", 0.01 );
- optimizeNoise = _conf->gB ( _confSection, "optimize_noise", false );
- if ( verbose )
- std::cerr << "Optimize noise: " << ( optimizeNoise ? "on" : "off" ) << std::endl;
-
- this->b_usePreviousAlphas = _conf->gB ( _confSection, "b_usePreviousAlphas", true );
-
- if ( verbose )
- {
- std::cerr << "------------" << std::endl;
- std::cerr << "| start |" << std::endl;
- std::cerr << "------------" << std::endl;
- }
- }
- ///////////////////// ///////////////////// /////////////////////
- // GET / SET
- ///////////////////// ///////////////////// /////////////////////
- void FMKGPHyperparameterOptimization::setParameterUpperBound ( const double & _parameterUpperBound )
- {
- parameterUpperBound = _parameterUpperBound;
- }
- void FMKGPHyperparameterOptimization::setParameterLowerBound ( const double & _parameterLowerBound )
- {
- parameterLowerBound = _parameterLowerBound;
- }
- std::set<int> FMKGPHyperparameterOptimization::getKnownClassNumbers ( ) const
- {
- return this->knownClasses;
- }
- ///////////////////// ///////////////////// /////////////////////
- // CLASSIFIER STUFF
- ///////////////////// ///////////////////// /////////////////////
- inline void FMKGPHyperparameterOptimization::setupGPLikelihoodApprox ( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize )
- {
- gplike = new GPLikelihoodApprox ( binaryLabels, ikmsum, linsolver, eig, verifyApproximation, nrOfEigenvaluesToConsider );
- gplike->setDebug( debug );
- gplike->setVerbose( verbose );
- parameterVectorSize = ikmsum->getNumParameters();
- }
- void FMKGPHyperparameterOptimization::updateEigenDecomposition( const int & i_noEigenValues )
- {
- //compute the largest eigenvalue of K + noise
- try
- {
- eig->getEigenvalues ( *ikmsum, eigenMax, eigenMaxVectors, i_noEigenValues );
- }
- catch ( char const* exceptionMsg)
- {
- std::cerr << exceptionMsg << std::endl;
- throw("Problem in calculating Eigendecomposition of kernel matrix. Abort program...");
- }
-
- //NOTE EigenValue computation extracts EV and EW per default in decreasing order.
-
- }
- void FMKGPHyperparameterOptimization::performOptimization ( GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
- {
- if (verbose)
- std::cerr << "perform optimization" << std::endl;
-
- if ( optimizationMethod == OPT_GREEDY )
- {
- if ( verbose )
- std::cerr << "OPT_GREEDY!!! " << std::endl;
-
- // simple greedy strategy
- if ( ikmsum->getNumParameters() != 1 )
- fthrow ( Exception, "Reduce size of the parameter vector or use downhill simplex!" );
- NICE::Vector lB = ikmsum->getParameterLowerBounds();
- NICE::Vector uB = ikmsum->getParameterUpperBounds();
-
- if ( verbose )
- std::cerr << "lower bound " << lB << " upper bound " << uB << " parameterStepSize: " << parameterStepSize << std::endl;
-
- NICE::Vector tmp = gplike.getBestParameters( );
-
- for ( double mypara = lB[0]; mypara <= uB[0]; mypara += this->parameterStepSize )
- {
- OPTIMIZATION::matrix_type hyperp ( 1, 1, mypara );
- gplike.evaluate ( hyperp );
- }
- }
- else if ( optimizationMethod == OPT_DOWNHILLSIMPLEX )
- {
- //standard as before, normal optimization
- if ( verbose )
- std::cerr << "DOWNHILLSIMPLEX!!! " << std::endl;
- // downhill simplex strategy
- OPTIMIZATION::DownhillSimplexOptimizer optimizer;
- OPTIMIZATION::matrix_type initialParams ( parameterVectorSize, 1 );
- NICE::Vector currentParameters;
- ikmsum->getParameters ( currentParameters );
- for ( uint i = 0 ; i < parameterVectorSize; i++ )
- initialParams(i,0) = currentParameters[ i ];
- if ( verbose )
- std::cerr << "Initial parameters: " << initialParams << std::endl;
- //the scales object does not really matter in the actual implementation of Downhill Simplex
- //OPTIMIZATION::matrix_type scales ( parameterVectorSize, 1);
- //scales.Set(1.0);
-
- OPTIMIZATION::SimpleOptProblem optProblem ( &gplike, initialParams, initialParams /* scales*/ );
- // std::cerr << "OPT: " << mypara << " " << nlikelihood << " " << logdet << " " << dataterm << std::endl;
- optimizer.setMaxNumIter ( true, downhillSimplexMaxIterations );
- optimizer.setTimeLimit ( true, downhillSimplexTimeLimit );
- optimizer.setParamTol ( true, downhillSimplexParamTol );
- optimizer.optimizeProb ( optProblem );
- }
- else if ( optimizationMethod == OPT_NONE )
- {
- if ( verbose )
- std::cerr << "NO OPTIMIZATION!!! " << std::endl;
- // without optimization
- if ( optimizeNoise )
- fthrow ( Exception, "Deactivate optimize_noise!" );
-
- if ( verbose )
- std::cerr << "Optimization is deactivated!" << std::endl;
-
- double value (1.0);
- if ( this->parameterLowerBound == this->parameterUpperBound)
- value = this->parameterLowerBound;
- pf->setParameterLowerBounds ( NICE::Vector ( 1, value ) );
- pf->setParameterUpperBounds ( NICE::Vector ( 1, value ) );
- // we use the standard value
- OPTIMIZATION::matrix_type hyperp ( 1, 1, value );
- gplike.setParameterLowerBound ( value );
- gplike.setParameterUpperBound ( value );
- //we do not need to compute the likelihood here - we are only interested in directly obtaining alpha vectors
- gplike.computeAlphaDirect( hyperp, eigenMax );
- }
- if ( verbose )
- {
- std::cerr << "Optimal hyperparameter was: " << gplike.getBestParameters() << std::endl;
- }
- }
- void FMKGPHyperparameterOptimization::transformFeaturesWithOptimalParameters ( const GPLikelihoodApprox & gplike, const uint & parameterVectorSize )
- {
- // transform all features with the currently "optimal" parameter
- ikmsum->setParameters ( gplike.getBestParameters() );
- }
- void FMKGPHyperparameterOptimization::computeMatricesAndLUTs ( const GPLikelihoodApprox & gplike )
- {
-
- std::cerr << "FMKGPHyperparameterOptimization::computeMatricesAndLUTs" << std::endl;
- precomputedA.clear();
- precomputedB.clear();
-
- std::cerr << "length of best alpha vectors: " << gplike.getBestAlphas().size() << std::endl;
- for ( std::map<int, NICE::Vector>::const_iterator i = gplike.getBestAlphas().begin(); i != gplike.getBestAlphas().end(); i++ )
- {
- PrecomputedType A;
- PrecomputedType B;
- fmk->hik_prepare_alpha_multiplications ( i->second, A, B );
- A.setIoUntilEndOfFile ( false );
- B.setIoUntilEndOfFile ( false );
- precomputedA[ i->first ] = A;
- precomputedB[ i->first ] = B;
- if ( q != NULL )
- {
- double *T = fmk->hik_prepare_alpha_multiplications_fast ( A, B, *q, pf );
- //just to be sure that we do not waste space here
- if ( precomputedT[ i->first ] != NULL )
- delete precomputedT[ i->first ];
-
- precomputedT[ i->first ] = T;
- }
-
- //TODO update the variance-related matrices as well here - currently it is done before in the outer method!!!
- }
-
- if ( this->precomputedTForVarEst != NULL )
- {
- this->prepareVarianceApproximationRough();
- }
- else if ( this->precomputedAForVarEst.size() > 0)
- {
- this->prepareVarianceApproximationFine();
- }
- }
- #ifdef NICE_USELIB_MATIO
- void FMKGPHyperparameterOptimization::optimizeBinary ( const sparse_t & data, const NICE::Vector & yl, const std::set<int> & positives, const std::set<int> & negatives, double noise )
- {
- map<int, int> examples;
- Vector y ( yl.size() );
- int ind = 0;
- for ( uint i = 0 ; i < yl.size(); i++ )
- {
- if ( positives.find ( i ) != positives.end() ) {
- y[ examples.size() ] = 1.0;
- examples.insert ( pair<int, int> ( i, ind ) );
- ind++;
- } else if ( negatives.find ( i ) != negatives.end() ) {
- y[ examples.size() ] = -1.0;
- examples.insert ( pair<int, int> ( i, ind ) );
- ind++;
- }
- }
- y.resize ( examples.size() );
- std::cerr << "Examples: " << examples.size() << std::endl;
- optimize ( data, y, examples, noise );
- }
- void FMKGPHyperparameterOptimization::optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise )
- {
- Timer t;
- t.start();
- std::cerr << "Initializing data structure ..." << std::endl;
- if ( fmk != NULL ) delete fmk;
- fmk = new FastMinKernel ( data, noise, examples );
- t.stop();
- if (verboseTime)
- std::cerr << "Time used for initializing the FastMinKernel structure: " << t.getLast() << std::endl;
-
- optimize ( y );
- }
- #endif
- int FMKGPHyperparameterOptimization::prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses )
- {
- myClasses.clear();
-
- // determine which classes we have in our label vector
- // -> MATLAB: myClasses = unique(y);
- for ( NICE::Vector::const_iterator it = y.begin(); it != y.end(); it++ )
- {
- if ( myClasses.find ( *it ) == myClasses.end() )
- {
- myClasses.insert ( *it );
- }
- }
- //count how many different classes appear in our data
- int nrOfClasses = myClasses.size();
- binaryLabels.clear();
- //compute the corresponding binary label vectors
- if ( nrOfClasses > 2 )
- {
- //resize every labelVector and set all entries to -1.0
- for ( set<int>::const_iterator k = myClasses.begin(); k != myClasses.end(); k++ )
- {
- binaryLabels[ *k ].resize ( y.size() );
- binaryLabels[ *k ].set ( -1.0 );
- }
- // now look on every example and set the entry of its corresponding label vector to 1.0
- // proper existance should not be a problem
- for ( int i = 0 ; i < ( int ) y.size(); i++ )
- binaryLabels[ y[i] ][i] = 1.0;
- }
- else if ( nrOfClasses == 2 )
- {
- //binary setting -- prepare two binary label vectors with opposite signs
- NICE::Vector yb ( y );
- binaryLabelNegative = *(myClasses.begin());
- std::set<int>::const_iterator classIt = myClasses.begin(); classIt++;
- binaryLabelPositive = *classIt;
-
- if ( verbose )
- std::cerr << "positiveClass : " << binaryLabelPositive << " negativeClass: " << binaryLabelNegative << std::endl;
- for ( uint i = 0 ; i < yb.size() ; i++ )
- yb[i] = ( y[i] == binaryLabelNegative ) ? -1.0 : 1.0;
-
- binaryLabels[ binaryLabelPositive ] = yb;
-
- //NOTE
- //uncomment the following, if you want to perform real binary computations with 2 classes
- // //we only need one vector, which already contains +1 and -1, so we need only one computation too
- // binaryLabels[ negativeClass ] = yb;
- // binaryLabels[ negativeClass ] *= -1.0;
-
- // std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
-
- // binaryLabels[ 0 ] = yb;
- // binaryLabels[ 0 ] *= -1.0;
-
-
- //comment the following, if you want to do a real binary computation. It should be senseless, but let's see...
-
- //we do NOT do real binary computation, but an implicite one with only a single object
- nrOfClasses--;
- std::set<int>::iterator it = myClasses.begin(); it++;
- // myClasses.erase(it);
- }
- else //OCC setting
- {
- //we set the labels to 1, independent of the previously given class number
- //however, the original class numbers are stored and returned in classification
- Vector yNew ( y.size(), 1 );
- myClasses.clear();
- myClasses.insert ( 1 );
- //we have to indicate, that we are in an OCC setting
- nrOfClasses--;
- }
- return nrOfClasses;
- }
- void FMKGPHyperparameterOptimization::optimize ( const NICE::Vector & y )
- {
- if ( fmk == NULL )
- fthrow ( Exception, "FastMinKernel object was not initialized!" );
- this->labels = y;
-
- std::map<int, NICE::Vector> binaryLabels;
- prepareBinaryLabels ( binaryLabels, y , knownClasses );
-
- //now call the main function :)
- this->optimize(binaryLabels);
- }
-
- void FMKGPHyperparameterOptimization::optimize ( std::map<int, NICE::Vector> & binaryLabels )
- {
- Timer t;
- t.start();
-
- //how many different classes do we have right now?
- int nrOfClasses = binaryLabels.size();
-
- if (verbose)
- {
- std::cerr << "Initial noise level: " << fmk->getNoise() << std::endl;
- std::cerr << "Number of classes (=1 means we have a binary setting):" << nrOfClasses << std::endl;
- std::cerr << "Effective number of classes (neglecting classes without positive examples): " << knownClasses.size() << std::endl;
- }
- // combine standard model and noise model
- Timer t1;
- t1.start();
- //setup the kernel combination
- ikmsum = new IKMLinearCombination ();
- if ( verbose )
- {
- std::cerr << "binaryLabels.size(): " << binaryLabels.size() << std::endl;
- }
- //First model: noise
- ikmsum->addModel ( new IKMNoise ( fmk->get_n(), fmk->getNoise(), optimizeNoise ) );
-
- // set pretty low built-in noise, because we explicitely add the noise with the IKMNoise
- fmk->setNoise ( 0.0 );
- //NOTE The GMHIKernel is always the last model which is added (this is necessary for easy store and restore functionality)
- ikmsum->addModel ( new GMHIKernel ( fmk, pf, NULL /* no quantization */ ) );
- t1.stop();
- if (verboseTime)
- std::cerr << "Time used for setting up the ikm-objects: " << t1.getLast() << std::endl;
- GPLikelihoodApprox * gplike;
- uint parameterVectorSize;
- t1.start();
- this->setupGPLikelihoodApprox ( gplike, binaryLabels, parameterVectorSize );
- t1.stop();
-
- if (verboseTime)
- std::cerr << "Time used for setting up the gplike-objects: " << t1.getLast() << std::endl;
- if (verbose)
- {
- std::cerr << "parameterVectorSize: " << parameterVectorSize << std::endl;
- }
- t1.start();
- // we compute all needed eigenvectors for standard classification and variance prediction at ones.
- // nrOfEigenvaluesToConsiderForVarApprox should NOT be larger than 1 if a method different than approximate_fine is used!
- this->updateEigenDecomposition( std::max ( this->nrOfEigenvaluesToConsider, this->nrOfEigenvaluesToConsiderForVarApprox) );
- t1.stop();
- if (verboseTime)
- std::cerr << "Time used for setting up the eigenvectors-objects: " << t1.getLast() << std::endl;
- if ( verbose )
- std::cerr << "resulting eigenvalues for first class: " << eigenMax[0] << std::endl;
- t1.start();
- this->performOptimization ( *gplike, parameterVectorSize );
- t1.stop();
- if (verboseTime)
- std::cerr << "Time used for performing the optimization: " << t1.getLast() << std::endl;
- if ( verbose )
- std::cerr << "Preparing classification ..." << std::endl;
- t1.start();
- this->transformFeaturesWithOptimalParameters ( *gplike, parameterVectorSize );
- t1.stop();
- if (verboseTime)
- std::cerr << "Time used for transforming features with optimal parameters: " << t1.getLast() << std::endl;
- t1.start();
- this->computeMatricesAndLUTs ( *gplike );
- t1.stop();
- if (verboseTime)
- std::cerr << "Time used for setting up the A'nB -objects: " << t1.getLast() << std::endl;
- t.stop();
- ResourceStatistics rs;
- std::cerr << "Time used for learning: " << t.getLast() << std::endl;
- long maxMemory;
- rs.getMaximumMemory ( maxMemory );
- std::cerr << "Maximum memory used: " << maxMemory << " KB" << std::endl;
- //don't waste memory
- delete gplike;
- }
- void FMKGPHyperparameterOptimization::prepareVarianceApproximationRough()
- {
- PrecomputedType AVar;
- fmk->hikPrepareKVNApproximation ( AVar );
- precomputedAForVarEst = AVar;
- precomputedAForVarEst.setIoUntilEndOfFile ( false );
- if ( q != NULL )
- {
- double *T = fmk->hikPrepareLookupTableForKVNApproximation ( *q, pf );
- this->precomputedTForVarEst = T;
- }
- }
- void FMKGPHyperparameterOptimization::prepareVarianceApproximationFine()
- {
- if ( this->eigenMax.size() != this->nrOfEigenvaluesToConsiderForVarApprox)
- {
- std::cerr << "not enough eigenvectors computed for fine approximation of predictive variance. Compute missing ones!" << std::endl;
- this->updateEigenDecomposition( this->nrOfEigenvaluesToConsiderForVarApprox );
- }
- }
- int FMKGPHyperparameterOptimization::classify ( const NICE::SparseVector & xstar, NICE::SparseVector & scores ) const
- {
- // loop through all classes
- if ( precomputedA.size() == 0 )
- {
- fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
- }
- uint maxClassNo = 0;
- for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
- {
- uint classno = i->first;
- maxClassNo = std::max ( maxClassNo, classno );
- double beta;
- if ( q != NULL ) {
- map<int, double *>::const_iterator j = precomputedT.find ( classno );
- double *T = j->second;
- fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
- } else {
- const PrecomputedType & A = i->second;
- std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
- const PrecomputedType & B = j->second;
- // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
- // Giving the transformation pf as an additional
- // argument is necessary due to the following reason:
- // FeatureMatrixT is sorted according to the original values, therefore,
- // searching for upper and lower bounds ( findFirst... functions ) require original feature
- // values as inputs. However, for calculation we need the transformed features values.
- fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
- }
- scores[ classno ] = beta;
- }
- scores.setDim ( maxClassNo + 1 );
-
- if ( precomputedA.size() > 1 )
- { // multi-class classification
- return scores.maxElement();
- }
- else
- { // binary setting
- scores[binaryLabelNegative] = -scores[binaryLabelPositive];
- return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
- }
- }
- int FMKGPHyperparameterOptimization::classify ( const NICE::Vector & xstar, NICE::SparseVector & scores ) const
- {
- // loop through all classes
- if ( precomputedA.size() == 0 )
- {
- fthrow ( Exception, "The precomputation vector is zero...have you trained this classifier?" );
- }
- uint maxClassNo = 0;
- for ( std::map<int, PrecomputedType>::const_iterator i = precomputedA.begin() ; i != precomputedA.end(); i++ )
- {
- uint classno = i->first;
- maxClassNo = std::max ( maxClassNo, classno );
- double beta;
- if ( q != NULL ) {
- std::map<int, double *>::const_iterator j = precomputedT.find ( classno );
- double *T = j->second;
- fmk->hik_kernel_sum_fast ( T, *q, xstar, beta );
- } else {
- const PrecomputedType & A = i->second;
- std::map<int, PrecomputedType>::const_iterator j = precomputedB.find ( classno );
- const PrecomputedType & B = j->second;
- // fmk->hik_kernel_sum ( A, B, xstar, beta ); if A, B are of type Matrix
- // Giving the transformation pf as an additional
- // argument is necessary due to the following reason:
- // FeatureMatrixT is sorted according to the original values, therefore,
- // searching for upper and lower bounds ( findFirst... functions ) require original feature
- // values as inputs. However, for calculation we need the transformed features values.
- fmk->hik_kernel_sum ( A, B, xstar, beta, pf );
- }
- scores[ classno ] = beta;
- }
- scores.setDim ( maxClassNo + 1 );
-
- if ( precomputedA.size() > 1 )
- { // multi-class classification
- return scores.maxElement();
- }
- else
- { // binary setting
-
- scores[binaryLabelNegative] = -scores[binaryLabelPositive];
- return scores[ binaryLabelPositive ] <= 0.0 ? binaryLabelNegative : binaryLabelPositive;
- }
- }
- //////////////////////////////////////////
- // variance computation: sparse inputs
- //////////////////////////////////////////
- void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::SparseVector & x, double & predVariance ) const
- {
- // security check!
- if ( pf == NULL )
- fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
-
- // ---------------- compute the first term --------------------
- double kSelf ( 0.0 );
- for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
- {
- kSelf += pf->f ( 0, it->second );
- // if weighted dimensions:
- //kSelf += pf->f(it->first,it->second);
- }
-
- // ---------------- compute the approximation of the second term --------------------
- double normKStar;
- if ( q != NULL )
- {
- if ( precomputedTForVarEst == NULL )
- {
- fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
- }
- fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
- }
- else
- {
- if ( precomputedAForVarEst.size () == 0 )
- {
- fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
- }
- fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
- }
- predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
- }
- void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::SparseVector & x, double & predVariance ) const
- {
- // security check!
- if ( eigenMaxVectors.rows() == 0 )
- {
- fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
- }
-
- // ---------------- compute the first term --------------------
- // Timer t;
- // t.start();
- double kSelf ( 0.0 );
- for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
- {
- kSelf += pf->f ( 0, it->second );
- // if weighted dimensions:
- //kSelf += pf->f(it->first,it->second);
- }
- // ---------------- compute the approximation of the second term --------------------
- // t.stop();
- // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
- // t.start();
- NICE::Vector kStar;
- fmk->hikComputeKernelVector ( x, kStar );
- /* t.stop();
- std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
-
- // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
- // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
- NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
- //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
- //wherefor it takes aeons...
- //so we compute it by ourselves
-
-
- // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
- NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
- // double kStarI ( kStar[tmpI] );
- for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
- {
- for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
- {
- multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
- }
- }
-
- double projectionLength ( 0.0 );
- double currentSecondTerm ( 0.0 );
- double sumOfProjectionLengths ( 0.0 );
- int cnt ( 0 );
- NICE::Vector::const_iterator it = multiplicationResults.begin();
- while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
- {
- projectionLength = ( *it );
- currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
- sumOfProjectionLengths += pow ( projectionLength, 2 );
-
- it++;
- cnt++;
- }
-
-
- double normKStar ( pow ( kStar.normL2 (), 2 ) );
- currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
-
- if ( ( normKStar - sumOfProjectionLengths ) < 0 )
- {
- std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
- }
- predVariance = kSelf - currentSecondTerm;
- }
- void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::SparseVector & x, double & predVariance ) const
- {
- // security check!
- if ( ikmsum->getNumberOfModels() == 0 )
- {
- fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
- }
-
- Timer t;
- // t.start();
- // ---------------- compute the first term --------------------
- double kSelf ( 0.0 );
- for ( NICE::SparseVector::const_iterator it = x.begin(); it != x.end(); it++ )
- {
- kSelf += pf->f ( 0, it->second );
- // if weighted dimensions:
- //kSelf += pf->f(it->first,it->second);
- }
- // ---------------- compute the second term --------------------
- // t.stop();
- // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
- // t.start();
- NICE::Vector kStar;
- fmk->hikComputeKernelVector ( x, kStar );
- // t.stop();
- // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
- //
-
- //now run the ILS method
- NICE::Vector diagonalElements;
- ikmsum->getDiagonalElements ( diagonalElements );
- // t.start();
- // init simple jacobi pre-conditioning
- ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
- //perform pre-conditioning
- if ( linsolver_cg != NULL )
- linsolver_cg->setJacobiPreconditioner ( diagonalElements );
-
- NICE::Vector beta;
-
- /** About finding a good initial solution (see also GPLikelihoodApproximation)
- * K~ = K + sigma^2 I
- *
- * K~ \approx lambda_max v v^T
- * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
- * => \lambda_max v^T alpha = v^T k_*
- * => alpha = k_* / lambda_max could be a good initial start
- * If we put everything in the first equation this gives us
- * v = k_*
- * This reduces the number of iterations by 5 or 8
- */
- beta = (kStar * (1.0 / eigenMax[0]) );
- /* t.stop();
- std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
-
- t.start();*/
- // t.start();
- linsolver->solveLin ( *ikmsum, kStar, beta );
- // t.stop();
- // t.stop();
- // t.stop();
- // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
- beta *= kStar;
-
- double currentSecondTerm( beta.Sum() );
- predVariance = kSelf - currentSecondTerm;
- }
- //////////////////////////////////////////
- // variance computation: non-sparse inputs
- //////////////////////////////////////////
-
- void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateRough ( const NICE::Vector & x, double & predVariance ) const
- {
- // security check!
- if ( pf == NULL )
- fthrow ( Exception, "pf is NULL...have you prepared the uncertainty prediction? Aborting..." );
-
- // ---------------- compute the first term --------------------
- double kSelf ( 0.0 );
- int dim ( 0 );
- for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
- {
- kSelf += pf->f ( 0, *it );
- // if weighted dimensions:
- //kSelf += pf->f(dim,*it);
- }
-
- // ---------------- compute the approximation of the second term --------------------
- double normKStar;
- if ( q != NULL )
- {
- if ( precomputedTForVarEst == NULL )
- {
- fthrow ( Exception, "The precomputed LUT for uncertainty prediction is NULL...have you prepared the uncertainty prediction? Aborting..." );
- }
- fmk->hikComputeKVNApproximationFast ( precomputedTForVarEst, *q, x, normKStar );
- }
- else
- {
- if ( precomputedAForVarEst.size () == 0 )
- {
- fthrow ( Exception, "The precomputedAForVarEst is empty...have you trained this classifer? Aborting..." );
- }
- fmk->hikComputeKVNApproximation ( precomputedAForVarEst, x, normKStar, pf );
- }
- predVariance = kSelf - ( 1.0 / eigenMax[0] )* normKStar;
- }
- void FMKGPHyperparameterOptimization::computePredictiveVarianceApproximateFine ( const NICE::Vector & x, double & predVariance ) const
- {
- // security check!
- if ( eigenMaxVectors.rows() == 0 )
- {
- fthrow ( Exception, "eigenMaxVectors is empty...have you trained this classifer? Aborting..." );
- }
-
- // ---------------- compute the first term --------------------
- // Timer t;
- // t.start();
- double kSelf ( 0.0 );
- int dim ( 0 );
- for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
- {
- kSelf += pf->f ( 0, *it );
- // if weighted dimensions:
- //kSelf += pf->f(dim,*it);
- }
- // ---------------- compute the approximation of the second term --------------------
- // t.stop();
- // std::cerr << "ApproxFine -- time for first term: " << t.getLast() << std::endl;
- // t.start();
- NICE::Vector kStar;
- fmk->hikComputeKernelVector ( x, kStar );
- /* t.stop();
- std::cerr << "ApproxFine -- time for kernel vector: " << t.getLast() << std::endl;*/
-
- // NICE::Vector multiplicationResults; // will contain nrOfEigenvaluesToConsiderForVarApprox many entries
- // multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
- NICE::Vector multiplicationResults( nrOfEigenvaluesToConsiderForVarApprox-1, 0.0 );
- //ok, there seems to be a nasty thing in computing multiplicationResults.multiply ( *eigenMaxVectorIt, kStar, true/* transpose */ );
- //wherefor it takes aeons...
- //so we compute it by ourselves
-
-
- // for ( uint tmpI = 0; tmpI < kStar.size(); tmpI++)
- NICE::Matrix::const_iterator eigenVecIt = eigenMaxVectors.begin();
- // double kStarI ( kStar[tmpI] );
- for ( int tmpJ = 0; tmpJ < nrOfEigenvaluesToConsiderForVarApprox-1; tmpJ++)
- {
- for ( NICE::Vector::const_iterator kStarIt = kStar.begin(); kStarIt != kStar.end(); kStarIt++,eigenVecIt++)
- {
- multiplicationResults[tmpJ] += (*kStarIt) * (*eigenVecIt);//eigenMaxVectors(tmpI,tmpJ);
- }
- }
- double projectionLength ( 0.0 );
- double currentSecondTerm ( 0.0 );
- double sumOfProjectionLengths ( 0.0 );
- int cnt ( 0 );
- NICE::Vector::const_iterator it = multiplicationResults.begin();
- while ( cnt < ( nrOfEigenvaluesToConsiderForVarApprox - 1 ) )
- {
- projectionLength = ( *it );
- currentSecondTerm += ( 1.0 / eigenMax[cnt] ) * pow ( projectionLength, 2 );
- sumOfProjectionLengths += pow ( projectionLength, 2 );
-
- it++;
- cnt++;
- }
-
-
- double normKStar ( pow ( kStar.normL2 (), 2 ) );
- currentSecondTerm += ( 1.0 / eigenMax[nrOfEigenvaluesToConsiderForVarApprox-1] ) * ( normKStar - sumOfProjectionLengths );
-
- if ( ( normKStar - sumOfProjectionLengths ) < 0 )
- {
- std::cerr << "Attention: normKStar - sumOfProjectionLengths is smaller than zero -- strange!" << std::endl;
- }
- predVariance = kSelf - currentSecondTerm;
- }
- void FMKGPHyperparameterOptimization::computePredictiveVarianceExact ( const NICE::Vector & x, double & predVariance ) const
- {
- if ( ikmsum->getNumberOfModels() == 0 )
- {
- fthrow ( Exception, "ikmsum is empty... have you trained this classifer? Aborting..." );
- }
-
- Timer t;
- // t.start();
- // ---------------- compute the first term --------------------
- double kSelf ( 0.0 );
- int dim ( 0 );
- for ( NICE::Vector::const_iterator it = x.begin(); it != x.end(); it++, dim++ )
- {
- kSelf += pf->f ( 0, *it );
- // if weighted dimensions:
- //kSelf += pf->f(dim,*it);
- }
- // ---------------- compute the second term --------------------
- // t.stop();
- // std::cerr << "ApproxExact -- time for first term: " << t.getLast() << std::endl;
- // t.start();
- NICE::Vector kStar;
- fmk->hikComputeKernelVector ( x, kStar );
- // t.stop();
- // std::cerr << "ApproxExact -- time for kernel vector: " << t.getLast() << std::endl;
- //
- //now run the ILS method
- NICE::Vector diagonalElements;
- ikmsum->getDiagonalElements ( diagonalElements );
- // t.start();
- // init simple jacobi pre-conditioning
- ILSConjugateGradients *linsolver_cg = dynamic_cast<ILSConjugateGradients *> ( linsolver );
- //perform pre-conditioning
- if ( linsolver_cg != NULL )
- linsolver_cg->setJacobiPreconditioner ( diagonalElements );
-
- NICE::Vector beta;
-
- /** About finding a good initial solution (see also GPLikelihoodApproximation)
- * K~ = K + sigma^2 I
- *
- * K~ \approx lambda_max v v^T
- * \lambda_max v v^T * alpha = k_* | multiply with v^T from left
- * => \lambda_max v^T alpha = v^T k_*
- * => alpha = k_* / lambda_max could be a good initial start
- * If we put everything in the first equation this gives us
- * v = k_*
- * This reduces the number of iterations by 5 or 8
- */
- beta = (kStar * (1.0 / eigenMax[0]) );
- /* t.stop();
- std::cerr << "ApproxExact -- time for preconditioning etc: " << t.getLast() << std::endl;
-
- t.start();*/
- // t.start();
- linsolver->solveLin ( *ikmsum, kStar, beta );
- // t.stop();
- // t.stop();
- // t.stop();
- // std::cerr << "ApproxExact -- time for lin solve: " << t.getLast() << std::endl;
- beta *= kStar;
-
- double currentSecondTerm( beta.Sum() );
- predVariance = kSelf - currentSecondTerm;
- }
- ///////////////////// INTERFACE PERSISTENT /////////////////////
- // interface specific methods for store and restore
- ///////////////////// INTERFACE PERSISTENT /////////////////////
- void FMKGPHyperparameterOptimization::restore ( std::istream & is, int format )
- {
- bool b_restoreVerbose ( false );
- #ifdef B_RESTOREVERBOSE
- b_restoreVerbose = true;
- #endif
- if ( is.good() )
- {
- if ( b_restoreVerbose )
- std::cerr << " in FMKGP restore" << std::endl;
-
- std::string tmp;
- is >> tmp; //class name
-
- if ( ! this->isStartTag( tmp, "FMKGPHyperparameterOptimization" ) )
- {
- std::cerr << " WARNING - attempt to restore FMKGPHyperparameterOptimization, but start flag " << tmp << " does not match! Aborting... " << std::endl;
- throw;
- }
- if (fmk != NULL)
- {
- delete fmk;
- fmk = NULL;
- }
-
- if ( ikmsum != NULL )
- {
- delete ikmsum;
- }
- ikmsum = new IKMLinearCombination ();
- if ( b_restoreVerbose )
- std::cerr << "ikmsum object created" << std::endl;
-
-
- is.precision ( numeric_limits<double>::digits10 + 1 );
-
-
- bool b_endOfBlock ( false ) ;
-
- while ( !b_endOfBlock )
- {
- is >> tmp; // start of block
-
- if ( this->isEndTag( tmp, "FMKGPHyperparameterOptimization" ) )
- {
- b_endOfBlock = true;
- continue;
- }
-
- tmp = this->removeStartTag ( tmp );
-
- if ( b_restoreVerbose )
- std::cerr << " currently restore section " << tmp << " in FMKGPHyperparameterOptimization" << std::endl;
-
- if ( tmp.compare("fmk") == 0 )
- {
- fmk = new FastMinKernel;
- fmk->restore( is, format );
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("precomputedA") == 0 )
- {
- is >> tmp; // size
- int preCompSize ( 0 );
- is >> preCompSize;
- precomputedA.clear();
- if ( b_restoreVerbose )
- std::cerr << "restore precomputedA with size: " << preCompSize << std::endl;
- for ( int i = 0; i < preCompSize; i++ )
- {
- int nr;
- is >> nr;
- PrecomputedType pct;
- pct.setIoUntilEndOfFile ( false );
- pct.restore ( is, format );
- precomputedA.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
- }
-
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("precomputedB") == 0 )
- {
- is >> tmp; // size
- int preCompSize ( 0 );
- is >> preCompSize;
- precomputedB.clear();
- if ( b_restoreVerbose )
- std::cerr << "restore precomputedB with size: " << preCompSize << std::endl;
- for ( int i = 0; i < preCompSize; i++ )
- {
- int nr;
- is >> nr;
- PrecomputedType pct;
- pct.setIoUntilEndOfFile ( false );
- pct.restore ( is, format );
- precomputedB.insert ( std::pair<int, PrecomputedType> ( nr, pct ) );
- }
-
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("precomputedT") == 0 )
- {
- is >> tmp; // size
- int precomputedTSize ( 0 );
- is >> precomputedTSize;
- precomputedT.clear();
-
- if ( b_restoreVerbose )
- std::cerr << "restore precomputedT with size: " << precomputedTSize << std::endl;
- if ( precomputedTSize > 0 )
- {
- if ( b_restoreVerbose )
- std::cerr << " restore precomputedT" << std::endl;
- is >> tmp;
- int sizeOfLUT;
- is >> sizeOfLUT;
-
- for (int i = 0; i < precomputedTSize; i++)
- {
- is >> tmp;
- int index;
- is >> index;
- double * array = new double [ sizeOfLUT];
- for ( int i = 0; i < sizeOfLUT; i++ )
- {
- is >> array[i];
- }
- precomputedT.insert ( std::pair<int, double*> ( index, array ) );
- }
- }
- else
- {
- if ( b_restoreVerbose )
- std::cerr << " skip restoring precomputedT" << std::endl;
- }
-
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("precomputedAForVarEst") == 0 )
- {
- int sizeOfAForVarEst;
- is >> sizeOfAForVarEst;
-
- if ( b_restoreVerbose )
- std::cerr << "restore precomputedAForVarEst with size: " << sizeOfAForVarEst << std::endl;
-
- if (sizeOfAForVarEst > 0)
- {
- precomputedAForVarEst.clear();
-
- precomputedAForVarEst.setIoUntilEndOfFile ( false );
- precomputedAForVarEst.restore ( is, format );
- }
-
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("precomputedTForVarEst") == 0 )
- {
- std::string isNull;
- is >> isNull; // NOTNULL or NULL
- if ( b_restoreVerbose )
- std::cerr << "content of isNull: " << isNull << std::endl;
- if (isNull.compare("NOTNULL") == 0)
- {
- if ( b_restoreVerbose )
- std::cerr << "restore precomputedTForVarEst" << std::endl;
-
- int sizeOfLUT;
- is >> sizeOfLUT;
- precomputedTForVarEst = new double [ sizeOfLUT ];
- for ( int i = 0; i < sizeOfLUT; i++ )
- {
- is >> precomputedTForVarEst[i];
- }
- }
- else
- {
- if ( b_restoreVerbose )
- std::cerr << "skip restoring of precomputedTForVarEst" << std::endl;
- if (precomputedTForVarEst != NULL)
- delete precomputedTForVarEst;
- }
-
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("eigenMax") == 0 )
- {
- is >> eigenMax;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("eigenMaxVectors") == 0 )
- {
- is >> eigenMaxVectors;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("ikmsum") == 0 )
- {
- bool b_endOfBlock ( false ) ;
-
- while ( !b_endOfBlock )
- {
- is >> tmp; // start of block
-
- if ( this->isEndTag( tmp, "ikmsum" ) )
- {
- b_endOfBlock = true;
- continue;
- }
-
- tmp = this->removeStartTag ( tmp );
- if ( tmp.compare("IKMNoise") == 0 )
- {
- IKMNoise * ikmnoise = new IKMNoise ();
- ikmnoise->restore ( is, format );
-
- if ( b_restoreVerbose )
- std::cerr << " add ikmnoise to ikmsum object " << std::endl;
- ikmsum->addModel ( ikmnoise );
- }
- else
- {
- std::cerr << "WARNING -- unexpected ikmsum object -- " << tmp << " -- for restoration... aborting" << std::endl;
- throw;
- }
- }
- }
- else if ( tmp.compare("binaryLabelPositive") == 0 )
- {
- is >> binaryLabelPositive;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("binaryLabelNegative") == 0 )
- {
- is >> binaryLabelNegative;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("labels") == 0 )
- {
- is >> labels;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else if ( tmp.compare("b_usePreviousAlphas") == 0 )
- {
- is >> b_usePreviousAlphas;
- is >> tmp; // end of block
- tmp = this->removeEndTag ( tmp );
- }
- else
- {
- std::cerr << "WARNING -- unexpected FMKGPHyper object -- " << tmp << " -- for restoration... aborting" << std::endl;
- throw;
- }
-
-
- }
-
- //NOTE are there any more models you added? then add them here respectively in the correct order
- //.....
- //the last one is the GHIK - which we do not have to restore, but simply reset it
- if ( b_restoreVerbose )
- std::cerr << " add GMHIKernel" << std::endl;
- ikmsum->addModel ( new GMHIKernel ( fmk, this->pf, this->q ) );
-
- if ( b_restoreVerbose )
- std::cerr << " restore positive and negative label" << std::endl;
-
- knownClasses.clear();
-
- if ( b_restoreVerbose )
- std::cerr << " fill known classes object " << std::endl;
-
- if ( precomputedA.size() == 1)
- {
- knownClasses.insert( binaryLabelPositive );
- knownClasses.insert( binaryLabelNegative );
- if ( b_restoreVerbose )
- std::cerr << " binary setting - added corresp. two class numbers" << std::endl;
- }
- else
- {
- for ( std::map<int, PrecomputedType>::const_iterator itA = precomputedA.begin(); itA != precomputedA.end(); itA++)
- knownClasses.insert ( itA->first );
- if ( b_restoreVerbose )
- std::cerr << " multi class setting - added corresp. multiple class numbers" << std::endl;
- }
- }
- else
- {
- std::cerr << "InStream not initialized - restoring not possible!" << std::endl;
- throw;
- }
- }
- void FMKGPHyperparameterOptimization::store ( std::ostream & os, int format ) const
- {
- if ( os.good() )
- {
- // show starting point
- os << this->createStartTag( "FMKGPHyperparameterOptimization" ) << std::endl;
-
- os << this->createStartTag( "fmk" ) << std::endl;
- fmk->store ( os, format );
- os << this->createEndTag( "fmk" ) << std::endl;
- os.precision ( numeric_limits<double>::digits10 + 1 );
- //we only have to store the things we computed, since the remaining settings come with the config file afterwards
-
- os << this->createStartTag( "precomputedA" ) << std::endl;
- os << "size: " << precomputedA.size() << std::endl;
- std::map< int, PrecomputedType >::const_iterator preCompIt = precomputedA.begin();
- for ( uint i = 0; i < precomputedA.size(); i++ )
- {
- os << preCompIt->first << std::endl;
- ( preCompIt->second ).store ( os, format );
- preCompIt++;
- }
- os << this->createEndTag( "precomputedA" ) << std::endl;
-
-
- os << this->createStartTag( "precomputedB" ) << std::endl;
- os << "size: " << precomputedB.size() << std::endl;
- preCompIt = precomputedB.begin();
- for ( uint i = 0; i < precomputedB.size(); i++ )
- {
- os << preCompIt->first << std::endl;
- ( preCompIt->second ).store ( os, format );
- preCompIt++;
- }
- os << this->createEndTag( "precomputedB" ) << std::endl;
-
-
-
- os << this->createStartTag( "precomputedT" ) << std::endl;
- os << "size: " << precomputedT.size() << std::endl;
- if ( precomputedT.size() > 0 )
- {
- int sizeOfLUT ( 0 );
- if ( q != NULL )
- sizeOfLUT = q->size() * this->fmk->get_d();
- os << "SizeOfLUTs: " << sizeOfLUT << std::endl;
- for ( std::map< int, double * >::const_iterator it = precomputedT.begin(); it != precomputedT.end(); it++ )
- {
- os << "index: " << it->first << std::endl;
- for ( int i = 0; i < sizeOfLUT; i++ )
- {
- os << ( it->second ) [i] << " ";
- }
- os << std::endl;
- }
- }
- os << this->createEndTag( "precomputedT" ) << std::endl;
- //now store the things needed for the variance estimation
-
- os << this->createStartTag( "precomputedAForVarEst" ) << std::endl;
- os << precomputedAForVarEst.size() << std::endl;
-
- if (precomputedAForVarEst.size() > 0)
- {
- precomputedAForVarEst.store ( os, format );
- os << std::endl;
- }
- os << this->createEndTag( "precomputedAForVarEst" ) << std::endl;
-
-
- os << this->createStartTag( "precomputedTForVarEst" ) << std::endl;
- if ( precomputedTForVarEst != NULL )
- {
- os << "NOTNULL" << std::endl;
- int sizeOfLUT ( 0 );
- if ( q != NULL )
- sizeOfLUT = q->size() * this->fmk->get_d();
-
- os << sizeOfLUT << std::endl;
- for ( int i = 0; i < sizeOfLUT; i++ )
- {
- os << precomputedTForVarEst[i] << " ";
- }
- os << std::endl;
- }
- else
- {
- os << "NULL" << std::endl;
- }
- os << this->createEndTag( "precomputedTForVarEst" ) << std::endl;
-
- //store the eigenvalues and eigenvectors
- os << this->createStartTag( "eigenMax" ) << std::endl;
- os << eigenMax << std::endl;
- os << this->createEndTag( "eigenMax" ) << std::endl;
- os << this->createStartTag( "eigenMaxVectors" ) << std::endl;
- os << eigenMaxVectors << std::endl;
- os << this->createEndTag( "eigenMaxVectors" ) << std::endl;
- os << this->createStartTag( "ikmsum" ) << std::endl;
- for ( int j = 0; j < ikmsum->getNumberOfModels() - 1; j++ )
- {
- ( ikmsum->getModel ( j ) )->store ( os, format );
- }
- os << this->createEndTag( "ikmsum" ) << std::endl;
-
- //store the class numbers for binary settings (if mc-settings, these values will be negative by default)
- os << this->createStartTag( "binaryLabelPositive" ) << std::endl;
- os << binaryLabelPositive << std::endl;
- os << this->createEndTag( "binaryLabelPositive" ) << std::endl;
-
- os << this->createStartTag( "binaryLabelNegative" ) << std::endl;
- os << binaryLabelNegative << std::endl;
- os << this->createEndTag( "binaryLabelNegative" ) << std::endl;
-
-
- os << this->createStartTag( "labels" ) << std::endl;
- os << labels << std::endl;
- os << this->createEndTag( "labels" ) << std::endl;
-
-
- os << this->createStartTag( "b_usePreviousAlphas" ) << std::endl;
- os << b_usePreviousAlphas << std::endl;
- os << this->createEndTag( "b_usePreviousAlphas" ) << std::endl;
-
-
- // done
- os << this->createEndTag( "FMKGPHyperparameterOptimization" ) << std::endl;
- }
- else
- {
- std::cerr << "OutStream not initialized - storing not possible!" << std::endl;
- }
- }
- void FMKGPHyperparameterOptimization::clear ( ) {};
- ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
- // interface specific methods for incremental extensions
- ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
- void FMKGPHyperparameterOptimization::addExample( const NICE::SparseVector * example,
- const double & label,
- const bool & performOptimizationAfterIncrement
- )
- {
-
- std::cerr << " --- FMKGPHyperparameterOptimization::addExample --- " << std::endl;
- std::set< int > newClasses;
-
- this->labels.append ( label );
- //have we seen this class already?
- if ( this->knownClasses.find( label ) == this->knownClasses.end() )
- {
- this->knownClasses.insert( label );
- newClasses.insert( label );
- }
- std::cerr << "call addExample of fmk object " << std::endl;
- // add the new example to our data structure
- // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
- NICE::Timer t;
- t.start();
- this->fmk->addExample ( example, pf );
- t.stop();
- if ( this->verboseTime)
- std::cerr << "Time used for adding the data to the fmk object: " << t.getLast() << std::endl;
- //TODO update the matrix for variance computations as well!!!
-
- // add examples to all implicite kernel matrices we currently use
- this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
-
- std::cerr << "call updateAfterSingleIncrement " << std::endl;
-
- // update the corresponding matrices A, B and lookup tables T
- // optional: do the optimization again using the previously known solutions as initialization
- this->updateAfterSingleIncrement ( *example, newClasses, performOptimizationAfterIncrement );
-
- //clean up
- newClasses.clear();
-
- std::cerr << " --- FMKGPHyperparameterOptimization::addExample done --- " << std::endl;
- }
- void FMKGPHyperparameterOptimization::addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
- const NICE::Vector & newLabels,
- const bool & performOptimizationAfterIncrement
- )
- {
- // // // //TODO check whether this set is actually needed
- // // // std::set< int > newClasses;
- // // //
- // // // if (this->knownClasses.size() == 1) //binary setting
- // // // {
- // // // int oldSize ( this->labels.size() );
- // // // this->labels.resize ( this->labels.size() + newLabels.size() );
- // // // for ( uint i = 0; i < newLabels.size(); i++ )
- // // // {
- // // // this->labels[i+oldSize] = newLabels[i];
- // // // //have we seen this class already?
- // // // if ( (newLabels[i] != this->binaryLabelPositive) && (newLabels[i] != this->binaryLabelNegative) )
- // // // {
- // // // fthrow(Exception, "Binary setting does not allow adding new classes so far");
- // // // // knownClasses.insert( newLabels[i] );
- // // // // newClasses.insert( newLabels[i] );
- // // // }
- // // // }
- // // // }
- // // // else //multi-class setting
- // // // {
- // // // int oldSize ( this->labels.size() );
- // // // this->labels.resize ( this->labels.size() + newLabels.size() );
- // // // for ( uint i = 0; i < newLabels.size(); i++ )
- // // // {
- // // // this->labels[i+oldSize] = newLabels[i];
- // // // //have we seen this class already?
- // // // if (knownClasses.find( newLabels[i] ) == knownClasses.end() )
- // // // {
- // // // knownClasses.insert( newLabels[i] );
- // // // newClasses.insert( newLabels[i] );
- // // // }
- // // // }
- // // // }
- // // //
- // // //
- // // //
- // // // // add the new example to our data structure
- // // // // It is necessary to do this already here and not lateron for internal reasons (see GMHIKernel for more details)
- // // // Timer t;
- // // // t.start();
- // // //
- // // // fmk->addMultipleExamples ( newExamples, pf );
- // // // t.stop();
- // // // if (verboseTime)
- // // // std::cerr << "Time used for adding the data to the fmk object: " << t.getLast() << std::endl;
- // // //
- // // // // add examples to all implicite kernel matrices we currently use
- // // // this->ikmsum->addExample ( example, label, performOptimizationAfterIncrement );
- // // //
- // // // Timer tVar;
- // // // tVar.start();
- // // // //do we need to update our matrices?
- // // // if ( precomputedAForVarEst.size() != 0)
- // // // {
- // // // std::cerr << "update the variance matrices " << std::endl;
- // // // //this computes everything from the scratch
- // // // this->prepareVarianceApproximation();
- // // // //this would perform a more sophisticated update
- // // // //unfortunately, there is a bug somewhere
- // // // //TODO fixme!
- // // // // std::cerr << "update the LUTs needed for variance computation" << std::endl;
- // // // // for ( std::vector<const NICE::SparseVector*>::const_iterator exampleIt = newExamples.begin(); exampleIt != newExamples.end(); exampleIt++ )
- // // // // {
- // // // // std::cerr << "new example: " << std::endl;
- // // // // (**exampleIt).store(std::cerr);
- // // // // std::cerr << "now update the LUT for var est" << std::endl;
- // // // // fmk->updatePreparationForKVNApproximation( **exampleIt, precomputedAForVarEst, pf );
- // // // // if ( q != NULL )
- // // // // {
- // // // // fmk->updateLookupTableForKVNApproximation( **exampleIt, precomputedTForVarEst, *q, pf );
- // // // // }
- // // // // }
- // // // // std::cerr << "update of LUTs for variance compuation done" << std::endl;
- // // // }
- // // // tVar.stop();
- // // // if (verboseTime)
- // // // std::cerr << "Time used for computing the Variance Matrix and LUT: " << tVar.getLast() << std::endl;
- // // //
- // // //
- // // //
- // // // // update the corresponding matrices A, B and lookup tables T
- // // // // optional: do the optimization again using the previously known solutions as initialization
- // // // updateAfterMultipleIncrements ( newExamples, newClasses, performOptimizationAfterIncrement );
- // // //
- // // // //clean up
- // // // newClasses.clear();
-
- }
|