FastMinKernel.h 24 KB

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