FMKGPHyperparameterOptimization.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /**
  2. * @file FMKGPHyperparameterOptimization.h
  3. * @brief Heart of the framework to set up everything, perform optimization, classification, and variance prediction (Interface)
  4. * @author Alexander Freytag, Erik Rodner
  5. * @date 01-02-2012 (dd-mm-yyyy)
  6. */
  7. #ifndef _NICE_FMKGPHYPERPARAMETEROPTIMIZATIONINCLUDE
  8. #define _NICE_FMKGPHYPERPARAMETEROPTIMIZATIONINCLUDE
  9. // STL includes
  10. #include <vector>
  11. #include <set>
  12. #include <map>
  13. // NICE-core includes
  14. #include <core/algebra/EigValues.h>
  15. #include <core/algebra/IterativeLinearSolver.h>
  16. #include <core/basics/Config.h>
  17. #include <core/basics/Persistent.h>
  18. #include <core/vector/VectorT.h>
  19. #ifdef NICE_USELIB_MATIO
  20. #include <core/matlabAccess/MatFileIO.h>
  21. #endif
  22. // gp-hik-core includes
  23. #include "gp-hik-core/FastMinKernel.h"
  24. #include "gp-hik-core/GPLikelihoodApprox.h"
  25. #include "gp-hik-core/IKMLinearCombination.h"
  26. #include "gp-hik-core/OnlineLearnable.h"
  27. #include "gp-hik-core/Quantization.h"
  28. #include "gp-hik-core/parameterizedFunctions/ParameterizedFunction.h"
  29. namespace NICE {
  30. /**
  31. * @class FMKGPHyperparameterOptimization
  32. * @brief Heart of the framework to set up everything, perform optimization, classification, and variance prediction
  33. * @author Alexander Freytag, Erik Rodner
  34. */
  35. class FMKGPHyperparameterOptimization : public NICE::Persistent, public NICE::OnlineLearnable
  36. {
  37. protected:
  38. /////////////////////////
  39. /////////////////////////
  40. // PROTECTED VARIABLES //
  41. /////////////////////////
  42. /////////////////////////
  43. ///////////////////////////////////
  44. // output/debug related settings //
  45. ///////////////////////////////////
  46. /** verbose flag */
  47. bool b_verbose;
  48. /** verbose flag for time measurement outputs */
  49. bool b_verboseTime;
  50. /** debug flag for several outputs useful for debugging*/
  51. bool b_debug;
  52. //////////////////////////////////////
  53. // classification related variables //
  54. //////////////////////////////////////
  55. /** per default, we perform classification, if not stated otherwise */
  56. bool b_performRegression;
  57. /** object storing sorted data and providing fast hik methods */
  58. NICE::FastMinKernel *fmk;
  59. /** object performing feature quantization */
  60. NICE::Quantization *q;
  61. /** upper bound for hyper parameters (ParameterizedFunction) to optimize */
  62. double d_parameterUpperBound;
  63. /** lower bound for hyper parameters (ParameterizedFunction) to optimize */
  64. double d_parameterLowerBound;
  65. /** the parameterized function we use within the minimum kernel */
  66. NICE::ParameterizedFunction *pf;
  67. /** Simple type definition for precomputation matrices used for fast classification */
  68. typedef VVector PrecomputedType;
  69. /** precomputed arrays A (1 per class) needed for classification without quantization */
  70. std::map< int, PrecomputedType > precomputedA;
  71. /** precomputed arrays B (1 per class) needed for classification without quantization */
  72. std::map< int, PrecomputedType > precomputedB;
  73. /** precomputed LUTs (1 per class) needed for classification with quantization */
  74. std::map< int, double * > precomputedT;
  75. //! storing the labels is needed for Incremental Learning (re-optimization)
  76. NICE::Vector labels;
  77. //! store the class number of the positive class (i.e., larger class no), only used in binary settings
  78. int i_binaryLabelPositive;
  79. //! store the class number of the negative class (i.e., smaller class no), only used in binary settings
  80. int i_binaryLabelNegative;
  81. //! contains all class numbers of the currently known classes
  82. std::set<int> knownClasses;
  83. //! container for multiple kernel matrices (e.g., a data-containing kernel matrix (GMHIKernel) and a noise matrix (IKMNoise) )
  84. NICE::IKMLinearCombination * ikmsum;
  85. //////////////////////////////////////////////
  86. // Iterative Linear Solver //
  87. //////////////////////////////////////////////
  88. /** method for solving linear equation systems - needed to compute K^-1 \times y */
  89. IterativeLinearSolver *linsolver;
  90. /** Max. number of iterations the iterative linear solver is allowed to run */
  91. int ils_max_iterations;
  92. /////////////////////////////////////
  93. // optimization related parameters //
  94. /////////////////////////////////////
  95. enum OPTIMIZATIONTECHNIQUE{
  96. OPT_GREEDY = 0,
  97. OPT_DOWNHILLSIMPLEX,
  98. OPT_NONE
  99. };
  100. /** specify the optimization method used (see corresponding enum) */
  101. OPTIMIZATIONTECHNIQUE optimizationMethod;
  102. //! whether or not to optimize noise with the GP likelihood
  103. bool optimizeNoise;
  104. // specific to greedy optimization
  105. /** step size used in grid based greedy optimization technique */
  106. double parameterStepSize;
  107. // specific to downhill simplex optimization
  108. /** Max. number of iterations the downhill simplex optimizer is allowed to run */
  109. int downhillSimplexMaxIterations;
  110. /** Max. time the downhill simplex optimizer is allowed to run */
  111. double downhillSimplexTimeLimit;
  112. /** Max. number of iterations the iterative linear solver is allowed to run */
  113. double downhillSimplexParamTol;
  114. //////////////////////////////////////////////
  115. // likelihood computation related variables //
  116. //////////////////////////////////////////////
  117. /** whether to compute the exact likelihood by computing the exact kernel matrix (not recommended - only for debugging/comparison purpose) */
  118. bool verifyApproximation;
  119. /** method computing eigenvalues and eigenvectors*/
  120. NICE::EigValues *eig;
  121. /** number of Eigenvalues to consider in the approximation of |K|_F used for approximating the likelihood */
  122. int nrOfEigenvaluesToConsider;
  123. //! k largest eigenvalues of the kernel matrix (k == nrOfEigenvaluesToConsider)
  124. NICE::Vector eigenMax;
  125. //! eigenvectors corresponding to k largest eigenvalues (k == nrOfEigenvaluesToConsider) -- format: nxk
  126. NICE::Matrix eigenMaxVectors;
  127. ////////////////////////////////////////////
  128. // variance computation related variables //
  129. ////////////////////////////////////////////
  130. /** number of Eigenvalues to consider in the fine approximation of the predictive variance (fine approximation only) */
  131. int nrOfEigenvaluesToConsiderForVarApprox;
  132. /** precomputed array needed for rough variance approximation without quantization */
  133. PrecomputedType precomputedAForVarEst;
  134. /** precomputed LUT needed for rough variance approximation with quantization */
  135. double * precomputedTForVarEst;
  136. /////////////////////////////////////////////////////
  137. // online / incremental learning related variables //
  138. /////////////////////////////////////////////////////
  139. /** whether or not to use previous alpha solutions as initialization after adding new examples*/
  140. bool b_usePreviousAlphas;
  141. //! store alpha vectors for good initializations in the IL setting, if activated
  142. std::map<int, NICE::Vector> previousAlphas;
  143. /////////////////////////
  144. /////////////////////////
  145. // PROTECTED METHODS //
  146. /////////////////////////
  147. /////////////////////////
  148. /**
  149. * @brief calculate binary label vectors using a multi-class label vector
  150. * @author Alexander Freytag
  151. */
  152. int prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses);
  153. /**
  154. * @brief prepare the GPLike object for given binary labels and already given ikmsum-object
  155. * @author Alexander Freytag
  156. */
  157. inline void setupGPLikelihoodApprox( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize);
  158. /**
  159. * @brief update eigenvectors and eigenvalues for given ikmsum-objects and a method to compute eigenvalues
  160. * @author Alexander Freytag
  161. */
  162. inline void updateEigenDecomposition( const int & i_noEigenValues );
  163. /**
  164. * @brief core of the optimize-functions
  165. * @author Alexander Freytag
  166. */
  167. inline void performOptimization( GPLikelihoodApprox & gplike, const uint & parameterVectorSize);
  168. /**
  169. * @brief apply the optimized transformation values to the underlying features
  170. * @author Alexander Freytag
  171. */
  172. inline void transformFeaturesWithOptimalParameters(const GPLikelihoodApprox & gplike, const uint & parameterVectorSize);
  173. /**
  174. * @brief build the resulting matrices A and B as well as lookup tables T for fast evaluations using the optimized parameter settings
  175. * @author Alexander Freytag
  176. */
  177. inline void computeMatricesAndLUTs( const GPLikelihoodApprox & gplike);
  178. /**
  179. * @brief Update matrices (A, B, LUTs) and optionally find optimal parameters after adding (a) new example(s).
  180. * @author Alexander Freytag
  181. */
  182. void updateAfterIncrement (
  183. const std::set<int> newClasses,
  184. const bool & performOptimizationAfterIncrement = false
  185. );
  186. public:
  187. /**
  188. * @brief default constructor
  189. * @author Alexander Freytag
  190. */
  191. FMKGPHyperparameterOptimization( );
  192. /**
  193. * @brief simple constructor
  194. * @author Alexander Freytag
  195. * @param b_performRegression
  196. */
  197. FMKGPHyperparameterOptimization( const bool & _performRegression );
  198. /**
  199. * @brief recommended constructor, only calls this->initialize with same input arguments
  200. * @author Alexander Freytag
  201. * @param conf
  202. * @param confSection
  203. *
  204. */
  205. FMKGPHyperparameterOptimization( const Config *_conf,
  206. const std::string & _confSection = "FMKGPHyperparameterOptimization"
  207. );
  208. /**
  209. * @brief recommended constructor, only calls this->initialize with same input arguments
  210. * @author Alexander Freytag
  211. *
  212. * @param conf
  213. * @param fmk pointer to a pre-initialized structure (will be deleted)
  214. * @param confSection
  215. */
  216. FMKGPHyperparameterOptimization( const Config *_conf,
  217. FastMinKernel *_fmk,
  218. const std::string & _confSection = "FMKGPHyperparameterOptimization"
  219. );
  220. /**
  221. * @brief standard destructor
  222. * @author Alexander Freytag
  223. */
  224. virtual ~FMKGPHyperparameterOptimization();
  225. /**
  226. * @brief Set variables and parameters to default or config-specified values
  227. * @author Alexander Freytag
  228. */
  229. void initFromConfig( const Config *_conf,
  230. const std::string & _confSection = "FMKGPHyperparameterOptimization"
  231. );
  232. ///////////////////// ///////////////////// /////////////////////
  233. // GET / SET
  234. ///////////////////// ///////////////////// /////////////////////
  235. /**
  236. * @brief Set lower bound for hyper parameters to optimize
  237. * @author Alexander Freytag
  238. */
  239. void setParameterUpperBound(const double & _parameterUpperBound);
  240. /**
  241. * @brief Set upper bound for hyper parameters to optimize
  242. * @author Alexander Freytag
  243. */
  244. void setParameterLowerBound(const double & _parameterLowerBound);
  245. /**
  246. * @brief Get the currently known class numbers
  247. * @author Alexander Freytag
  248. */
  249. std::set<int> getKnownClassNumbers ( ) const;
  250. /**
  251. * @brief Change between classification and regression, only allowed if not trained. Otherwise, exceptions will be thrown...
  252. * @author Alexander Freytag
  253. * @date 05-02-2014 (dd-mm-yyyy)
  254. */
  255. void setPerformRegression ( const bool & _performRegression );
  256. /**
  257. * @brief Set the FastMinKernel object. Only allowed if not trained. Otherwise, exceptions will be thrown...
  258. * @author Alexander Freytag
  259. * @date 05-02-2014 (dd-mm-yyyy)
  260. */
  261. void setFastMinKernel ( FastMinKernel *fmk );
  262. /**
  263. * @brief Set the number of EV we considere for variance approximation. Only allowed if not trained. Otherwise, exceptions will be thrown...
  264. * @author Alexander Freytag
  265. * @date 06-02-2014 (dd-mm-yyyy)
  266. */
  267. void setNrOfEigenvaluesToConsiderForVarApprox ( const int & i_nrOfEigenvaluesToConsiderForVarApprox );
  268. ///////////////////// ///////////////////// /////////////////////
  269. // CLASSIFIER STUFF
  270. ///////////////////// ///////////////////// /////////////////////
  271. #ifdef NICE_USELIB_MATIO
  272. /**
  273. * @brief Perform hyperparameter optimization
  274. * @author Alexander Freytag
  275. *
  276. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  277. * @param y label vector (arbitrary), will be converted into a binary label vector
  278. * @param positives set of positive examples (indices)
  279. * @param negatives set of negative examples (indices)
  280. */
  281. void optimizeBinary ( const sparse_t & data, const NICE::Vector & y, const std::set<int> & positives, const std::set<int> & negatives, double noise );
  282. /**
  283. * @brief Perform hyperparameter optimization for GP multi-class or binary problems
  284. * @author Alexander Freytag
  285. *
  286. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  287. * @param y label vector with multi-class labels
  288. * @param examples mapping of example index to new index
  289. */
  290. void optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise );
  291. #endif
  292. /**
  293. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  294. * @author Alexander Freytag
  295. *
  296. * @param y label vector (multi-class as well as binary labels supported)
  297. */
  298. void optimize ( const NICE::Vector & y );
  299. /**
  300. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  301. *
  302. * @param binLabels vector of binary label vectors (1,-1) and corresponding class no.
  303. */
  304. void optimize ( std::map<int, NICE::Vector> & binaryLabels );
  305. /**
  306. * @brief Compute the necessary variables for appxorimations of predictive variance (LUTs), assuming an already initialized fmk object
  307. * @author Alexander Freytag
  308. * @date 11-04-2012 (dd-mm-yyyy)
  309. */
  310. void prepareVarianceApproximationRough();
  311. /**
  312. * @brief Compute the necessary variables for fine appxorimations of predictive variance (EVs), assuming an already initialized fmk object
  313. * @author Alexander Freytag
  314. * @date 11-04-2012 (dd-mm-yyyy)
  315. */
  316. void prepareVarianceApproximationFine();
  317. /**
  318. * @brief classify an example
  319. *
  320. * @param x input example (sparse vector)
  321. * @param scores scores for each class number
  322. *
  323. * @return class number achieving the best score
  324. */
  325. int classify ( const NICE::SparseVector & x, SparseVector & scores ) const;
  326. /**
  327. * @brief classify an example that is given as non-sparse vector
  328. * NOTE: whenever possible, you should use sparse vectors to obtain significantly smaller computation times
  329. *
  330. * @date 18-06-2013 (dd-mm-yyyy)
  331. * @author Alexander Freytag
  332. *
  333. * @param x input example (non-sparse vector)
  334. * @param scores scores for each class number
  335. *
  336. * @return class number achieving the best score
  337. */
  338. int classify ( const NICE::Vector & x, SparseVector & scores ) const;
  339. //////////////////////////////////////////
  340. // variance computation: sparse inputs
  341. //////////////////////////////////////////
  342. /**
  343. * @brief compute predictive variance for a given test example using a rough approximation: k_{**} - k_*^T (K+\sigma I)^{-1} k_* <= k_{**} - |k_*|^2 * 1 / \lambda_max(K + \sigma I), where we approximate |k_*|^2 by neglecting the mixed terms
  344. * @author Alexander Freytag
  345. * @date 10-04-2012 (dd-mm-yyyy)
  346. * @param x input example
  347. * @param predVariance contains the approximation of the predictive variance
  348. *
  349. */
  350. void computePredictiveVarianceApproximateRough(const NICE::SparseVector & x, double & predVariance ) const;
  351. /**
  352. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  353. * @author Alexander Freytag
  354. * @date 18-04-2012 (dd-mm-yyyy)
  355. * @param x input example
  356. * @param predVariance contains the approximation of the predictive variance
  357. *
  358. */
  359. void computePredictiveVarianceApproximateFine(const NICE::SparseVector & x, double & predVariance ) const;
  360. /**
  361. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  362. * @author Alexander Freytag
  363. * @date 10-04-2012 (dd-mm-yyyy)
  364. * @param x input example
  365. * @param predVariance contains the approximation of the predictive variance
  366. *
  367. */
  368. void computePredictiveVarianceExact(const NICE::SparseVector & x, double & predVariance ) const;
  369. //////////////////////////////////////////
  370. // variance computation: non-sparse inputs
  371. //////////////////////////////////////////
  372. /**
  373. * @brief compute predictive variance for a given test example using a rough approximation: k_{**} - k_*^T (K+\sigma I)^{-1} k_* <= k_{**} - |k_*|^2 * 1 / \lambda_max(K + \sigma I), where we approximate |k_*|^2 by neglecting the mixed terms
  374. * @author Alexander Freytag
  375. * @date 19-12-2013 (dd-mm-yyyy)
  376. * @param x input example
  377. * @param predVariance contains the approximation of the predictive variance
  378. *
  379. */
  380. void computePredictiveVarianceApproximateRough(const NICE::Vector & x, double & predVariance ) const;
  381. /**
  382. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  383. * @author Alexander Freytag
  384. * @date 19-12-2013 (dd-mm-yyyy)
  385. * @param x input example
  386. * @param predVariance contains the approximation of the predictive variance
  387. *
  388. */
  389. void computePredictiveVarianceApproximateFine(const NICE::Vector & x, double & predVariance ) const;
  390. /**
  391. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  392. * @author Alexander Freytag
  393. * @date 19-12-2013 (dd-mm-yyyy)
  394. * @param x input example
  395. * @param predVariance contains the approximation of the predictive variance
  396. *
  397. */
  398. void computePredictiveVarianceExact(const NICE::Vector & x, double & predVariance ) const;
  399. ///////////////////// INTERFACE PERSISTENT /////////////////////
  400. // interface specific methods for store and restore
  401. ///////////////////// INTERFACE PERSISTENT /////////////////////
  402. /**
  403. * @brief Load current object from external file (stream)
  404. * @author Alexander Freytag
  405. */
  406. void restore ( std::istream & is, int format = 0 );
  407. /**
  408. * @brief Save current object to external file (stream)
  409. * @author Alexander Freytag
  410. */
  411. void store ( std::ostream & os, int format = 0 ) const;
  412. /**
  413. * @brief Clear current object
  414. * @author Alexander Freytag
  415. */
  416. void clear ( ) ;
  417. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  418. // interface specific methods for incremental extensions
  419. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  420. /**
  421. * @brief add a new example
  422. * @author Alexander Freytag
  423. */
  424. virtual void addExample( const NICE::SparseVector * example,
  425. const double & label,
  426. const bool & performOptimizationAfterIncrement = true
  427. );
  428. /**
  429. * @brief add several new examples
  430. * @author Alexander Freytag
  431. */
  432. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  433. const NICE::Vector & newLabels,
  434. const bool & performOptimizationAfterIncrement = true
  435. );
  436. };
  437. }
  438. #endif