FastMinKernel.h 24 KB

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