FastMinKernel.h 20 KB

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