FMKGPHyperparameterOptimization.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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 verbose;
  48. /** verbose flag for time measurement outputs */
  49. bool verboseTime;
  50. /** debug flag for several outputs useful for debugging*/
  51. bool 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 parameterUpperBound;
  63. /** lower bound for hyper parameters (ParameterizedFunction) to optimize */
  64. double 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 binaryLabelPositive;
  79. //! store the class number of the negative class (i.e., smaller class no), only used in binary settings
  80. int 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 & b_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, const std::string & confSection = "FMKGPHyperparameterOptimization" );
  206. /**
  207. * @brief recommended constructor, only calls this->initialize with same input arguments
  208. * @author Alexander Freytag
  209. *
  210. * @param conf
  211. * @param fmk pointer to a pre-initialized structure (will be deleted)
  212. * @param confSection
  213. */
  214. FMKGPHyperparameterOptimization( const Config *conf, FastMinKernel *_fmk, const std::string & confSection = "FMKGPHyperparameterOptimization" );
  215. /**
  216. * @brief standard destructor
  217. * @author Alexander Freytag
  218. */
  219. virtual ~FMKGPHyperparameterOptimization();
  220. /**
  221. * @brief Set variables and parameters to default or config-specified values
  222. * @author Alexander Freytag
  223. */
  224. void initFromConfig( const Config *conf, const std::string & confSection = "FMKGPHyperparameterOptimization" );
  225. ///////////////////// ///////////////////// /////////////////////
  226. // GET / SET
  227. ///////////////////// ///////////////////// /////////////////////
  228. /**
  229. * @brief Set lower bound for hyper parameters to optimize
  230. * @author Alexander Freytag
  231. */
  232. void setParameterUpperBound(const double & _parameterUpperBound);
  233. /**
  234. * @brief Set upper bound for hyper parameters to optimize
  235. * @author Alexander Freytag
  236. */
  237. void setParameterLowerBound(const double & _parameterLowerBound);
  238. /**
  239. * @brief Get the currently known class numbers
  240. * @author Alexander Freytag
  241. */
  242. std::set<int> getKnownClassNumbers ( ) const;
  243. /**
  244. * @brief Change between classification and regression, only allowed if not trained. Otherwise, exceptions will be thrown...
  245. * @author Alexander Freytag
  246. * @date 05-02-2014 (dd-mm-yyyy)
  247. */
  248. void setPerformRegression ( const bool & b_performRegression );
  249. /**
  250. * @brief Set the FastMinKernel object. Only allowed if not trained. Otherwise, exceptions will be thrown...
  251. * @author Alexander Freytag
  252. * @date 05-02-2014 (dd-mm-yyyy)
  253. */
  254. void setFastMinKernel ( FastMinKernel *fmk );
  255. /**
  256. * @brief Set the number of EV we considere for variance approximation. Only allowed if not trained. Otherwise, exceptions will be thrown...
  257. * @author Alexander Freytag
  258. * @date 06-02-2014 (dd-mm-yyyy)
  259. */
  260. void setNrOfEigenvaluesToConsiderForVarApprox ( const int & i_nrOfEigenvaluesToConsiderForVarApprox );
  261. ///////////////////// ///////////////////// /////////////////////
  262. // CLASSIFIER STUFF
  263. ///////////////////// ///////////////////// /////////////////////
  264. #ifdef NICE_USELIB_MATIO
  265. /**
  266. * @brief Perform hyperparameter optimization
  267. * @author Alexander Freytag
  268. *
  269. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  270. * @param y label vector (arbitrary), will be converted into a binary label vector
  271. * @param positives set of positive examples (indices)
  272. * @param negatives set of negative examples (indices)
  273. */
  274. void optimizeBinary ( const sparse_t & data, const NICE::Vector & y, const std::set<int> & positives, const std::set<int> & negatives, double noise );
  275. /**
  276. * @brief Perform hyperparameter optimization for GP multi-class or binary problems
  277. * @author Alexander Freytag
  278. *
  279. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  280. * @param y label vector with multi-class labels
  281. * @param examples mapping of example index to new index
  282. */
  283. void optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise );
  284. #endif
  285. /**
  286. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  287. * @author Alexander Freytag
  288. *
  289. * @param y label vector (multi-class as well as binary labels supported)
  290. */
  291. void optimize ( const NICE::Vector & y );
  292. /**
  293. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  294. *
  295. * @param binLabels vector of binary label vectors (1,-1) and corresponding class no.
  296. */
  297. void optimize ( std::map<int, NICE::Vector> & binaryLabels );
  298. /**
  299. * @brief Compute the necessary variables for appxorimations of predictive variance (LUTs), assuming an already initialized fmk object
  300. * @author Alexander Freytag
  301. * @date 11-04-2012 (dd-mm-yyyy)
  302. */
  303. void prepareVarianceApproximationRough();
  304. /**
  305. * @brief Compute the necessary variables for fine appxorimations of predictive variance (EVs), assuming an already initialized fmk object
  306. * @author Alexander Freytag
  307. * @date 11-04-2012 (dd-mm-yyyy)
  308. */
  309. void prepareVarianceApproximationFine();
  310. /**
  311. * @brief classify an example
  312. *
  313. * @param x input example (sparse vector)
  314. * @param scores scores for each class number
  315. *
  316. * @return class number achieving the best score
  317. */
  318. int classify ( const NICE::SparseVector & x, SparseVector & scores ) const;
  319. /**
  320. * @brief classify an example that is given as non-sparse vector
  321. * NOTE: whenever possible, you should use sparse vectors to obtain significantly smaller computation times
  322. *
  323. * @date 18-06-2013 (dd-mm-yyyy)
  324. * @author Alexander Freytag
  325. *
  326. * @param x input example (non-sparse vector)
  327. * @param scores scores for each class number
  328. *
  329. * @return class number achieving the best score
  330. */
  331. int classify ( const NICE::Vector & x, SparseVector & scores ) const;
  332. //////////////////////////////////////////
  333. // variance computation: sparse inputs
  334. //////////////////////////////////////////
  335. /**
  336. * @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
  337. * @author Alexander Freytag
  338. * @date 10-04-2012 (dd-mm-yyyy)
  339. * @param x input example
  340. * @param predVariance contains the approximation of the predictive variance
  341. *
  342. */
  343. void computePredictiveVarianceApproximateRough(const NICE::SparseVector & x, double & predVariance ) const;
  344. /**
  345. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  346. * @author Alexander Freytag
  347. * @date 18-04-2012 (dd-mm-yyyy)
  348. * @param x input example
  349. * @param predVariance contains the approximation of the predictive variance
  350. *
  351. */
  352. void computePredictiveVarianceApproximateFine(const NICE::SparseVector & x, double & predVariance ) const;
  353. /**
  354. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  355. * @author Alexander Freytag
  356. * @date 10-04-2012 (dd-mm-yyyy)
  357. * @param x input example
  358. * @param predVariance contains the approximation of the predictive variance
  359. *
  360. */
  361. void computePredictiveVarianceExact(const NICE::SparseVector & x, double & predVariance ) const;
  362. //////////////////////////////////////////
  363. // variance computation: non-sparse inputs
  364. //////////////////////////////////////////
  365. /**
  366. * @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
  367. * @author Alexander Freytag
  368. * @date 19-12-2013 (dd-mm-yyyy)
  369. * @param x input example
  370. * @param predVariance contains the approximation of the predictive variance
  371. *
  372. */
  373. void computePredictiveVarianceApproximateRough(const NICE::Vector & x, double & predVariance ) const;
  374. /**
  375. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  376. * @author Alexander Freytag
  377. * @date 19-12-2013 (dd-mm-yyyy)
  378. * @param x input example
  379. * @param predVariance contains the approximation of the predictive variance
  380. *
  381. */
  382. void computePredictiveVarianceApproximateFine(const NICE::Vector & x, double & predVariance ) const;
  383. /**
  384. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  385. * @author Alexander Freytag
  386. * @date 19-12-2013 (dd-mm-yyyy)
  387. * @param x input example
  388. * @param predVariance contains the approximation of the predictive variance
  389. *
  390. */
  391. void computePredictiveVarianceExact(const NICE::Vector & x, double & predVariance ) const;
  392. ///////////////////// INTERFACE PERSISTENT /////////////////////
  393. // interface specific methods for store and restore
  394. ///////////////////// INTERFACE PERSISTENT /////////////////////
  395. /**
  396. * @brief Load current object from external file (stream)
  397. * @author Alexander Freytag
  398. */
  399. void restore ( std::istream & is, int format = 0 );
  400. /**
  401. * @brief Save current object to external file (stream)
  402. * @author Alexander Freytag
  403. */
  404. void store ( std::ostream & os, int format = 0 ) const;
  405. /**
  406. * @brief Clear current object
  407. * @author Alexander Freytag
  408. */
  409. void clear ( ) ;
  410. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  411. // interface specific methods for incremental extensions
  412. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  413. /**
  414. * @brief add a new example
  415. * @author Alexander Freytag
  416. */
  417. virtual void addExample( const NICE::SparseVector * example,
  418. const double & label,
  419. const bool & performOptimizationAfterIncrement = true
  420. );
  421. /**
  422. * @brief add several new examples
  423. * @author Alexander Freytag
  424. */
  425. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  426. const NICE::Vector & newLabels,
  427. const bool & performOptimizationAfterIncrement = true
  428. );
  429. };
  430. }
  431. #endif