FastMinKernel.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /**
  2. * @file FastMinKernel.h
  3. * @brief Efficient GPs with HIK for classification by regression (Interface)
  4. * @author Alexander Freytag
  5. * @date 06-12-2011 (dd-mm-yyyy)
  6. */
  7. #ifndef FASTMINKERNELINCLUDE
  8. #define FASTMINKERNELINCLUDE
  9. // STL includes
  10. #include <iostream>
  11. // NICE-core includes
  12. #include <core/basics/Config.h>
  13. #include <core/basics/Exception.h>
  14. #include <core/basics/Persistent.h>
  15. //
  16. //
  17. #include <core/vector/MatrixT.h>
  18. #include <core/vector/SparseVectorT.h>
  19. #include <core/vector/VectorT.h>
  20. #include <core/vector/VVector.h>
  21. // gp-hik-core includes
  22. #include "gp-hik-core/FeatureMatrixT.h"
  23. #include "gp-hik-core/OnlineLearnable.h"
  24. #include "gp-hik-core/Quantization.h"
  25. #include "gp-hik-core/parameterizedFunctions/ParameterizedFunction.h"
  26. namespace NICE {
  27. /**
  28. * @class FastMinKernel
  29. * @brief Efficient GPs with HIK for classification by regression
  30. * @author Alexander Freytag
  31. */
  32. /** interface to FastMinKernel implementation*/
  33. class FastMinKernel : public NICE::Persistent, public OnlineLearnable
  34. {
  35. protected:
  36. /** number of examples */
  37. int n;
  38. /** dimension of feature vectors */
  39. int d;
  40. /** noise added to the diagonal of the kernel matrix */
  41. double noise;
  42. /** sorted matrix of features (sorted along each dimension) */
  43. NICE::FeatureMatrixT<double> X_sorted;
  44. //! verbose flag for output after calling the restore-function
  45. bool verbose;
  46. //! debug flag for output during debugging
  47. bool debug;
  48. /**
  49. * @brief Set number of examples
  50. * @author Alexander Freytag
  51. * @date 07-12-2011 (dd-mm-yyyy)
  52. */
  53. void set_n(const int & _n){n = _n;};
  54. /**
  55. * @brief Set number of dimensions
  56. * @author Alexander Freytag
  57. * @date 07-12-2011 (dd-mm-yyyy)
  58. */
  59. void set_d(const int & _d){d = _d;};
  60. /**
  61. * @brief Prepare the efficient HIK-computations part 1: order the features in each dimension and save the permutation. Pay attention: X is of dim n x d, where as X_sorted is of dimensionality d x n!
  62. * @author Alexander Freytag
  63. * @date 07-12-2011 (dd-mm-yyyy)
  64. */
  65. void hik_prepare_kernel_multiplications(const std::vector<std::vector<double> > & X, NICE::FeatureMatrixT<double> & X_sorted, const int & _dim = -1);
  66. void hik_prepare_kernel_multiplications ( const std::vector< NICE::SparseVector * > & X, NICE::FeatureMatrixT<double> & X_sorted, const bool & dimensionsOverExamples, const int & _dim = -1);
  67. void randomPermutation(NICE::Vector & permutation, const std::vector<int> & oldIndices, const int & newSize) const;
  68. enum ApproximationScheme{ MEDIAN = 0, EXPECTATION=1};
  69. ApproximationScheme approxScheme;
  70. public:
  71. //------------------------------------------------------
  72. // several constructors and destructors
  73. //------------------------------------------------------
  74. /**
  75. * @brief dummy constructor
  76. * @author Alexander Freytag
  77. * @date 20-04-2012 (dd-mm-yyyy)
  78. */
  79. FastMinKernel();
  80. /**
  81. * @brief initialize with some data
  82. * @author Alexander Freytag
  83. * @date 06-12-2011 (dd-mm-yyyy)
  84. */
  85. FastMinKernel( const std::vector<std::vector<double> > & X, const double noise , const bool _debug = false, const int & _dim = -1);
  86. /**
  87. * @brief Just another sparse data structure
  88. *
  89. * @param X vector of sparse vector pointers
  90. * @param noise GP noise
  91. */
  92. FastMinKernel( const std::vector< SparseVector * > & X, const double noise, const bool _debug = false, const bool & dimensionsOverExamples=false, const int & _dim = -1);
  93. #ifdef NICE_USELIB_MATIO
  94. /**
  95. * @brief intialize with some data given in a matlab-sparse struct and restricted with an example index
  96. *
  97. * @param X matlab-struct containing the feature vectors
  98. * @param noise additional noise variance of the labels
  99. * @param examples set of indices to include
  100. */
  101. FastMinKernel ( const sparse_t & X, const double noise, const std::map<int, int> & examples, const bool _debug = false , const int & _dim = -1);
  102. #endif
  103. /**
  104. * @brief Default destructor
  105. * @author Alexander Freytag
  106. * @date 06-12-2011 (dd-mm-yyyy)
  107. */
  108. ~FastMinKernel();
  109. //------------------------------------------------------
  110. // several get and set methods including access operators
  111. //------------------------------------------------------
  112. void setApproximationScheme(const ApproximationScheme & _approxScheme = MEDIAN) {approxScheme = _approxScheme;};
  113. virtual void setApproximationScheme(const int & _approxScheme = 0);
  114. /**
  115. * @brief Get number of examples
  116. * @author Alexander Freytag
  117. * @date 07-12-2011 (dd-mm-yyyy)
  118. */
  119. int get_n() const {return n;};
  120. /**
  121. * @brief Get number of dimensions
  122. * @author Alexander Freytag
  123. * @date 07-12-2011 (dd-mm-yyyy)
  124. */
  125. int get_d() const {return d;};
  126. /**
  127. * @brief Computes the ratio of sparsity across the matrix
  128. * @author Alexander Freytag
  129. * @date 11-01-2012 (dd-mm-yyyy)
  130. */
  131. double getSparsityRatio(){return X_sorted.computeSparsityRatio();};
  132. /** set verbose flag used for restore-functionality*/
  133. void setVerbose( const bool & _verbose);
  134. bool getVerbose( ) const;
  135. /** set debug flag used for debug output*/
  136. void setDebug( const bool & _debug);
  137. bool getDebug( ) const;
  138. //------------------------------------------------------
  139. // high level methods
  140. //------------------------------------------------------
  141. /**
  142. * @brief apply a parameterized function to the feature matrix
  143. * @author Alexander Freytag
  144. * @date 04-05-2012 (dd-mm-yyyy)
  145. *
  146. * @param pf the parameterized function (optional), if not given, nothing will be done
  147. */
  148. void applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *pf = NULL );
  149. /**
  150. * @brief Prepare the efficient HIK-computations part 2: calculate the partial sum for each dimension. Explicitely exploiting sparsity!!! Pay attention: X_sorted is of dimensionality d x n!
  151. * @author Alexander Freytag
  152. * @date 17-01-2012 (dd-mm-yyyy)
  153. */
  154. void hik_prepare_alpha_multiplications(const NICE::Vector & alpha, NICE::VVector & A, NICE::VVector & B) const;
  155. /**
  156. * @brief Computing K*alpha with the minimum kernel trick, explicitely exploiting sparsity!!!
  157. * @author Alexander Freytag
  158. * @date 17-01-2012 (dd-mm-yyyy)
  159. */
  160. void hik_kernel_multiply(const NICE::VVector & A, const NICE::VVector & B, const NICE::Vector & alpha, NICE::Vector & beta) const;
  161. void hik_kernel_multiply_fast(const double *Tlookup, const Quantization & q, const NICE::Vector & alpha, NICE::Vector & beta) const;
  162. /**
  163. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  164. *
  165. * @author Alexander Freytag
  166. * @date 20-01-2012 (dd-mm-yyyy)
  167. * @param A pre-computation matrix (VVector) (use the prepare method)
  168. * @param B pre-computation matrix (VVector)
  169. * @param xstar new feature vector (SparseVector)
  170. * @param beta result of the scalar product
  171. * @param pf optional feature transformation
  172. */
  173. void hik_kernel_sum(const NICE::VVector & A, const NICE::VVector & B, const NICE::SparseVector & xstar, double & beta, const ParameterizedFunction *pf = NULL ) const;
  174. /**
  175. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  176. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  177. *
  178. * @author Alexander Freytag
  179. * @date 18-06-2013 (dd-mm-yyyy)
  180. * @param A pre-computation matrix (VVector) (use the prepare method)
  181. * @param B pre-computation matrix (VVector)
  182. * @param xstar new feature vector (non-sparse Vector)
  183. * @param beta result of the scalar product
  184. * @param pf optional feature transformation
  185. */
  186. void hik_kernel_sum(const NICE::VVector & A, const NICE::VVector & B, const NICE::Vector & xstar, double & beta, const ParameterizedFunction *pf = NULL ) const;
  187. /**
  188. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  189. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  190. * @author Alexander Freytag
  191. * @date 18-06-2013 (dd-mm-yyyy)
  192. *
  193. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  194. * @param q Quantization object
  195. * @param xstar feature vector (indirect k_*)
  196. * @param beta result of the calculation
  197. */
  198. void hik_kernel_sum_fast(const double* Tlookup, const Quantization & q, const NICE::Vector & xstar, double & beta) const;
  199. /**
  200. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  201. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  202. * @author Alexander Frytag
  203. *
  204. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  205. * @param q Quantization object
  206. * @param xstar feature vector (indirect k_*)
  207. * @param beta result of the calculation
  208. */
  209. void hik_kernel_sum_fast(const double *Tlookup, const Quantization & q, const NICE::SparseVector & xstar, double & beta) const;
  210. /**
  211. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  212. * @author Erik Rodner, Alexander Freytag
  213. *
  214. * @param alpha coefficient vector
  215. * @param A pre-calculation array computed by hik_prepare_alpha_multiplications
  216. * @param B pre-calculation array computed by hik_prepare_alpha_multiplications
  217. * @param q Quantization
  218. *
  219. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  220. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  221. */
  222. double *hik_prepare_alpha_multiplications_fast(const NICE::VVector & A, const NICE::VVector & B, const Quantization & q, const ParameterizedFunction *pf = NULL ) const;
  223. /**
  224. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  225. * @author Alexander Freytag
  226. *
  227. * @param alpha coefficient vector
  228. * @param q Quantization
  229. * @param pf ParameterizedFunction to change the original feature values
  230. *
  231. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  232. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  233. */
  234. double* hikPrepareLookupTable(const NICE::Vector & alpha, const Quantization & q, const ParameterizedFunction *pf = NULL) const;
  235. /**
  236. * @brief update the lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  237. * @author Alexander Freytag
  238. *
  239. * @param T previously computed LUT, that will be changed
  240. * @param alphaNew new value of alpha at index idx
  241. * @param alphaOld old value of alpha at index idx
  242. * @param idx index in which alpha changed
  243. * @param q Quantization
  244. * @param pf ParameterizedFunction to change the original feature values
  245. */
  246. void hikUpdateLookupTable(double * T, const double & alphaNew, const double & alphaOld, const int & idx, const Quantization & q, const ParameterizedFunction *pf ) const;
  247. /**
  248. * @brief return a reference to the sorted feature matrix
  249. */
  250. FeatureMatrix & featureMatrix(void) { return X_sorted; };
  251. const FeatureMatrix & featureMatrix(void) const { return X_sorted; };
  252. /**
  253. * @brief solve the linear system K*alpha = y with the minimum kernel trick based on the algorithm of Wu (Wu10_AFD)
  254. * @note method converges slowly for large scale problems and even for normal scale :(
  255. * @author Paul Bodesheim
  256. *
  257. * @param y right hand side of linear system
  258. * @param alpha final solution of the linear system
  259. * @param q Quantization
  260. * @param pf ParameterizedFunction to change the original feature values
  261. * @param useRandomSubsets true, if the order of examples in each iteration should be randomly sampled
  262. * @param maxIterations maximum number of iterations
  263. * @param sizeOfRandomSubset nr of Elements that should be randomly considered in each iteration (max: y.size())
  264. * @param minDelta minimum difference between two solutions alpha_t and alpha_{t+1} (convergence criterion)
  265. *
  266. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  267. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  268. **/
  269. double *solveLin(const NICE::Vector & y, NICE::Vector & alpha, const Quantization & q, const ParameterizedFunction *pf = NULL, const bool & useRandomSubsets = true, uint maxIterations = 10000, const int & _sizeOfRandomSubset = (-1), double minDelta = 1e-7, bool timeAnalysis = false) const;
  270. //! set the noise parameter
  271. void setNoise ( double noise ) { this->noise = noise; }
  272. //! get the current noise parameter
  273. double getNoise (void) const { return noise; }
  274. double getFrobNormApprox();
  275. /**
  276. * @brief Prepare the efficient HIK-computations for the squared kernel vector |k_*|^2 : calculate the partial squared sums for each dimension.
  277. * @author Alexander Freytag
  278. * @date 10-04-2012 (dd-mm-yyyy)
  279. */
  280. void hikPrepareKVNApproximation(NICE::VVector & A) const;
  281. /**
  282. * @brief Compute lookup table for HIK calculation of |k_*|^2 assuming quantized test samples. You have to run hikPrepareSquaredKernelVector before
  283. * @author Alexander Freytag
  284. * @date 10-04-2012 (dd-mm-yyyy)
  285. *
  286. * @param A pre-calculation array computed by hikPrepareSquaredKernelVector
  287. * @param q Quantization
  288. * @param pf Parameterized Function to efficiently apply a function to the underlying data
  289. *
  290. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  291. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  292. */
  293. double * hikPrepareKVNApproximationFast(NICE::VVector & A, const Quantization & q, const ParameterizedFunction *pf = NULL ) const;
  294. /**
  295. * @brief Compute lookup table for HIK calculation of |k_*|^2 assuming quantized test samples ( equals hikPrepareSquaredKernelVector + hikPrepareSquaredKernelVectorFast, but is faster). Approximation does not considere mixed terms between dimensions.
  296. * @author Alexander Freytag
  297. * @date 10-04-2012 (dd-mm-yyyy)
  298. *
  299. * @param q Quantization
  300. * @param pf ParameterizedFunction to change the original feature values
  301. *
  302. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  303. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  304. */
  305. double* hikPrepareLookupTableForKVNApproximation(const Quantization & q, const ParameterizedFunction *pf = NULL) const;
  306. //////////////////////////////////////////
  307. // variance computation: sparse inputs
  308. //////////////////////////////////////////
  309. /**
  310. * @brief Approximate norm = |k_*|^2 using the minimum kernel trick and exploiting sparsity of the given feature vector. Approximation does not considere mixed terms between dimensions.
  311. * @author Alexander Freytag
  312. * @date 10-04-2012 (dd-mm-yyyy)
  313. *
  314. * @param A pre-computation matrix (VVector) (use the prepare method)
  315. * @param xstar new feature vector (SparseVector)
  316. * @param norm result of the squared norm approximation
  317. * @param pf optional feature transformation
  318. */
  319. void hikComputeKVNApproximation(const NICE::VVector & A, const NICE::SparseVector & xstar, double & norm, const ParameterizedFunction *pf = NULL ) ;
  320. /**
  321. * @brief Approximate norm = |k_*|^2 using a large lookup table created by hikPrepareSquaredKernelVector and hikPrepareSquaredKernelVectorFast or directly using hikPrepareLookupTableForSquaredKernelVector. Approximation does not considere mixed terms between dimensions.
  322. * @author Alexander Freytag
  323. * @date 10-04-2012 (dd-mm-yyyy)
  324. *
  325. * @param Tlookup large lookup table
  326. * @param q Quantization object
  327. * @param xstar feature vector (indirect k_*)
  328. * @param norm result of the calculation
  329. */
  330. void hikComputeKVNApproximationFast(const double *Tlookup, const Quantization & q, const NICE::SparseVector & xstar, double & norm ) const;
  331. /**
  332. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Exploiting sparsity
  333. * @author Alexander Freytag
  334. * @date 13-04-2012 (dd-mm-yyyy)
  335. *
  336. * @param xstar feature vector
  337. * @param kstar kernel vector
  338. */
  339. void hikComputeKernelVector( const NICE::SparseVector & xstar, NICE::Vector & kstar) const;
  340. //////////////////////////////////////////
  341. // variance computation: non-sparse inputs
  342. //////////////////////////////////////////
  343. /**
  344. * @brief Approximate norm = |k_*|^2 using the minimum kernel trick and exploiting sparsity of the given feature vector. Approximation does not considere mixed terms between dimensions.
  345. * @author Alexander Freytag
  346. * @date 19-12-2013 (dd-mm-yyyy)
  347. *
  348. * @param A pre-computation matrix (VVector) (use the prepare method)
  349. * @param xstar new feature vector (Vector)
  350. * @param norm result of the squared norm approximation
  351. * @param pf optional feature transformation
  352. */
  353. void hikComputeKVNApproximation(const NICE::VVector & A, const NICE::Vector & xstar, double & norm, const ParameterizedFunction *pf = NULL ) ;
  354. /**
  355. * @brief Approximate norm = |k_*|^2 using a large lookup table created by hikPrepareSquaredKernelVector and hikPrepareSquaredKernelVectorFast or directly using hikPrepareLookupTableForSquaredKernelVector. Approximation does not considere mixed terms between dimensions.
  356. * @author Alexander Freytag
  357. * @date 19-12-2013 (dd-mm-yyyy)
  358. *
  359. * @param Tlookup large lookup table
  360. * @param q Quantization object
  361. * @param xstar feature vector (indirect k_*)
  362. * @param norm result of the calculation
  363. */
  364. void hikComputeKVNApproximationFast(const double *Tlookup, const Quantization & q, const NICE::Vector & xstar, double & norm ) const;
  365. /**
  366. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Does not exploit sparsity - deprecated!
  367. * @author Alexander Freytag
  368. * @date 19-12-2013 (dd-mm-yyyy)
  369. *
  370. * @param xstar feature vector
  371. * @param kstar kernel vector
  372. */
  373. void hikComputeKernelVector( const NICE::Vector & xstar, NICE::Vector & kstar) const;
  374. /** Persistent interface */
  375. virtual void restore ( std::istream & is, int format = 0 );
  376. virtual void store ( std::ostream & os, int format = 0 ) const;
  377. virtual void clear ();
  378. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  379. // interface specific methods for incremental extensions
  380. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  381. virtual void addExample( const NICE::SparseVector * example,
  382. const double & label,
  383. const bool & performOptimizationAfterIncrement = true
  384. );
  385. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & newExamples,
  386. const NICE::Vector & newLabels,
  387. const bool & performOptimizationAfterIncrement = true
  388. );
  389. /**
  390. * @brief Add a new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  391. * @author Alexander Freytag
  392. * @date 02-01-2014 (dd-mm-yyyy)
  393. *
  394. * @param example new feature vector
  395. */
  396. void addExample(const NICE::SparseVector * example, const NICE::ParameterizedFunction *pf = NULL);
  397. /**
  398. * @brief Add multiple new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  399. * @author Alexander Freytag
  400. * @date 02-01-2014 (dd-mm-yyyy)
  401. *
  402. * @param newExamples new feature vectors
  403. */
  404. void addMultipleExamples(const std::vector<const NICE::SparseVector * > & newExamples, const NICE::ParameterizedFunction *pf = NULL);
  405. };
  406. } // namespace
  407. #endif