FMKGPHyperparameterOptimization.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. /** object storing sorted data and providing fast hik methods */
  56. NICE::FastMinKernel *fmk;
  57. /** object performing feature quantization */
  58. NICE::Quantization *q;
  59. /** the parameterized function we use within the minimum kernel */
  60. NICE::ParameterizedFunction *pf;
  61. /** method for solving linear equation systems - needed to compute K^-1 \times y */
  62. IterativeLinearSolver *linsolver;
  63. /** Max. number of iterations the iterative linear solver is allowed to run */
  64. int ils_max_iterations;
  65. /** Simple type definition for precomputation matrices used for fast classification */
  66. typedef VVector PrecomputedType;
  67. /** precomputed arrays A (1 per class) needed for classification without quantization */
  68. std::map< int, PrecomputedType > precomputedA;
  69. /** precomputed arrays B (1 per class) needed for classification without quantization */
  70. std::map< int, PrecomputedType > precomputedB;
  71. /** precomputed LUTs (1 per class) needed for classification with quantization */
  72. std::map< int, double * > precomputedT;
  73. //! storing the labels is needed for Incremental Learning (re-optimization)
  74. NICE::Vector labels;
  75. //! store the class number of the positive class (i.e., larger class no), only used in binary settings
  76. int binaryLabelPositive;
  77. //! store the class number of the negative class (i.e., smaller class no), only used in binary settings
  78. int binaryLabelNegative;
  79. //! contains all class numbers of the currently known classes
  80. std::set<int> knownClasses;
  81. //! container for multiple kernel matrices (e.g., a data-containing kernel matrix (GMHIKernel) and a noise matrix (IKMNoise) )
  82. NICE::IKMLinearCombination * ikmsum;
  83. /////////////////////////////////////
  84. // optimization related parameters //
  85. /////////////////////////////////////
  86. enum {
  87. OPT_GREEDY = 0,
  88. OPT_DOWNHILLSIMPLEX,
  89. OPT_NONE
  90. };
  91. /** specify the optimization method used (see corresponding enum) */
  92. int optimizationMethod;
  93. //! whether or not to optimize noise with the GP likelihood
  94. bool optimizeNoise;
  95. /** upper bound for hyper parameters to optimize */
  96. double parameterUpperBound;
  97. /** lower bound for hyper parameters to optimize */
  98. double parameterLowerBound;
  99. // specific to greedy optimization
  100. /** step size used in grid based greedy optimization technique */
  101. double parameterStepSize;
  102. // specific to downhill simplex optimization
  103. /** Max. number of iterations the downhill simplex optimizer is allowed to run */
  104. int downhillSimplexMaxIterations;
  105. /** Max. time the downhill simplex optimizer is allowed to run */
  106. double downhillSimplexTimeLimit;
  107. /** Max. number of iterations the iterative linear solver is allowed to run */
  108. double downhillSimplexParamTol;
  109. // likelihood computation related variables
  110. /** whether to compute the exact likelihood by computing the exact kernel matrix (not recommended - only for debugging/comparison purpose) */
  111. bool verifyApproximation;
  112. /** method computing eigenvalues and eigenvectors*/
  113. NICE::EigValues *eig;
  114. /** number of Eigenvalues to consider in the approximation of |K|_F used for approximating the likelihood */
  115. int nrOfEigenvaluesToConsider;
  116. //! k largest eigenvalues of the kernel matrix (k == nrOfEigenvaluesToConsider)
  117. NICE::Vector eigenMax;
  118. //! eigenvectors corresponding to k largest eigenvalues (k == nrOfEigenvaluesToConsider) -- format: nxk
  119. NICE::Matrix eigenMaxVectors;
  120. ////////////////////////////////////////////
  121. // variance computation related variables //
  122. ////////////////////////////////////////////
  123. /** number of Eigenvalues to consider in the fine approximation of the predictive variance (fine approximation only) */
  124. int nrOfEigenvaluesToConsiderForVarApprox;
  125. /** precomputed array needed for rough variance approximation without quantization */
  126. PrecomputedType precomputedAForVarEst;
  127. /** precomputed LUT needed for rough variance approximation with quantization */
  128. double * precomputedTForVarEst;
  129. /////////////////////////////////////////////////////
  130. // online / incremental learning related variables //
  131. /////////////////////////////////////////////////////
  132. /** whether or not to use previous alpha solutions as initialization after adding new examples*/
  133. bool b_usePreviousAlphas;
  134. //! store alpha vectors for good initializations in the IL setting, if activated
  135. std::map<int, NICE::Vector> previousAlphas;
  136. /////////////////////////
  137. /////////////////////////
  138. // PROTECTED METHODS //
  139. /////////////////////////
  140. /////////////////////////
  141. /**
  142. * @brief calculate binary label vectors using a multi-class label vector
  143. * @author Alexander Freytag
  144. */
  145. int prepareBinaryLabels ( std::map<int, NICE::Vector> & binaryLabels, const NICE::Vector & y , std::set<int> & myClasses);
  146. /**
  147. * @brief prepare the GPLike object for given binary labels and already given ikmsum-object
  148. * @author Alexander Freytag
  149. */
  150. inline void setupGPLikelihoodApprox( GPLikelihoodApprox * & gplike, const std::map<int, NICE::Vector> & binaryLabels, uint & parameterVectorSize);
  151. /**
  152. * @brief update eigenvectors and eigenvalues for given ikmsum-objects and a method to compute eigenvalues
  153. * @author Alexander Freytag
  154. */
  155. inline void updateEigenDecomposition( const int & i_noEigenValues );
  156. /**
  157. * @brief core of the optimize-functions
  158. * @author Alexander Freytag
  159. */
  160. inline void performOptimization( GPLikelihoodApprox & gplike, const uint & parameterVectorSize);
  161. /**
  162. * @brief apply the optimized transformation values to the underlying features
  163. * @author Alexander Freytag
  164. */
  165. inline void transformFeaturesWithOptimalParameters(const GPLikelihoodApprox & gplike, const uint & parameterVectorSize);
  166. /**
  167. * @brief build the resulting matrices A and B as well as lookup tables T for fast evaluations using the optimized parameter settings
  168. * @author Alexander Freytag
  169. */
  170. inline void computeMatricesAndLUTs( const GPLikelihoodApprox & gplike);
  171. /**
  172. * @brief Update matrices (A, B, LUTs) and optionally find optimal parameters after adding (a) new example(s).
  173. * @author Alexander Freytag
  174. */
  175. void updateAfterIncrement (
  176. const std::set<int> newClasses,
  177. const bool & performOptimizationAfterIncrement = false
  178. );
  179. public:
  180. /**
  181. * @brief simple constructor
  182. * @author Alexander Freytag
  183. */
  184. FMKGPHyperparameterOptimization();
  185. /**
  186. * @brief standard constructor
  187. *
  188. * @param pf pointer to a parameterized function used within the minimum kernel min(f(x_i), f(x_j)) (will not be deleted)
  189. * @param noise GP label noise
  190. * @param fmk pointer to a pre-initialized structure (will be deleted)
  191. */
  192. FMKGPHyperparameterOptimization( const Config *conf, ParameterizedFunction *pf, FastMinKernel *fmk = NULL, const std::string & confSection = "GPHIKClassifier" );
  193. /**
  194. * @brief standard destructor
  195. * @author Alexander Freytag
  196. */
  197. virtual ~FMKGPHyperparameterOptimization();
  198. ///////////////////// ///////////////////// /////////////////////
  199. // GET / SET
  200. ///////////////////// ///////////////////// /////////////////////
  201. /**
  202. * @brief Set lower bound for hyper parameters to optimize
  203. * @author Alexander Freytag
  204. */
  205. void setParameterUpperBound(const double & _parameterUpperBound);
  206. /**
  207. * @brief Set upper bound for hyper parameters to optimize
  208. * @author Alexander Freytag
  209. */
  210. void setParameterLowerBound(const double & _parameterLowerBound);
  211. /**
  212. * @brief Get the currently known class numbers
  213. * @author Alexander Freytag
  214. */
  215. std::set<int> getKnownClassNumbers ( ) const;
  216. ///////////////////// ///////////////////// /////////////////////
  217. // CLASSIFIER STUFF
  218. ///////////////////// ///////////////////// /////////////////////
  219. /**
  220. * @brief Set variables and parameters to default or config-specified values
  221. * @author Alexander Freytag
  222. */
  223. void initialize( const Config *conf, ParameterizedFunction *pf, FastMinKernel *fmk = NULL, const std::string & confSection = "GPHIKClassifier" );
  224. #ifdef NICE_USELIB_MATIO
  225. /**
  226. * @brief Perform hyperparameter optimization
  227. *
  228. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  229. * @param y label vector (arbitrary), will be converted into a binary label vector
  230. * @param positives set of positive examples (indices)
  231. * @param negatives set of negative examples (indices)
  232. */
  233. void optimizeBinary ( const sparse_t & data, const NICE::Vector & y, const std::set<int> & positives, const std::set<int> & negatives, double noise );
  234. /**
  235. * @brief Perform hyperparameter optimization for GP multi-class or binary problems
  236. *
  237. * @param data MATLAB data structure, like a feature matrix loaded from ImageNet
  238. * @param y label vector with multi-class labels
  239. * @param examples mapping of example index to new index
  240. */
  241. void optimize ( const sparse_t & data, const NICE::Vector & y, const std::map<int, int> & examples, double noise );
  242. #endif
  243. /**
  244. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  245. *
  246. * @param y label vector (multi-class as well as binary labels supported)
  247. */
  248. void optimize ( const NICE::Vector & y );
  249. /**
  250. * @brief Perform hyperparameter optimization (multi-class or binary) assuming an already initialized fmk object
  251. *
  252. * @param binLabels vector of binary label vectors (1,-1) and corresponding class no.
  253. */
  254. void optimize ( std::map<int, NICE::Vector> & binaryLabels );
  255. /**
  256. * @brief Compute the necessary variables for appxorimations of predictive variance (LUTs), assuming an already initialized fmk object
  257. * @author Alexander Freytag
  258. * @date 11-04-2012 (dd-mm-yyyy)
  259. */
  260. void prepareVarianceApproximationRough();
  261. /**
  262. * @brief Compute the necessary variables for fine appxorimations of predictive variance (EVs), assuming an already initialized fmk object
  263. * @author Alexander Freytag
  264. * @date 11-04-2012 (dd-mm-yyyy)
  265. */
  266. void prepareVarianceApproximationFine();
  267. /**
  268. * @brief classify an example
  269. *
  270. * @param x input example (sparse vector)
  271. * @param scores scores for each class number
  272. *
  273. * @return class number achieving the best score
  274. */
  275. int classify ( const NICE::SparseVector & x, SparseVector & scores ) const;
  276. /**
  277. * @brief classify an example that is given as non-sparse vector
  278. * NOTE: whenever possible, you should sparse vectors to obtain significantly smaller computation times
  279. *
  280. * @date 18-06-2013 (dd-mm-yyyy)
  281. * @author Alexander Freytag
  282. *
  283. * @param x input example (non-sparse vector)
  284. * @param scores scores for each class number
  285. *
  286. * @return class number achieving the best score
  287. */
  288. int classify ( const NICE::Vector & x, SparseVector & scores ) const;
  289. //////////////////////////////////////////
  290. // variance computation: sparse inputs
  291. //////////////////////////////////////////
  292. /**
  293. * @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
  294. * @author Alexander Freytag
  295. * @date 10-04-2012 (dd-mm-yyyy)
  296. * @param x input example
  297. * @param predVariance contains the approximation of the predictive variance
  298. *
  299. */
  300. void computePredictiveVarianceApproximateRough(const NICE::SparseVector & x, double & predVariance ) const;
  301. /**
  302. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  303. * @author Alexander Freytag
  304. * @date 18-04-2012 (dd-mm-yyyy)
  305. * @param x input example
  306. * @param predVariance contains the approximation of the predictive variance
  307. *
  308. */
  309. void computePredictiveVarianceApproximateFine(const NICE::SparseVector & x, double & predVariance ) const;
  310. /**
  311. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  312. * @author Alexander Freytag
  313. * @date 10-04-2012 (dd-mm-yyyy)
  314. * @param x input example
  315. * @param predVariance contains the approximation of the predictive variance
  316. *
  317. */
  318. void computePredictiveVarianceExact(const NICE::SparseVector & x, double & predVariance ) const;
  319. //////////////////////////////////////////
  320. // variance computation: non-sparse inputs
  321. //////////////////////////////////////////
  322. /**
  323. * @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
  324. * @author Alexander Freytag
  325. * @date 19-12-2013 (dd-mm-yyyy)
  326. * @param x input example
  327. * @param predVariance contains the approximation of the predictive variance
  328. *
  329. */
  330. void computePredictiveVarianceApproximateRough(const NICE::Vector & x, double & predVariance ) const;
  331. /**
  332. * @brief compute predictive variance for a given test example using a fine approximation (k eigenvalues and eigenvectors to approximate the quadratic term)
  333. * @author Alexander Freytag
  334. * @date 19-12-2013 (dd-mm-yyyy)
  335. * @param x input example
  336. * @param predVariance contains the approximation of the predictive variance
  337. *
  338. */
  339. void computePredictiveVarianceApproximateFine(const NICE::Vector & x, double & predVariance ) const;
  340. /**
  341. * @brief compute exact predictive variance for a given test example using ILS methods (exact, but more time consuming than approx versions)
  342. * @author Alexander Freytag
  343. * @date 19-12-2013 (dd-mm-yyyy)
  344. * @param x input example
  345. * @param predVariance contains the approximation of the predictive variance
  346. *
  347. */
  348. void computePredictiveVarianceExact(const NICE::Vector & x, double & predVariance ) const;
  349. ///////////////////// INTERFACE PERSISTENT /////////////////////
  350. // interface specific methods for store and restore
  351. ///////////////////// INTERFACE PERSISTENT /////////////////////
  352. /**
  353. * @brief Load current object from external file (stream)
  354. * @author Alexander Freytag
  355. */
  356. void restore ( std::istream & is, int format = 0 );
  357. /**
  358. * @brief Save current object to external file (stream)
  359. * @author Alexander Freytag
  360. */
  361. void store ( std::ostream & os, int format = 0 ) const;
  362. /**
  363. * @brief Clear current object
  364. * @author Alexander Freytag
  365. */
  366. void clear ( ) ;
  367. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  368. // interface specific methods for incremental extensions
  369. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  370. /**
  371. * @brief add a new example
  372. * @author Alexander Freytag
  373. */
  374. virtual void addExample( const NICE::SparseVector * example,
  375. const double & label,
  376. const bool & performOptimizationAfterIncrement = true
  377. );
  378. /**
  379. * @brief add several new examples
  380. * @author Alexander Freytag
  381. */
  382. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  383. const NICE::Vector & newLabels,
  384. const bool & performOptimizationAfterIncrement = true
  385. );
  386. };
  387. }
  388. #endif