FastMinKernel.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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. uint ui_n;
  38. /** dimension of feature vectors */
  39. uint ui_d;
  40. /** noise added to the diagonal of the kernel matrix */
  41. double d_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 b_verbose;
  46. //! debug flag for output during debugging
  47. bool b_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 uint & _n){this->ui_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 uint & _d){this->ui_d = _d;};
  60. void randomPermutation(NICE::Vector & _permutation,
  61. const std::vector<uint> & _oldIndices,
  62. const uint & _newSize
  63. ) const;
  64. enum ApproximationScheme{ MEDIAN = 0, EXPECTATION=1};
  65. ApproximationScheme approxScheme;
  66. public:
  67. //------------------------------------------------------
  68. // several constructors and destructors
  69. //------------------------------------------------------
  70. /**
  71. * @brief default constructor
  72. * @author Alexander Freytag
  73. * @date 20-04-2012 (dd-mm-yyyy)
  74. */
  75. FastMinKernel();
  76. /**
  77. * @brief recommended constructor, initialize with some data
  78. * @author Alexander Freytag
  79. * @date 06-12-2011 (dd-mm-yyyy)
  80. */
  81. FastMinKernel( const std::vector<std::vector<double> > & _X,
  82. const double _noise ,
  83. const bool _debug = false,
  84. const uint & _dim = 0
  85. );
  86. /**
  87. * @brief recommended constructor, 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< const NICE::SparseVector * > & _X,
  93. const double _noise,
  94. const bool _debug = false,
  95. const bool & dimensionsOverExamples=false,
  96. const uint & _dim = 0
  97. );
  98. #ifdef NICE_USELIB_MATIO
  99. /**
  100. * @brief recommended constructor, intialize with some data given in a matlab-sparse struct and restricted with an example index
  101. *
  102. * @param X matlab-struct containing the feature vectors
  103. * @param noise additional noise variance of the labels
  104. * @param examples set of indices to include
  105. */
  106. FastMinKernel ( const sparse_t & _X,
  107. const double _noise,
  108. const std::map<uint, uint> & _examples,
  109. const bool _debug = false ,
  110. const uint & _dim = 0);
  111. #endif
  112. /**
  113. * @brief Default destructor
  114. * @author Alexander Freytag
  115. * @date 06-12-2011 (dd-mm-yyyy)
  116. */
  117. ~FastMinKernel();
  118. ///////////////////// ///////////////////// /////////////////////
  119. // GET / SET
  120. // INCLUDING ACCESS OPERATORS
  121. ///////////////////// ///////////////////// /////////////////////
  122. void setApproximationScheme(const ApproximationScheme & _approxScheme = MEDIAN) {approxScheme = _approxScheme;};
  123. virtual void setApproximationScheme(const int & _approxScheme = 0);
  124. /**
  125. * @brief Get number of examples
  126. * @author Alexander Freytag
  127. * @date 07-12-2011 (dd-mm-yyyy)
  128. */
  129. uint get_n() const;
  130. /**
  131. * @brief Get number of dimensions
  132. * @author Alexander Freytag
  133. * @date 07-12-2011 (dd-mm-yyyy)
  134. */
  135. uint get_d() const;
  136. /**
  137. * @brief Computes the ratio of sparsity across the matrix
  138. * @author Alexander Freytag
  139. * @date 11-01-2012 (dd-mm-yyyy)
  140. */
  141. double getSparsityRatio() const;
  142. /** set verbose flag used for restore-functionality*/
  143. void setVerbose( const bool & _verbose);
  144. bool getVerbose( ) const;
  145. /** set debug flag used for debug output*/
  146. void setDebug( const bool & _debug);
  147. bool getDebug( ) const;
  148. //------------------------------------------------------
  149. // high level methods
  150. //------------------------------------------------------
  151. /**
  152. * @brief apply a parameterized function to the feature matrix
  153. * @author Alexander Freytag
  154. * @date 04-05-2012 (dd-mm-yyyy)
  155. *
  156. * @param pf the parameterized function (optional), if not given, nothing will be done
  157. */
  158. void applyFunctionToFeatureMatrix ( const NICE::ParameterizedFunction *_pf = NULL );
  159. /**
  160. * @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!
  161. * @author Alexander Freytag
  162. * @date 17-01-2012 (dd-mm-yyyy)
  163. */
  164. void hik_prepare_alpha_multiplications(const NICE::Vector & _alpha,
  165. NICE::VVector & _A,
  166. NICE::VVector & _B
  167. ) const;
  168. /**
  169. * @brief Computing K*alpha with the minimum kernel trick, explicitely exploiting sparsity!!!
  170. * @author Alexander Freytag
  171. * @date 17-01-2012 (dd-mm-yyyy)
  172. */
  173. void hik_kernel_multiply(const NICE::VVector & _A,
  174. const NICE::VVector & _B,
  175. const NICE::Vector & _alpha,
  176. NICE::Vector & _beta
  177. ) const;
  178. void hik_kernel_multiply_fast(const double *_Tlookup,
  179. const Quantization & _q,
  180. const NICE::Vector & _alpha,
  181. NICE::Vector & _beta
  182. ) const;
  183. /**
  184. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  185. *
  186. * @author Alexander Freytag
  187. * @date 20-01-2012 (dd-mm-yyyy)
  188. * @param A pre-computation matrix (VVector) (use the prepare method)
  189. * @param B pre-computation matrix (VVector)
  190. * @param xstar new feature vector (SparseVector)
  191. * @param beta result of the scalar product
  192. * @param pf optional feature transformation
  193. */
  194. void hik_kernel_sum(const NICE::VVector & _A,
  195. const NICE::VVector & _B,
  196. const NICE::SparseVector & _xstar,
  197. double & _beta,
  198. const ParameterizedFunction *_pf = NULL
  199. ) const;
  200. /**
  201. * @brief Computing k_{*}*alpha using the minimum kernel trick and exploiting sparsity of the feature vector given
  202. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  203. *
  204. * @author Alexander Freytag
  205. * @date 18-06-2013 (dd-mm-yyyy)
  206. * @param A pre-computation matrix (VVector) (use the prepare method)
  207. * @param B pre-computation matrix (VVector)
  208. * @param xstar new feature vector (non-sparse Vector)
  209. * @param beta result of the scalar product
  210. * @param pf optional feature transformation
  211. */
  212. void hik_kernel_sum(const NICE::VVector & _A,
  213. const NICE::VVector & _B,
  214. const NICE::Vector & _xstar,
  215. double & _beta,
  216. const ParameterizedFunction *_pf = NULL
  217. ) const;
  218. /**
  219. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  220. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  221. * @author Alexander Freytag
  222. * @date 18-06-2013 (dd-mm-yyyy)
  223. *
  224. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  225. * @param q Quantization object
  226. * @param xstar feature vector (indirect k_*)
  227. * @param beta result of the calculation
  228. */
  229. void hik_kernel_sum_fast(const double* _Tlookup,
  230. const Quantization & _q,
  231. const NICE::Vector & _xstar,
  232. double & _beta
  233. ) const;
  234. /**
  235. * @brief compute beta = k_*^T * alpha by using a large lookup table created by hik_prepare_alpha_multiplications_fast
  236. * NOTE: Whenever possible, you should use sparse features to obtain significantly smaller computation times!
  237. * @author Alexander Frytag
  238. *
  239. * @param Tlookup large lookup table calculated by hik_prepare_alpha_multiplications_fast
  240. * @param q Quantization object
  241. * @param xstar feature vector (indirect k_*)
  242. * @param beta result of the calculation
  243. */
  244. void hik_kernel_sum_fast(const double *_Tlookup,
  245. const Quantization & _q,
  246. const NICE::SparseVector & _xstar,
  247. double & _beta
  248. ) const;
  249. /**
  250. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  251. * @author Erik Rodner, Alexander Freytag
  252. *
  253. * @param alpha coefficient vector
  254. * @param A pre-calculation array computed by hik_prepare_alpha_multiplications
  255. * @param B pre-calculation array computed by hik_prepare_alpha_multiplications
  256. * @param q Quantization
  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 *hik_prepare_alpha_multiplications_fast(const NICE::VVector & _A,
  262. const NICE::VVector & _B,
  263. const Quantization & _q,
  264. const ParameterizedFunction *_pf = NULL
  265. ) const;
  266. /**
  267. * @brief compute lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  268. * @author Alexander Freytag
  269. *
  270. * @param alpha coefficient vector
  271. * @param q Quantization
  272. * @param pf ParameterizedFunction to change the original feature values
  273. *
  274. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  275. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  276. */
  277. double* hikPrepareLookupTable(const NICE::Vector & _alpha,
  278. const Quantization & _q,
  279. const ParameterizedFunction *_pf = NULL
  280. ) const;
  281. /**
  282. * @brief update the lookup table for HIK calculation using quantized signals and prepare for K*alpha or k_*^T * alpha computations
  283. * @author Alexander Freytag
  284. *
  285. * @param T previously computed LUT, that will be changed
  286. * @param alphaNew new value of alpha at index idx
  287. * @param alphaOld old value of alpha at index idx
  288. * @param idx index in which alpha changed
  289. * @param q Quantization
  290. * @param pf ParameterizedFunction to change the original feature values
  291. */
  292. void hikUpdateLookupTable(double * _T,
  293. const double & _alphaNew,
  294. const double & _alphaOld,
  295. const uint & _idx,
  296. const Quantization & _q,
  297. const ParameterizedFunction *pf
  298. ) const;
  299. /**
  300. * @brief return a reference to the sorted feature matrix
  301. */
  302. FeatureMatrix & featureMatrix(void) { return X_sorted; };
  303. const FeatureMatrix & featureMatrix(void) const { return X_sorted; };
  304. /**
  305. * @brief solve the linear system K*alpha = y with the minimum kernel trick based on the algorithm of Wu (Wu10_AFD)
  306. * @note method converges slowly for large scale problems and even for normal scale :(
  307. * @author Paul Bodesheim
  308. *
  309. * @param y right hand side of linear system
  310. * @param alpha final solution of the linear system
  311. * @param q Quantization
  312. * @param pf ParameterizedFunction to change the original feature values
  313. * @param useRandomSubsets true, if the order of examples in each iteration should be randomly sampled
  314. * @param maxIterations maximum number of iterations
  315. * @param sizeOfRandomSubset nr of Elements that should be randomly considered in each iteration (max: y.size())
  316. * @param minDelta minimum difference between two solutions alpha_t and alpha_{t+1} (convergence criterion)
  317. *
  318. * @return C standard vector representing a q.size()*n double matrix and the lookup table T. Elements can be accessed with
  319. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  320. **/
  321. double *solveLin(const NICE::Vector & _y,
  322. NICE::Vector & _alpha,
  323. const Quantization & _q,
  324. const ParameterizedFunction *_pf = NULL,
  325. const bool & _useRandomSubsets = true,
  326. uint _maxIterations = 10000,
  327. const uint & _sizeOfRandomSubset = 0,
  328. double _minDelta = 1e-7,
  329. bool _timeAnalysis = false
  330. ) const;
  331. //! set the noise parameter
  332. void setNoise ( double _noise ) { this->d_noise = _noise; }
  333. //! get the current noise parameter
  334. double getNoise (void) const { return this->d_noise; }
  335. double getFrobNormApprox();
  336. /**
  337. * @brief Prepare the efficient HIK-computations for the squared kernel vector |k_*|^2 : calculate the partial squared sums for each dimension.
  338. * @author Alexander Freytag
  339. * @date 10-04-2012 (dd-mm-yyyy)
  340. */
  341. void hikPrepareKVNApproximation(NICE::VVector & _A) const;
  342. /**
  343. * @brief Compute lookup table for HIK calculation of |k_*|^2 assuming quantized test samples. You have to run hikPrepareSquaredKernelVector before
  344. * @author Alexander Freytag
  345. * @date 10-04-2012 (dd-mm-yyyy)
  346. *
  347. * @param A pre-calculation array computed by hikPrepareSquaredKernelVector
  348. * @param q Quantization
  349. * @param pf Parameterized Function to efficiently apply a function to the underlying data
  350. *
  351. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  352. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  353. */
  354. double * hikPrepareKVNApproximationFast(NICE::VVector & _A, const Quantization & _q, const ParameterizedFunction *_pf = NULL ) const;
  355. /**
  356. * @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.
  357. * @author Alexander Freytag
  358. * @date 10-04-2012 (dd-mm-yyyy)
  359. *
  360. * @param q Quantization
  361. * @param pf ParameterizedFunction to change the original feature values
  362. *
  363. * @return C standard vector representing a q.size()*d double matrix and the lookup table T. Elements can be accessed with
  364. * T[dim*q.size() + j], where j is a bin entry corresponding to quantization q.
  365. */
  366. double* hikPrepareLookupTableForKVNApproximation(const Quantization & _q, const ParameterizedFunction *_pf = NULL) const;
  367. //////////////////////////////////////////
  368. // variance computation: sparse inputs
  369. //////////////////////////////////////////
  370. /**
  371. * @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.
  372. * @author Alexander Freytag
  373. * @date 10-04-2012 (dd-mm-yyyy)
  374. *
  375. * @param A pre-computation matrix (VVector) (use the prepare method)
  376. * @param xstar new feature vector (SparseVector)
  377. * @param norm result of the squared norm approximation
  378. * @param pf optional feature transformation
  379. */
  380. void hikComputeKVNApproximation(const NICE::VVector & _A, const NICE::SparseVector & _xstar, double & _norm, const ParameterizedFunction *_pf = NULL ) ;
  381. /**
  382. * @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.
  383. * @author Alexander Freytag
  384. * @date 10-04-2012 (dd-mm-yyyy)
  385. *
  386. * @param Tlookup large lookup table
  387. * @param q Quantization object
  388. * @param xstar feature vector (indirect k_*)
  389. * @param norm result of the calculation
  390. */
  391. void hikComputeKVNApproximationFast(const double *_Tlookup, const Quantization & _q, const NICE::SparseVector & _xstar, double & _norm ) const;
  392. /**
  393. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Exploiting sparsity
  394. * @author Alexander Freytag
  395. * @date 13-04-2012 (dd-mm-yyyy)
  396. *
  397. * @param xstar feature vector
  398. * @param kstar kernel vector
  399. */
  400. void hikComputeKernelVector( const NICE::SparseVector & _xstar, NICE::Vector & _kstar) const;
  401. //////////////////////////////////////////
  402. // variance computation: non-sparse inputs
  403. //////////////////////////////////////////
  404. /**
  405. * @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.
  406. * @author Alexander Freytag
  407. * @date 19-12-2013 (dd-mm-yyyy)
  408. *
  409. * @param A pre-computation matrix (VVector) (use the prepare method)
  410. * @param xstar new feature vector (Vector)
  411. * @param norm result of the squared norm approximation
  412. * @param pf optional feature transformation
  413. */
  414. void hikComputeKVNApproximation(const NICE::VVector & _A, const NICE::Vector & _xstar, double & _norm, const ParameterizedFunction *_pf = NULL ) ;
  415. /**
  416. * @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.
  417. * @author Alexander Freytag
  418. * @date 19-12-2013 (dd-mm-yyyy)
  419. *
  420. * @param Tlookup large lookup table
  421. * @param q Quantization object
  422. * @param xstar feature vector (indirect k_*)
  423. * @param norm result of the calculation
  424. */
  425. void hikComputeKVNApproximationFast(const double *_Tlookup, const Quantization & _q, const NICE::Vector & _xstar, double & _norm ) const;
  426. /**
  427. * @brief Compute the kernel vector k_* between training examples and test example. Runtime. O(n \times D). Does not exploit sparsity - deprecated!
  428. * @author Alexander Freytag
  429. * @date 19-12-2013 (dd-mm-yyyy)
  430. *
  431. * @param xstar feature vector
  432. * @param kstar kernel vector
  433. */
  434. void hikComputeKernelVector( const NICE::Vector & _xstar, NICE::Vector & _kstar) const;
  435. /** Persistent interface */
  436. virtual void restore ( std::istream & _is, int _format = 0 );
  437. virtual void store ( std::ostream & _os, int _format = 0 ) const;
  438. virtual void clear ();
  439. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  440. // interface specific methods for incremental extensions
  441. ///////////////////// INTERFACE ONLINE LEARNABLE /////////////////////
  442. virtual void addExample( const NICE::SparseVector * _example,
  443. const double & _label,
  444. const bool & _performOptimizationAfterIncrement = true
  445. );
  446. virtual void addMultipleExamples( const std::vector< const NICE::SparseVector * > & _newExamples,
  447. const NICE::Vector & _newLabels,
  448. const bool & _performOptimizationAfterIncrement = true
  449. );
  450. /**
  451. * @brief Add a new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  452. * @author Alexander Freytag
  453. * @date 02-01-2014 (dd-mm-yyyy)
  454. *
  455. * @param example new feature vector
  456. */
  457. void addExample(const NICE::SparseVector * _example, const NICE::ParameterizedFunction *_pf = NULL);
  458. /**
  459. * @brief Add multiple new example to the feature-storage. You have to update the corresponding variables explicitely after that.
  460. * @author Alexander Freytag
  461. * @date 02-01-2014 (dd-mm-yyyy)
  462. *
  463. * @param newExamples new feature vectors
  464. */
  465. void addMultipleExamples(const std::vector<const NICE::SparseVector * > & _newExamples, const NICE::ParameterizedFunction *_pf = NULL);
  466. };
  467. } // namespace
  468. #endif